简体   繁体   中英

Passing data through ajax

I was following a tutorial to pass text to search through ajax, and it works good. Now I want to pass also checkboxes values. Can someone point me to the right direction? Right now I have:

             function search(){

                  var term=$("#search").val();

                  if(term!=""){
                    $("#result").html("<img src='/img/spin.gif'/ style='margin-top: 30px;'>");
                     $.ajax({
                        type:"post",
                        url:"file.php",
                        data:"q="+encodeURIComponent(term), /* encodeURI is used to escape things such as plus sign */
                        success:function(data){
                            $("#result").html(data);
                            $("#search").val("");
                         }
                      });
                  }

So, basically I figure the text is sent through the post variable "q". Let's say I have an array of checkboxes, how can I add that to the same post request?

you could use jQuery's serialize.

$('#form').submit(function(e) {

    var data  = $('#form').serialize();

    $.post('form.php',data, function(status) {
        if(status == 'success') {
            // success
        } else {
            // error
        }
    });
    e.preventDefault();
});

form.php

<?php

$search = $_POST['search'];
etc...
$.ajax({
   type:"post",
   url:"file.php",
   data: {
       q: encodeURIComponent(term), /* encodeURI is used to escape things such as plus sign */
       checkboxes: $('input[type=checkbox]').serialize()
   }
   success:function(data){
      $("#result").html(data);
      $("#search").val("");
   }
});

It will be simpler for you, if you try to serialize your data.

You didn't write how your html looks like, so let's say you have a form like this:

<form id="form">
   Search text: <input type="text" name="data[text]"/>
   <input type="checkbox" name="data[option]" /> Option 1
   <input type="submit" value="Search"/>
</form>

To send this form with ajax request, all you have to do is to serialize your form

$('#form input[type="submit"]').click(function(e) {
   e.preventDefault();

   $.post("file.php", $("#form").serialize(), function(){
       console.log('success');
   });
});

Then in your php script you can retrieve data from $_POST variable, for example $_POST['data']['text']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM