Mostrando entradas con la etiqueta ajax. Mostrar todas las entradas
Mostrando entradas con la etiqueta ajax. Mostrar todas las entradas

viernes, 10 de octubre de 2014

jueves, 25 de septiembre de 2014

Usando web services con JSON OK

Curso jQuery, Usando web services con JSON

https://www.youtube.com/watch?v=7TMt6FItfv4
http://codigofacilito.com/videos/tutorial_jquery_34_metodo_getjson

miércoles, 24 de septiembre de 2014

exceptions ajax

http://www.novogeek.com/post/Handling-AJAX-exceptions-of-ASPNET-using-jQuery.aspx

jueves, 11 de septiembre de 2014

ajax async false

            var items = [];
            var apiUrl = "/Servicio.svc/operador";

            $.ajax({
                async: false,
                url: apiUrl,
                type: "GET",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    //console.log(data.Data);
                    items = data.Data;

                },
                error: function (e) {
                    alert("Error al guardar operadores:\n");
                }
            });

enviar formulario con jquery y ajax

http://www.masquewordpress.com/enviar-formularios-con-ajax-y-jquery/

domingo, 7 de septiembre de 2014

conbinando json con serialize

http://stackoverflow.com/questions/11338774/serialize-form-data-to-json
http://css-tricks.com/snippets/jquery/serialize-form-to-json/
http://jaydson.org/serializando-um-formulario-com-jquery
http://www.cerocreativo.cl/labs/codigos/y-asi-funciona-serialize-en-jquery/
http://stackoverflow.com/questions/22742329/what-is-the-difference-between-jquery-serialize-method-vs-json-stringify
http://geekswithblogs.net/rgupta/archive/2014/06/25/combining-jquery-form-serialize-and-json.stringify-when-doing-ajax-post.aspx

Que significa asincrono en ajax

http://stackoverflow.com/questions/3393751/what-does-asynchronous-means-in-ajax

Asynchronous means that the script will send a request to the server, and continue it's execution without waiting for the reply. As soon as reply is received a browser event is fired, which in turn allows the script to execute associated actions.
Ajax knows when to pull data from server, because you tell it when to do it.

A1 parametros AJAX contentType dataType, stringify


contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: jsonhtmltext, etc. jQuery will use this to figure out how to populate the success function's parameter.
If you're posting something like:
{"name":"John Doe"}
and expecting back:
{"success":true}
Then you should have:
var data = {"name":"John Doe"}
$.ajax({
    datatype : "json",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        alert(result.success); // result is an object which is created from the returned JSON
    },
});
If you're expecting the following:
<div>SUCCESS!!!</div>
Then you should do:
var data = {"name":"John Doe"}
$.ajax({
    datatype : "html",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});
One more - if you want to post:
name=John&age=34
Then don't stringify the data, and do:
var data = {"name":"John", "age": 34}
$.ajax({
    datatype : "html",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
    data : data,
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});
share|edit

From the jQuery documentation - http://api.jquery.com/jQuery.ajax/
contentType When sending data to the server, use this content type.
dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response
"text": A plain text string.
REFERENCIA:
http://stackoverflow.com/questions/18701282/what-is-content-type-and-datatype-in-an-ajax-request 

Parametros de llamada AJAX jquery bien explicado

http://stackoverflow.com/questions/17828250/datatype-vs-contenttype-in-jquery-ajax
4 down vote accepted
dataType:
The type of data that you're expecting back from the server.
contentType:
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.
----
contentType is used to determine how the payload has to be sent to the server as request parameters or as request body.

dataType is used to tell jQuery what is the return type of the request - to determine how to process the response text before it is sent the the handler methods

http://stackoverflow.com/questions/17828250/datatype-vs-contenttype-in-jquery-ajax
*****************
From the documentation:
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: String
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.
and:

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
http://stackoverflow.com/questions/14322984/differences-between-contenttype-and-datatype-in-jquery-ajax-function
*****************

1.1 Propiedades de los llamados Ajax.

La función Ajax de JQuery recibe un JSON el cuál posee varias propiedades que enumeraremos a continuación.
  • type: Tipo de llamada que se ejecutara por defecto es GET.
  • url: Ruta a la cual se le ejecutara la llamada.
  • data: Datos que se enviaran al servidor, se envía un string con formato de JSON.
  • contentType: Tipo de datos que van a ser enviara al servidor.
  • dataType: Tipo de dato que se espera recibir desde el servidor . Jquery lo interpreta con los MIME types que el soporta. Los valores válidos para esta propiedad son los siguientes: (xml,html,script,json,jsop,text)
  • success:  Función ejecutada cuando la llamada Ajax fue satisfactoria.
  • error: Función a ser ejecutada si la llamada Ajax no fue satisfactoria.
  • async: Propiedad que define si la llamada Ajax es asíncrona o no, por defecto esta propiedad es verdadera.
Estas definiciones serán utilizadas posteriormente y es importante conocer su significado.
- See more at: http://7sabores.com/blog/consumir-un-webservice-net-jquery#sthash.vEl1KKTC.dpuf

http://7sabores.com/blog/consumir-un-webservice-net-jquery
*******************
contentType Se usa cuando se mandan datos a los servidores a modo de encabezado. String: "application/x-www-form-urlencoded" funciona perfectamente
data Se usa para especificar datos a mandar. Estos tienen la siguiente forma: foo=bar&foo2=bar2;. Si los datos a enviar son un vector(array) jQuery los convierte a varios valores con un mismo nombre (si foo["alt1","alt2"], foo="alt1"&foo="alt2";) Array / String con la forma antes mencionada. (un objeto que yo sepa tambien)
dataType Indica el tipo de datos que se van a llamar (YO: que se resiben del servidor). Si no se especifica jQuery automaticamente encontrará el tipo basado en el header del archivo llamado (pero toma mas tiempo en cargar, asi que especificalo u_u)
  • "xml": Devuelve un documento XML.
  • "html": Devuelve HTML con texto plano, y respeta las etiquetas.
  • "script": Evalua el JavaScript y devuelve texto plano.
  • "json": Evalua la respuesta JSON y devuelve un objeto Javascript 
http://www.cristalab.com/tutoriales/ajax-en-jquery-c226l/
*******************
jQuery
Nuestro último cliente será jQuery y lo cierto es que el más sencillo de todos.
La ventaja de jQuery frente a ASP.NET AJAX es que puede consumir servicios que no estén en la solución actual y además tampoco es necesario ningún cambio en el servicio web, es decir, no es necesario descomentar la línea que sí tuvimos que descomentar para trabajar con ASP.NET AJAX.
Además, para proyectos de ASP.NET MVC sólo tenemos disponible está opción
$(document).ready(function () {
    var options = {
        type: "POST",
        url: "/WebService1.asmx/Saludar",
        data: "{ 'nombre': 'Sergio' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, textStatus, jqXHR) { //do something...
        },
        error: function (jqXHR, textStatus, errorThrown) { //do something...
        }
    }
    $.ajax(options);
});

Lo más relevante del este código es:
  • Se utiliza JSON para la llamada según indica el parámetro contentType.
  • Se pasan los datos en la propiedad data, de nuevo como un objeto JSON pero en una cadena.
  • El nombre del parámetro es case-sensitive, así que nombre funcionará pero Nombre fallará.
  • Se espera que la respuesta sea en formato JSON según indica el parámetro dataType.
Si quisiéramos llamar al método SaludarPersona que recibe un objeto del tipo Persona, habría que escribir lo siguiente en la propiedad data:
data: "{ 'persona' : { 'Nombre' : 'Sergio' , 'Apellidos' : 'León' } }",

http://panicoenlaxbox.blogspot.com/2011_12_01_archive.html
**************************

sábado, 6 de septiembre de 2014

como pasar parametros el atributo data en ajax

http://stackoverflow.com/questions/15576548/jquery-how-to-pass-parameters-in-get-requests
http://stackoverflow.com/questions/3066070/using-jquery-to-make-a-post-how-to-properly-supply-data-parameter
Como enviar en formato value1=value1 &value2=value2...
http://stackoverflow.com/questions/9328743/sending-multiple-data-parameters-with-jquery-ajax

how to sent json parameters mediante el metodo get con ajax jquery
http://stackoverflow.com/questions/10948233/jquery-send-json-object-using-get-method
http://stackoverflow.com/questions/10948233/jquery-send-json-object-using-get-method

RESUELTO EL PROBLEMA DE JSON COMO PARAMETRO GET
http://techbrij.com/pass-parameters-aspdotnet-webapi-jquery
-----------
http://stackoverflow.com/questions/18697034/how-to-pass-parameters-in-ajax-post 
Try using GET method,
$.ajax({
        url: 'url',
        type: 'GET',
        data: { field1: "hello", field2 : "hello2"} ,
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            your success code
        },
        error: function () {
            your error code
        }
    }); 
You cannot see parametrs in url with POST method

-----
http://stackoverflow.com/questions/249692/jquery-wont-parse-my-json-from-ajax-query
According to the json.org specification, your return is invalid. The names are always quoted, so you should be returning
{ "title": "One", "key": "1" }
and
[ { "title": "One", "key": "1" }, { "title": "Two", "key": "2" } ]
This may not be the problem with your setup, since you say one of them works now, but it should be fixed for correctness in case you need to switch to another JSON parser in the future.
-----------

http://api.jquery.com/jQuery.ajax/
  • data
    Type: PlainObject or String or Array
    Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
    $.ajax({
    type: "POST",
    url: "some.php",
    data: { name: "John", location: "Boston" }
    })
    .done(function( msg ) {
    alert( "Data Saved: " + msg );
    });
    **************v2b
    VER el parametro data:
    $.ajax({ async:true, type: "POST", dataType: "html", contentType: "application/x-www-form-urlencoded", url:"ajaxcompleto2.php", data:"anio="+v, beforeSend:inicioEnvio, success:llegada, timeout:4000, error:problemas }); 
    ---
     
    
    
    otro en http://blog.zeion.net/2012/09/14/ejemplo-practico-de-ajax-json-con-jquery/
    pero con post ojo 
    var data = "tarea=1&cedula=" + cedula.id; 
    **************