How to return PHP variables on success AJAX/jQuery POST

前端 未结 3 1250
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 00:39

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 pr

相关标签:
3条回答
  • 2020-12-15 01:01

    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); 
    
    0 讨论(0)
  • 2020-12-15 01:05

    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
      }
    });
    
    0 讨论(0)
  • 2020-12-15 01:06
    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); }
    
    0 讨论(0)
提交回复
热议问题