Henry Henry - 2 months ago 7
Ajax Question

Basic ajax/jquery POST failing

It's been a while since I've touched jQuery (a few years in fact) so please forgive the ignorance.

I can't get the following basic jQuery post to a PHP script to work:

<!DOCTYPE html>
<html><body>
<form id="formID">
<input name="name" type="text" id="name">
<input name="email" type="text" id="email">
<input name="mobile" type="text" id="mobile">
<div id="submitButton">Submit</div>
<div id="result"></div>
</form>

<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
$("#submitButton").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/fupload",
/*data: $("#formID").serialize(),*/
data: {name: "bob"},
success: function(resp) {
//$('#result').html(resp);
console.log(resp);
}
});
});
</script>
</body></html>


and the /fupload/index.php script:

<?php

$idInfo = "[ " . $_POST['name'] . ':' . $_POST['email'] . ':' . $_POST['mobile'] . " ]";
echo $idInfo;
return;


The PHP $_POST variables are not being defined (as per console output). Using serialize() on the actual form data also results in the $_POST vars not being defined. If I change to the GET method, then it works, but I need to post.

I'd appreciate any pointers on what stupid mistake I'm making.

Thanks

Answer

Add a / after /fupload like this:

url: "/fupload/",

This will run your code properly. If you do not use / at the end, this will send a malformed request to your php script. Since the post request values are also sent by using query string.

Complete Code:

<script>
    $("#submitButton").click(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/fupload/",
            /*data: $("#formID").serialize(),*/
            data: {name: "bob"},
            success: function(resp) {
                //$('#result').html(resp);
                console.log(resp);
            }
    });
});
</script>
Comments