How to return PHP variables to AJAX / jQuery POST success

How to use AJAX to return a variable in PHP? I am currently using echo in my controller to display the price of a dropdown .change at a div price.

However, I have a hidden field in which I need to return the row identifier for the change. How to assign return var in jQuery so that I can repeat 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 every time the form changes. "/">

Thanks for the help!

+7
source share
3 answers

Well ... One option is to return a JSON object. To create a JSON object in PHP, you start with an array of values ​​and 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 will need to tell your $.ajax call that you expect some JSON return values, so you specify another parameter - dataType : 'json' . Now your return 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 } }); 
+15
source
 echo json_encode($RESPONDE); exit(); 

The output does not display other things than the answer. RESPONDE is good for an array or object. You can access it in

 success: function(data) { data } 

data is an array of response or whatever you echo. For example...

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

in jquery

 success: function(data){ alert(data.some_key); } 
+1
source

If u returns only one value from php respone in ajax, then u can set its hidden feild using val method

 $("#hidden_fld").val(return_val); 
+1
source

All Articles