0

I'm experimenting with Ajax and am trying to send a 1-dimensional, non associative array from a PHP function to a calling javascript function. The array is simple stuff like:

$arr[0] = 1900-1905
$arr[1] = 1905-1911

etc. For various reasons I'm using jQuery, but I am reasonably familiar with the raw Javascript way of using Ajax but I can't seem to find a way how to process the JSON data client side using Javascript. I'm going to be calling the PHP function using a call to something like

myserver.com/myfunction.php?var1=1&var2=2&var3=3

and I know you have to use echo json_encode($arr) in the PHP function, but what do you do in the Ajax method to convert the JSON back into an array, and access the array elements? From reading some of the answers on this forum, this is the part where people fall at the hurdle.

Many thanks.

user3713442
  • 478
  • 8
  • 22
  • And where is your JavaScript code pertaining the JSON unpacking? If you're not that proficient with it after all, why not use the existing solution? – mario May 09 '15 at 18:39
  • I'm not familiar with JSON at all; its the Ajax I'm OK with. Thats why I'm asking about JSON. – user3713442 May 09 '15 at 18:41
  • Here's some info on native JSON parsing. I'm not 100 % sure what you're after, but I hope it helps. http://stackoverflow.com/questions/4935632/parse-json-in-javascript – Joel Hinz May 09 '15 at 18:45
  • Hi Joel, I know how to convert the 1-D array into a JSON format and then transfer it back from an Ajax call but I don't know what to do with it when I get the data back and how to access the array elements. I don't want to use JQuery, just native Javascript in the Ajax etc. methods. – user3713442 May 09 '15 at 18:48

2 Answers2

2

Try This

function callAjax()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) //Success
    {
        var objResponse = JSON.parse(xmlhttp.responseText); //JSON.parse Parses a string as JSON
        console.log(objResponse[0]); //1900-1905
    }
  }
xmlhttp.open("GET","myserver.com/myfunction.php?var1=1&var2=2&var3=3",true);
xmlhttp.send();
}
Samosa
  • 845
  • 7
  • 19
  • Hi Samosa, many thanks, this looks ideal. I think the problem I had was that I was looking for a name similar to the PHP json_encode function and as you're pointed out the converse Javascript version is JSON.parse. – user3713442 May 09 '15 at 20:49
  • HI Samosa, Many thanks. Apologies for my late reply, I have been away for a few weeks. – user3713442 May 25 '15 at 11:31
0

This chunk is the callback. As you can see, your problem can be resolved by a function call.

success: function(response) {
    //do something with jQuery.parseJSON
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175