BonJon
BonJon

Reputation: 799

How to get retrieve data via ajax in my case?

I have an weird issue in my php and javascript.

I have something in php like

$testData = array(
       'prop1' => true,
       'prop2' => 2,
       'name' => 'testname',
       'number' => 123
);

echo json_encode($testData);

in Javascript

 $.ajax({
    type: "GET",
    cache: false,
    async: false,
    url: phpfile,
    global: false,
    success: function(result) {
        console.log(result)
        console.log(result.prop1)
        console.log(result.prop2)
    }

I was able to get result from console.log(result) but I can't get anything from console.log(result.prop1) nor console.log(result.prop2). Did I do something wrong here?

Thanks!

Upvotes: 1

Views: 61

Answers (3)

Ash
Ash

Reputation: 1422

you encode your array in PHP to send it to Javascript, by writing json_encode($testData); so to get it on javascript side you have to use JSON.parse(yourencodedArray) by using this you are able to get values inside your array.

var data = JSON.parse(yourencodedArray);
var dat1 = data.prop1;
var dat2 = data.prop2;

JSON.parse is able to decode your encoded Array.

Upvotes: 1

Oscar Reyes
Oscar Reyes

Reputation: 4342

There are 2 ways to get json objects from ajax.

First: (Recomended) You have to define dataType property with JSON,

example:

$.ajax({
    type: "GET",
    cache: false,
    async: false,
    url: phpfile,
    global: false,
    dataType: 'JSON',
    success: function(result) {
        console.log(result)
        console.log(result.prop1)
        console.log(result.prop2)
    }
});

in this case, jQuery will process the result as JSON and then you can access it's object property, if it is not an JSON, then it will go for error event.

Second: The other way to parse the object is by using JSON.parse() function because the data you are getting is just string.

example:

$.ajax({
    type: "GET",
    cache: false,
    async: false,
    url: phpfile,
    global: false,
    success: function(result){
        var data = JSON.parse(result);
        console.log(data);
        console.log(data.prop1);
        console.log(data.prop2);
    }
});

Upvotes: 1

JulioJaavier
JulioJaavier

Reputation: 91

You have transform the json from php

success: function(result) {
  var res = JSON.parse(result)
  console.log(result)
  console.log(res.prop1)
  console.log(res.prop2)
}

Upvotes: 2

Related Questions