55

I am sending an ajax request to a php file as shown here:

function checkDB(code, userid)
{

  $.ajax({
  type: "POST",
  url: "<?php bloginfo('template_url'); ?>/profile/check_code.php",
  data: 'code='+code+'userid='+userid,
  datatype: "html",
  success: function(result){

       if(result == 0)
        {
            $('#success').html( code + ' has been redeemed!');
            // alert('success');//testing purposes
        }
        else if(result == 2)
        {
            $('#err').html(  code + ' already exists and has already been redeemed....');
            //alert('fail');//testing purposes
        }else if(result == 1){
            $('#err').html(  code + ' redeem code doesnt exist');      
        }

        alert(result);      
      }
  })

}

This is sent calling the function on submit, like so:

<form method="post" class="sc_ajaxxx" id="sc_add_voucherx" name="sc_ajax"  
     onsubmit="checkDB(document.sc_ajax.sc_voucher_code.value, <?php echo $user_id ?>); return false;">
</form>

The problem is that the user id php variable is not getting sent to the check_code.php page by ajax. or at least I cant seem to echo the id back to the page.

Is this the correct way of passing multiple values to a server-side page? Without the userid passing over, it works fine just passing over the code.

Thanks guys :)

Lucky
  • 16,787
  • 19
  • 117
  • 151
JamesG
  • 2,018
  • 2
  • 28
  • 57

7 Answers7

134

Here is how POST data should be formatted:

key1=value1&key2=value2&key3=value3

In your case (note the & as a separator):

'code=' + code + '&userid=' + userid

But jQuery does that for you if you specify your data as an object:

data: { code: code, userid: userid }
Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
  • 1
    Ok thanks. How would I specify it as an object? Would this be datatype: json? – JamesG Feb 17 '12 at 13:26
  • 1
    Nope, you don't need to change your `dataType` - that's a hint to jQuery how it should interpret your response. The data it sends is by default serialized as post data, e.g. `code=17&userid=42`. You just need to change your data string into what I wrote above and it will work. – Linus Thiel Feb 17 '12 at 13:31
  • Ok that makes sense... but why woiuld you want to set your dataType to JSON then? To read in JSON specifically? – JamesG Feb 17 '12 at 15:01
  • 1
    Normally you don't need to specify a `dataType`, jQuery will figure it out based on response headers etc. In cases where it can't, and you expect it to receive e.g. JSON back, it makes sense. See [jQuery.ajax documentation](http://api.jquery.com/jQuery.ajax/). – Linus Thiel Feb 17 '12 at 15:05
  • I like the object method because it is easier to read and looks clean. – a coder Aug 08 '13 at 23:08
  • @LinusGustavLarssonThiel can we send array of data also in the same way like below 'code=' + code + '&userid=' + userid +'&array1=' + array1 is it right way to do ? – nallskarthi Mar 01 '16 at 05:59
  • @nallskarthi see the [jQuery docs](http://api.jquery.com/jquery.post/#entry-examples), use the object method above but: `data: {array1: array1}`. Might vary a little with different servers. – Linus Thiel Mar 01 '16 at 10:17
  • Thanks @Linus. Its solving the issue. – ArunDhwaj IIITH May 20 '16 at 19:48
  • @LinusGustavLarssonThiel is there another way to do this besides yr answer? in my case, I get values from a textarea, what happening is, its not getting the whole content because if the values have characters like: &, ', ", =. now, I have tried to replace them upon saving, but still I think its not efficient. the same problem may occur on other special characters I used. hope you can help me thanks – wolfQueen Jan 25 '18 at 02:38
  • @wolfQueen well, if you give jQuery.ajax the data as an object, as in the second example above, I'm pretty sure jQuery will handle the escaping of the values and make it work for you. I seem to recall it uses https://api.jquery.com/jQuery.param/ internally. – Linus Thiel Jan 26 '18 at 11:55
  • @LinusGustavLarssonThiel I have custom form using ajax, single value pass working successfully, how to pass two values with same condition, i am newbie in ajax, can i get some idea about to solve my issue : My logic : if two dop down selected the price will come [its working] along with my price how to get my shipping_weight, i have both values like price and shipping_weight, the thing is how to pass. FYI -> The price passing good, along with price how can i share my shipping weight, my code url = paste.ofcode.org/33VpD34uLS64un2KKvzrUem and ajax :url = paste.ofcode.org/ifGL2ezWmdRuPRfnEVhX2A – Gem Apr 13 '19 at 12:31
15

you should set your data like so :

data: 'code='+code+'&userid='+userid
Camille Hodoul
  • 376
  • 2
  • 13
4

you can try this :

data: 'code='+code+'&userid='+userid,

instead of

data: 'code='+code+'userid='+userid,
Poonam
  • 4,591
  • 1
  • 15
  • 20
3

usually sending your data like this helps:

data: { code: code, userid: userid }

the most important thing to not forget is to verify if the name of the variables you are sending are the same in the server side

break7533
  • 148
  • 2
  • 10
1

The answer from Linus Gustav Larsson Thiel refers, I used the following &.ajax() that triggers when a button is clicked and it works great. I could pass day, month and year parameters.

$('#convertbtn').on('click',function(){
ageddajax = $("#agedd").val();
agedmmajax = $("#agemm").val();
ageyyyyajax = $("#ageyyyy").val();
    if(ageddajax > 0 && agemmajax > 0 && ageyyyyajax >0){
    $.ajax({
        type:'POST',
        url:'ajaxDataAge.php',
        data:'agedd_id='+ageddajax +'&agemm_id='+agemmajax +'&ageyyyy_id='+ageyyyyajax,
            success:function(html){
            $('#cydivage').html(html);
            }
        });
    }   
});
Sanopotens
  • 11
  • 4
0

Try this code... it is working for me ...

<script type='text/javascript'>
$(document).ready(function(){
  $(".star").click(function(){
   var rate_value1= $(this).index(".star")+1;
    $.ajax({
    type: "POST",
    dataType: "json",
    url:  "<?php echo(rootpath()) ?>/vote.php",

data: { product_id: '<?php echo($product_id_to_permalink) ?>' , rate_value: rate_value1 }

        });
      });
    });
</script>       
Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
0
 Try this code... 
    <script>
     function quote_ajax_table(){
       var doc_name = '<?php echo $test; ?>';
       var doc_no = '<?php echo $doc_no; ?>';

$.get('quote_ajax_table.php?doc_no='+doc_no+'&doc_name='+doc_name,function(data) {
   $('.dyna').html(data);
 });
}
</script>

//in html code 
  <div class="dyna"></div>
Dee_wab
  • 1,171
  • 1
  • 10
  • 23