0

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
        $.ajax({

            url: "../folder/getdata.php",
            type: "POST",
            data: {
                'id' : $id
            },
            success:function(data){
                $result = data; 
                console.log($result);
                $('#inputid').val($result.column1);
                $('#inputid2').val($result.column2);
            }
        });

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

array(1) {
  [0]=>
  object(stdClass)#5 (4) {
    ["id"]=>
    string(1) "2"
    ["column1"]=>
    string(7) "20.0000"
    ["column2"]=>
    string(14) "someinfo"
    ["column3"]=>
    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

success:function(data){
                $result = data; 

            }

the PHP is

<?php

//Create class Object
$mProduct = new mProduct;

$id = $_POST['id'];

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

the model PHP page is

public function getData($id){
    $this->db->query("
    SELECT 
    *
    FROM rebate
    WHERE id= :id
    ");
    //bind
    $this->db->bind(':id', $id);
    //Assign Result Set
    $result = $this->db->resultset();
    return $result;
}
codenoob
  • 539
  • 1
  • 9
  • 26
  • Could you show the code returning the data from server-side (PHP)? – Erik Engervall Jul 06 '16 at 00:22
  • http://stackoverflow.com/questions/26668290/jquery-javascript-store-ajax-jsonp-response-into-variables I tried solution on this page, does not seem to change anything – codenoob Jul 06 '16 at 00:59

3 Answers3

1

To receive data on front end, the PHP page has to print something, preferably in JSON format. Try this:

<?php

//Create class Object
$mProduct = new mProduct;

$id = $_POST['id'];

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

print_r(json_encode($result));
Erik Engervall
  • 269
  • 1
  • 8
  • Hi Erik, it is getting close. the console shows the result if I print_r the $result in PHP page, with json encode I get same info in a different format. but my javascript is not doing anything – codenoob Jul 06 '16 at 00:38
  • Hm, perhaps you need to use JSON.parse(data) on front end, give it a try. – Erik Engervall Jul 06 '16 at 00:40
  • I get Uncaught SyntaxError: Unexpected token A. if I put json.parse(data) in the $result = data part. – codenoob Jul 06 '16 at 00:43
  • Try adding 'dataType': 'json' to your $.ajax call – Erik Engervall Jul 06 '16 at 00:45
  • does not seem to change anything. also success:function(data){ $result = data; } where is the data coming from. is the word data supposed to match the $result from my PHP page? – codenoob Jul 06 '16 at 00:54
  • hm strange :/ "data" is simply the return value from the success function, it can be named anything – Erik Engervall Jul 06 '16 at 01:02
1

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" ];
$arr=array($arr);
//var_dump($arr);
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:

$.ajax({

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

        },
        error:function(data){
           window.alert("Something went wrong"+data.error);
        }
    });

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

P. Eastman
  • 46
  • 5
0

I am OP answering my own question.

Get data from php array - AJAX - jQuery

after checking above post. here is the answer

so the final working code look like this

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

        url: "../folder/getdata.php",
        type: "POST",
        data: {
            'id' : $id
        },
        datatype: "json",
        success:function(data){
            $result = data; 
            console.log($result);
            $('#inputid').val($result.column1);
            $('#inputid2').val($result.column2);
        }
    });

in PHP

add one more line

echo json_encode($result);
Community
  • 1
  • 1
codenoob
  • 539
  • 1
  • 9
  • 26