Send data with Ajax and Json

1

I need to work with Ajax and Json. These 2 Codes below work together and they work, it returns the id and the name.

<script>
    function enviarDatos(){
        $.ajax({
            data:{
                id:1,
                nombre:"foto7"
            },
            type:"GET",
            datatype:"json",
            url:"listar.php"
        })
        .done(function(datos,textStatus,jqXHR){

            respuesta1.innerHTML+="ID:"+datos.id+"<br>";
            respuesta2.innerHTML+="Categoria:"+datos.categoria+"<br>";
        })

    }
</script>

$id=$_GET['id'];
$nombre=$_GET['nombre'];

$datosJson['id']=$id;
$datosJson['nombre']=$nombre;

header('Content-type: application/json; charset=utf-8');
echo  json_encode($datosJson);
exit();

But the issue is that I need that in the script where I make the ajax call the data id and name are collected from a form. And I do not know what the syntax is for doing this. When I used only Ajax without Json, I wrote:

var dataString= "datos que necesito"

And then:

$.ajax({
        data:dataString,
   })

but apparently with Json is not the right way. I have been reading information but I do not give with it. I would appreciate a little help. Greetings

    
asked by Inca 30.03.2018 в 18:05
source

1 answer

0

I leave an example of your example

 <script src="./jquery-latest.min.js"></script>
$.ajax({
    // En data puedes utilizar un objeto JSON, un array o un query string
    data: {"parametro1" : "valor1", "parametro2" : "valor2"},
    //Cambiar a type: POST si necesario
    type: "GET",
    // Formato de datos que se espera en la respuesta
    dataType: "json",
    // URL a la que se enviará la solicitud Ajax
    url: "script.php",
})
 .done(function( data, textStatus, jqXHR ) {
     if ( console && console.log ) {
         console.log( "La solicitud se ha completado correctamente." );
     }
 })
 .fail(function( jqXHR, textStatus, errorThrown ) {
     if ( console && console.log ) {
         console.log( "La solicitud a fallado: " +  textStatus);
     }
});
    
answered by 30.03.2018 / 18:22
source