Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return PHP variables on success AJAX/jQuery POST

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!

like image 256
MrPizzaFace Avatar asked Nov 03 '12 19:11

MrPizzaFace


2 Answers

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
  }
});
like image 75
Lix Avatar answered Sep 20 '22 23:09

Lix


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); }
like image 31
Svetoslav Avatar answered Sep 16 '22 23:09

Svetoslav