codenoob codenoob - 3 months ago 10x
jQuery Question

ajax set result to a variable

How can I assign results from Ajax call into a variable?

I have a drop down list. when user make a choice. I want ajax to call a PHP page to find related data from server and auto fill that into an input field.

See below code

$(document).on('change','#dropdownchoiceid', function(){
$id = 1; // passing in some variable for php to use

url: "../folder/getdata.php",
type: "POST",
data: {
'id' : $id
$result = data;

The php is working. I get the result in a object that look like this

array(1) {
object(stdClass)#5 (4) {
string(1) "2"
string(7) "20.0000"
string(14) "someinfo"
string(1) "1"

So I am trying to change the input field value with the datas I got from the server. but I get blanks in the console.log. I dont quite understand the code below. I tried it because I see this answer on stackoverflow for similar questions

$result = data;


the PHP is


//Create class Object
$mProduct = new mProduct;

$id = $_POST['id'];

$result= $mProduct->getData($id);

the model PHP page is

public function getData($id){
FROM rebate
WHERE id= :id
$this->db->bind(':id', $id);
//Assign Result Set
$result = $this->db->resultset();
return $result;


I hard-coded an array to match what your db methods returned, according to your var_dump, in your PHP page:

$arr=(object) [  "id"=> "2", "column1"=>"20.0000", "column2"=>"someinfo", column3"=>"1" ];
echo json_encode($arr, JSON_FORCE_OBJECT);

Also, I suggest that use echo instead of print_r because

print_r will also show protected and private properties of objects with PHP 5. See PHP Manual print_r

Initialize your $result variable and since it is an array with a single element you must reference it that way:


        url: "getData.php",
        type: "POST",
        data: {
            'id' : $id
        dataType: "json",
            var $result = data; // var initialize
           $('#inputid').val($result[0].column1); //$result is an array

           window.alert("Something went wrong"+data.error);

You ask: (Quote) the word data supposed to match the $result from my PHP page? is the variable on the client side that the server response gets stored in