简体   繁体   中英

Using JQuery and AJAX to pass data to a PHP script

I have an HTML form that Is only composed of a button with a value. I would like to leave it this way. I am using AJAX/JQuery to pass the form data to a PHP script. But, for some reason, the button value is not sent. What could I be doing wrong?

HTML:

<form id="friend-send" method="post" action="">
<button type="submit" class="foll" name="approve-friend" value="4"> Approve </button>
</form>

AJAX/JQUERY:

$(document).ready(function() {

    $("#friend-send").submit(function(e) {

        var $this = $(this);        
        var dataString = $this.serialize(); 

        e.preventDefault();     

        $.ajax({  
            type: "POST",  
            url: "relate.php",  
            data: dataString,
            async: false,
            success: function() {
                $this.hide();
            }
        });             

    });

});

JQuery won't serialize a button, use a hidden field instead

 <form id="friend-send" method="post" action="">
 <input type="hidden" name="approve-friend" value="4" />
 <button type="submit" class="foll"> Approve </button>
 </form>

Also, You need to serialze the form by id, not the button by id Instead of this

 $("#friend-request-buttons")

It should be this

 $("#friend-send") 

Lastly, since you are using ajax to post, you can simplfy your form open tag to this...

 <form id="friend-send">

<button> tags are not supported by serialize https://api.jquery.com/serialize/

You would need to use an input of some kind. A hidden one would work.

Don't use serialize , create the input data yourself:

var dataString = {};
var $button = $this.find("[type=submit]");
dataString[$button.attr('name')] = $button.val();

When you provide an object as the data: argument to $.ajax , jQuery will serialize it automatically.

This answer would be if you are set on using the button alone

$(document).ready(function() {

$("#friend-send").submit(function(e) {

    var $this = $(this);        
    var dataString = "?" + $(this).find('button').attr('name') + "=" + $(this).find('button').attr('value'); 

    e.preventDefault();     

    $.ajax({  
        type: "POST",  
        url: "relate.php",  
        data: dataString,
        async: false,
        success: function() {
            $this.hide();
        }
    });             

    });

});

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