Laurent
Laurent

Reputation: 1563

Ajax request, fetch JS array and make it available

I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.

I have a PHP file that echoes the following:

[["content11", "content12", "content13", "content14","content15"], 
 ["content21", "content22", "content23", "content24","content25"]]

I'm using a simple Ajax get to retrieve the data:

$.ajax({
      type: "GET",
      url: myUrlToPhpFile,
      dataType: "html",
      success : function(data) 
          {
              result = data;
              alert (result);

          }
    });

The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.

Is there something I should do to make JS understand it's a JS array?

I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)

Thanks Laurent

Upvotes: 0

Views: 94

Answers (3)

Larionov Nikita
Larionov Nikita

Reputation: 117

In you php file you need check that your arrays echos with json_encode.

echo json_encode($arr);

And in your javascript file:

$.ajax({
  type: "GET",
  url: myUrlToPhpFile,
  dataType: "html", // json
  success : function(data) 
      {
         var res = JSON.parse(html);
         alert(html); // show raw data
         alert(res); // show parsed JSON
      }
});

Upvotes: 1

Vala
Vala

Reputation: 5674

@Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.

$.getJSON(myUrlToPhpFile, function(result) { ... });

This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.

Upvotes: 1

Rho
Rho

Reputation: 380

You can use JSON.parse to format the string back into an array.

JSON.parse(result)[0]

or

var result = JSON.parse(result);
result[0];

Upvotes: 1

Related Questions