Access JSON response in AJAX

0

I try to access the values of the response I receive through AJAX but I am not capable. The JSON that receives the function in success I think is fine, but when I access its elements these have value undefined .

If I throw in the console

console.log(data);

I get this result:

{
    "id": 83,
    "error": 0,
    "msg": "evento creado"
}

But nevertheless

console.log(data.id);

I get undefined .

AddEvent.php

$resp["id"]    = '';
$resp["error"] = '';
$resp["msg"]   = '';

try {

    $event         = new Event($title, $start, $finish, $description, $type, $color, $customer);
    $resp["id"]    = $event->newEvent();
    $resp["msg"]   = 'evento creado';
    $resp["error"] = 0;

} catch (MyException $e) {

    $resp["error"] = 1;
    $resp["msg"]   = $e->getMessage();

}

echo json_encode($resp);

JavaScript

if (btnSave.html() == "guardar evento") {
    e.preventDefault();
    //not use serialize because I need manipulate start and end
    var title = $('#event_title').val();
    //I clone 'date' because I need generate two different dates
    var finishDate = date.clone();
    var start = addTimeToDate(date, $('#event_start').val());
    var end = addTimeToDate(finishDate, $('#event_end').val());
    var description = $('#event_description').val();
    var type = $('#event_type').val();
    var customer = $('#event_customer').val();
    //prepare send to AJAX
    var send = {
        "title"       : title,
        "start"       : start,
        "finish"      : end,
        "description" : description,
        "type"        : type,
        "customer"    : customer,
    };

    $.ajax({
        url     : "addEvent.php",
        type    : "post",
        data    : send,
        success : (function (data) {
                      console.log(data);
                      console.log(data.id);
                  })
    });
    
asked by crismf 11.12.2017 в 22:17
source

2 answers

1

When returning a JSON of some API to get the data that returns you is the first parameter within the function success or in this case is a promise and is in the then() the most normal is to put as key data I leave an example greetings I hope to help you.

There are cases in which the return is a specific data and so that the ajax understands which value to return changes or adds the

 dataType: 'json'

In case you return a string you have to use the function parse() and so you can manipulate the returned data.

  

NOTE: In order to use the function parse() the string must have the structure of a JSON

var datax = JSON.parse(data)

For the example we make a console.log() of the returned

 console.log(data);

And to obtain a data within it as the title in this case:

$("p").text(data.title)//data es el retorno y title es una clave dentro de el

var root = 'https://jsonplaceholder.typicode.com';

$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  console.log(data);
 $("p").text(data.title)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
    
answered by 11.12.2017 / 22:29
source
1

If you are returning a JSON from your PHP then you must indicate to your AJAX the type of data you will receive using the% option dataType

$.ajax({
    url: "addEvent.php",
    type: "post",
    data: send,
    dataType: 'json',
    success: function(data){
        console.log(data);
        console.log(data.id);   
    }
});
    
answered by 11.12.2017 в 22:24