Trombone0904
Trombone0904

Reputation: 4258

get array of php function call with Ajax

I am working with php and call a php function with ajax:

<button onclick="loop()">Do It</button>

function loop() {
  $.get("ajax.php", {
     action: "true"
   },
   function(result) {
      $("input").val(result);
   });
}

PHP

if (isset($_GET["action"])) {     
   for ($i = 0; $i < 5; $i++) {
      $array[] =  array( "Value 1", $i  );
   }
   echo $array;
}

My Input value will show this:

enter image description here

Now I would like to show the first array element. I modify the code like this:

 $("input").val(result[0][0]);

My result:

enter image description here

But it has to be "Value 1"

Here is an overview of my array structure:

Array
(
    [0] => Array
        (
            [0] => Value 1
            [1] => 0
        )

    [1] => Array
        (
            [0] => Value 1
            [1] => 1
        )

    [2] => Array
        (
            [0] => Value 1
            [1] => 2
        )

    [3] => Array
        (
            [0] => Value 1
            [1] => 3
        )

    [4] => Array
        (
            [0] => Value 1
            [1] => 4
        )

)

Upvotes: 0

Views: 69

Answers (1)

xjmdoo
xjmdoo

Reputation: 1736

You'll need to return a format that javascript understands like JSON.

echo json_encode($array);

Then jQuery has a convenience method to automatically parse the returned JSON string:

$.getJSON("ajax.php", ...

Now result will be a javascript array in your ajax response.

Upvotes: 1

Related Questions