简体   繁体   中英

Why isn't my form working correctly when trying to post something using Ajax and an external PHP file, which is receiving two strings?

So basically I'm trying to use Ajax to work with a PHP file and post both inputs (fullname and phonenumber), but it doesn't seem to be working when I try and click the submit button it only refreshes.

Here's my code, it's all on the HTML file:

HTML:

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style2.css" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function validateForm () {
var x=document.forms["myForm"] ["fullname"].value;
if (x==null || x=="")
{
alert ("First name must be filled out");
return false;
}
var x=document.forms["myForm"] ["phonenumber"].value;
if (x=null || x=="")
{
alert ("Please enter a phone number");
return false;
}
function isNumberKey(evt) {
var e = evt || window.event; //window.event is safer,
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 47 || charCode > 57))
return false;
if (e.shiftKey) return false;
return true;
}
</script>
<script>
$.ajax({
type: "POST",
url: "http://www.bmoseley.com/ajax/addrecord.php",
data: "fullname=" + fullname + "&phonenumber=" + phonenumber,
success: function(){
alert("Name and phone number added successfully!");
}
});
$("#displayInfo").load("http://www.bmoseley.com/ajax/listrecords.php");  
}
</script>
</head>
<body>
<div id="wrap">
<div id="wrapper">
<div id="info">
<form name="myForm" action="#" onSubmit="return validateForm ()">
<table border="0">
<tr>
<td><input id="fullname" name="fullname" maxlength="50" type="text" name="fullname" placeholder="Name" action="#"></td>
</tr>
<tr>
<td><input id="phonenumber" name="phonenumber" maxlength="10" onkeypress="return isNumberKey(event)" placeholder="Phone Number"></td>
</tr>
<tr>
<td><input class="button" type="submit" value="Submit"></td>
</tr>
</table>
</form>
</div>
<div id="displayInfo">
<script>
$(document).ready(function(){
$("#displayInfo").load("http://www.bmoseley.com/ajax/listrecords.php");
});
</script>
</div>
</div>
</div>
</div>
</body>
</html>

Sorry for the messy code. Hope someone can help!

You need to sent the ajax request on the form submit, your code does it while page is loading.

Remove the inline submit handler onSubmit="return validateForm ()" and try

jQuery(function () {
    //register a form submit event handler
    $('form').submit(function (e) {
        //stop the default form submission
        e.preventDefault();

        //validations, use jQuery selectors to get the input elements
        var fullname = $('#fullname').val();
        if (fullname == '') {
            alert("First name must be filled out");
            return;
        }
        var phonenumber = $('#phonenumber').val();
        if (phonenumber == '') {
            alert("Please enter a phone number");
            return;
        }

        //if validations are successful then send the ajax request
        $.ajax({
            type: "POST",
            url: "http://www.bmoseley.com/ajax/addrecord.php",
            data: "fullname=" + fullname + "&phonenumber=" + phonenumber,
            success: function () {
                alert("Name and phone number added successfully!");
            }
        }).always(function () {
            //once ajax request is completed reload the list
            $("#displayInfo").load("http://www.bmoseley.com/ajax/listrecords.php");
        });
    })
})

function isNumberKey(evt) {
    var e = evt || window.event; //window.event is safer,
    var charCode = e.which || e.keyCode;
    if (charCode > 31 && (charCode < 47 || charCode > 57)) return false;
    if (e.shiftKey) return false;
    return true;
}

It seems that @Arun has already the answer on your question only an additional information to you because I saw your comment on his answer.

If the console says jquery is not defined maybe you did not include the library on your file, you may do it so by

//referencing it on google_codes like
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>


//or downloading the framework at [jquery][1] and include to your file like
<script type = "text/javascript" src = "path where you paset the downloaded file"></script>

hope it hepls :)

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