0

I have PHP function:

public function doit()
{
    $arr1= array();
        $arr1['index1'] = 'value1';
            $arr1['index2'] = 'value2';
}

I call it from my JQuery function:

$.ajax
({    
    url: "/controller/doit",  
    success: function()
    { 
        alert('done!'); 
    }  
 });  

Everything I want is - that my JQuery function, which contains this ajax call will return me the array, which is identical to the one, which PHP function returned (the only difference is language of course: JS instead of PHP)

1
  • public function doit() { $arr1= array(); $arr1['index1'] = 'value1'; $arr1['index2'] = 'value2'; } Commented Dec 3, 2012 at 2:02

3 Answers 3

2

You need to return something from your doit function.

public function doit()
{
  $arr1= array();
  $arr1['index1'] = 'value1';
  $arr1['index2'] = 'value2';

  echo json_encode($arr1);
}


$.ajax
({    
  url: "/controller/doit",  
  success: function(data)
  { 
    console.log(data); 
  }  
});  

Edit:

Jquery to PHP: When the javascript is run, it will send the data array to the server using the url. The server receives the array, encodes it as json and sends it back to the success callback function which will log the data to the console.

// YOUR JAVASCRIPT FILE
// your data to send.
var data = {'index1': 'value1', 'index2': 'value2'};

$.ajax({
  type: 'POST',
  url: '/controller/doit',
  data: data,
  success: function(data) { console.log(data) },
  dataType: 'json'
});


//YOUR PHP FILE
public function doit()
{ 
   // you should be setting your content type header to application/json if sending json
   header('Content-type: application/json');
   echo json_encode($_POST['data']);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, but I want to create javascript array from this JSON, normal array and return it in the function - how to do it?
Ah right, in that case, use an ajax call. Ill add an edit to my answer.
0

You can echo the array as json from php using:

echo json_encode($arr1);

And use $.getJSON in your JS:

$.getJSON('/controller/doit', function(data) {
  console.log(data);
});

2 Comments

Hey, but I want to create javascript array from this JSON, normal array and return it in the function - how to do it?
getJSON will parse the json for you. Did you try console.log(data). It will be a js array
0

you can use JSON to encode your array. http://php.net/manual/en/function.json-encode.php

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.