Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ajax to call php and return multiple variables?

I am trying to use javascript to call a php script which then will return multiple variables back to my javascript so I can manipulate them.

This is my JS.

                $.ajax({ 
                    url: 'test.php',
                    data: { id : lastFileId },
                    success: function(output) {
                        alert(output);
                    }
                });

my PHP

<?php
    $fileId = ($_GET['id']);
    $num1 = 1;
    $num2 = 2;

?>

From here, how can I return variables $num1 and $num2 so i can use them in my javascript. Is it possible?

also this is a very basic idea of what I have planned to do if I can achieve this.

like image 637
Joe Avatar asked Nov 28 '22 13:11

Joe


2 Answers

You can return as many variables as you want with json_encode().

Try in your PHP:

<?php
echo json_encode(array($num1, $num2));
?>

You can add to that array , $num3, $num4, ... and so on.

In your JS, you can access each number as follows.

First, you will need this line of code to parse the encoded JSON string, in your success function.

var result = $.parseJSON(output);

That sets result as a JSON object. Now you can access all fields within result:

  • result[0] -- $num1 in PHP
  • result[1] -- $num2 in PHP
like image 66
geoff Avatar answered Dec 09 '22 19:12

geoff


You can go for Json in PHP and javascript if you want array in response for a ajax request

PHP Code

<?php
    $fileId = isset($_GET['id'])?$_GET['id']:0;
    echo json_encode(array("field"=>$fileId,"num1"=>1,"num2"=>2));
?>

Js Code

jQuery.ajax({
    type: "GET",
    url: 'test.php',
    dataType: "json",
    success: function(response) {
        console.log(response);
        alert(response.num1);
    }
});
like image 41
Santosh Yadav Avatar answered Dec 09 '22 21:12

Santosh Yadav