Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  42] [ 6]  / answers: 1 / hits: 28729  / 10 Years ago, wed, april 2, 2014, 12:00:00

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.


More From » php

 Answers
17

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


[#71650] Tuesday, April 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;