8

How do I use AJAX to return a variable in PHP? I am currently using echo in my controller to display a price on dropdown .change in a div called price.

However I have a hidden field which I need to return the row id to on change. How do I assign the return var in jQuery so that I can echo it in my hidden field?

jQuery

$(document).ready(function() {
    $('#pricingEngine').change(function() {
         var query = $("#pricingEngine").serialize();
         $('#price').fadeOut(500).addClass('ajax-loading');
         $.ajax({
             type: "POST",
             url: "store/PricingEngine",
             data: query,
             success: function(data)
             {
                  $('#price').removeClass('ajax-loading').html('$' + data).fadeIn(500);
             }
         });
    return false;
   });

});

Controller

function PricingEngine()
{
    //print_r($_POST);
    $this->load->model('M_Pricing');
    $post_options = array(
      'X_SIZE' => $this->input->post('X_SIZE'),
      'X_PAPER' => $this->input->post('X_PAPER'),
      'X_COLOR' => $this->input->post('X_COLOR'),
      'X_QTY' => $this->input->post('X_QTY'),
      'O_RC' => $this->input->post('O_RC')
                          );

    $data = $this->M_Pricing->ajax_price_engine($post_options);

    foreach($data as $pData) {
        echo number_format($pData->F_PRICE / 1000,2);
        return $ProductById = $pData->businesscards_id;
    }
}

View

Here is my hidden field I want to pass the VAR to every-time the form is changed. " />

Thanks for the help!

MrPizzaFace
  • 7,807
  • 15
  • 79
  • 123

3 Answers3

16

Well.. One option would be to return a JSON object. To create a JSON object in PHP, you start with an array of values and you execute json_encode($arr). This will return a JSON string.

$arr = array(
  'stack'=>'overflow',
  'key'=>'value'
);
echo json_encode($arr);

{"stack":"overflow","key":"value"}

Now in your jQuery, you'll have to tell your $.ajax call that you are expecting some JSON return values, so you specify another parameter - dataType : 'json'. Now your returned values in the success function will be a normal JavaScript object.

$.ajax({
  type: "POST",
  url: "...",
  data: query,
  dataType: 'json',
  success: function(data){
    console.log(data.stack); // overflow
    console.log(data.key);   // value
  }
});
Lix
  • 47,311
  • 12
  • 103
  • 131
  • I implemented your suggestion. It seems to be working but having some issues.. Please see new question http://stackoverflow.com/questions/13213361/getting-undefined-response-from-jquery-ajax-form-post Thanks! ;) – MrPizzaFace Nov 03 '12 at 20:51
  • how to get this string into php variable? – 151291 Nov 03 '15 at 08:37
  • @151291 - In my example, the data inside the `query` variable will arrive inside the `$_POST` variable when this code executes the `AJAX` request. – Lix Nov 03 '15 at 09:34
  • @151291 - it's really not clear what you are asking.. Please open a new post (if you can't find an answer on an already existing question). – Lix Nov 03 '15 at 10:09
  • @151291 - without seeing the code you are using it's quite difficult to make suggestions. This is why I suggested opening a new post to solve your problem. – Lix Nov 03 '15 at 11:08
  • ok ok i got answer ... json elements having numeric index 0 like this `["0":{"id":"1001","full_name":"raju "}]` , all elements in 0th index. i got it while writing `document.write(result)` without write `dataType: 'json'`. – 151291 Nov 03 '15 at 11:46
  • what is the advantage of using `console.log` and how can i access this json data into php script, I tried `$_POST['stack']` but not able to access, plus i tried `var_dump($_POST['stack'])` shows undefined index. – 151291 Dec 22 '15 at 08:26
  • controller returns json encoded object, how can i get this object into php script?, it means how can i pass an json object from ajax success function into php script – 151291 Dec 22 '15 at 09:02
1
echo json_encode($RESPONDE);
exit(); 

The exit is not to display other things except answer. RESPONDE is good to be array or object. You can access it at

success: function(data)
             { data }

data is the responde array or whatever you echo.. For example...

echo json_encode(array('some_key'=>'yesss')); exit();

at jquery

success: function(data){ alert(data.some_key); }
Svetoslav
  • 4,686
  • 2
  • 28
  • 43
  • controller returns json encoded object, how can i get this object into php script?, it means how can i pass an json object from ajax success function into php script – 151291 Dec 22 '15 at 09:03
  • @151291 to start any PHP action you have to make new request so you have to make again ajax.. But its not logical 1 ajax to trigger 2nd ajax to the same script, its better to put your logic in the 1st script which you trigger with ajax request, and there to run the 2nd logic which you want to add. (If its possible of course.. else you have to make a new ajax request) – Svetoslav Dec 22 '15 at 09:21
  • json.decode() is not PHP function. Please go to PHP.net and search for JSON handling the documentation is full and you will understand it. I am not teacher. – Svetoslav Dec 22 '15 at 10:13
  • Ya its my mistake, not `json.decode` its `json_decode()`, so this is php function right? – 151291 Dec 22 '15 at 10:16
  • from your answer, how can i get `data` values into php script if it is object. – 151291 Dec 22 '15 at 10:30
1

if u are returning only single value from php respone to ajax then u can set it hidden feild using val method

$("#hidden_fld").val(return_val); 
bensiu
  • 24,660
  • 56
  • 77
  • 117
mohan.gade
  • 1,095
  • 1
  • 9
  • 15