Return data from a php server using AJAX

3

Greetings, I am doing a simple test, it is about sending a data through AJAX to PHP so that I can return a data, but I do not know why it does not return any data. The JavaScript code is as follows:

$(document).ready(function(){

        $("#login").submit(function(){

            var data_form=$(this).serialize();

            $.getJSON("login2.php", data_form, procesar_datos);

            return false;

        });

});

function procesar_datos(devueltos){

            $("#contenidos_externos").html("<p>" + devueltos.edad + "</p>");

}

And the PHP script the following

$user = $_GET['usuario'];

$el_array = new stdClass();

if ($user=="Name") {

    $el_array->Nombre = "Name";
    $el_array->Apellido = "Gómez";
    $el_array->Edad = "18";
    $json = json_encode($el_array);
    echo $json;


}
    
asked by Brian Hernandez 19.09.2017 в 01:13
source

2 answers

2

Did you try adding the json header in the php? Is that all the Php code you use? you are missing this

header('Content-Type: application/json');
    
answered by 19.09.2017 / 01:32
source
3

We will write the jQuery code as indicated in the documentation , handling the answers by done and fail .

We will also use updated code. For example, document.ready is obsolete from jQuery 3 ( see this question )

As for PHP, we have to give it all the possibilities. What if an error occurs? The PHP must send in any case a valid json, which must be evaluated in the response.

It can not be assumed that the code will always work as expected, there may be erroneous data and that must be controlled always . Your code does not establish any control over it.

Let's see:

jQuery

    $(function() {
        var data_form={usuario:"Name"}; //usé una variable data_form temporal
        //$(this).serialize();

        var peticion = $.getJSON( "login2.php", data_form, function(data) 
        {
            console.log( "Petición enviada" );
        })

        .done(function(data) 
        {
            console.log( data);

            // Creamos una variable y evaluamos data
            var txtHTML;

            if (!data.Error)
            {

                txtHTML=data.Edad ;

            }else{

                txtHTML=data.Error ;

            }
            //Presentamos la variable según lo ocurrido
            $("#contenidos_externos").html("<p>" + txtHTML + "</p>");

        })

        .fail(function() 
        {
            console.log( "error en la petición ajax" );
        })     

    });

PHP

PHP evaluates:

  • If there is actually a variable usuario in GET
  • Yes% co_of%
  • Whatever happens, create a json with information about what happened on the server side. Then, in the $user = Name part of Ajax you will read the json to determine what is in it, for example, if there is an error, print the error message, and if there is no error, print the data of the person.

    <?php
    
    
        $user = $_GET['usuario'];
    
        // Hay que evaluar todas las posibilidades ...
        // No podemos suponer que todo funciona como debería funcionar
        if(!empty($user)) 
        {
            $el_array = new stdClass();
    
            if ($user=="Name") 
            {
                $el_array->Nombre = "Name";
                $el_array->Apellido = "Gómez";
                $el_array->Edad = "18";
    
            }else{
    
                $el_array->Error = "No existe la persona $user";
            }
    
        }else{
    
            $el_array->Error = "El dato Name no existe en la petición";
    
        }
    
        $json = json_encode($el_array);
        header('Content-Type: application/json');
        echo $json;
    
    ?>
    

    HTML

    <div id="contenidos_externos"></div>
    

    Test

    I throw this at the console:

    [Log] Petición enviada (test.php, line 17)
    [Log] {Nombre: "Name", Apellido: "Gómez", Edad: "18"} (test.php, line 22)
    

    And the age appears on the page.

    Also try erroneous data and you will see that the code will always work.

    I hope it serves you.

        
    answered by 19.09.2017 в 02:15