0

How can I send 2 arrays to JavaScript and use them in another part of the JavaScript file? (sorry I'm a newbie and struggling all evening with this question)

I have a php file with 2 arrays. In the JavaScript I have an ajax request to get the arrays. But I can return only one. And I cannot save the output so I can for each it later.

//Get arrays

 $.ajax(
 {
   type: 'get',
   url: '../classes/bestanden_overzicht_client.php',
   data: "id="+id,
     success:function(data)//we got the response of ajax :)
     {
    <-- how can i target the 2 arrays and send them to function below --> 
     },
     error:function(data)
     {
     //no respons show error.
     alert  ("error!");
     alert(JSON.stringify(data)) //we give an alert of the error when there is no respons from ajax
     ;}
});

("#images").fileinput({
        uploadAsync: false,
        overwriteInitial: false,
initialPreview: [

<-- want here the output of the array1


],
intialConfig [

<-- Want here the output of array2

]



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$array1 = array();
$array2 = array();

$array1[0] = "numbers"; 
$array1[1] = "letters"; 

$array2[0] = "forname"; 
$array2[0] = "surname"; 

echo json_encode($array1);
echo json_encode($array2);
?>
8
  • 1
    put it in one "big master" array, then encode it. $return = ["array1"=>$array1, "array2"=>$array2]; then echo json_encode($return); Commented Sep 14, 2017 at 21:03
  • then you'll have it in javascript there: var array1 = data.array1; Commented Sep 14, 2017 at 21:04
  • thnx and how can i use the output outside the ajax request? Commented Sep 14, 2017 at 21:05
  • BUT you need to get rid of the <script...> in your php file! this way javascript gets confused.... "unexpected character" Commented Sep 14, 2017 at 21:06
  • 1
    You have to put all the code that uses the response into the success: function. You can't use it in other parts because AJAX is asynchronous. Commented Sep 14, 2017 at 21:11

1 Answer 1

3

You can only send one json encoded object to javascript. To solve that, put your two arrays into one array, then encode that and send it back:

$return = ["array1"=>$array1, "array2"=>$array2]; 
echo json_encode($return);

you'll be able to access it in your ajax call there:

//..
success: function(data) {
    var array1 = data.array1;
},
//...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.