jpl42 jpl42 - 1 year ago 45
Ajax Question

How to POST form data to external PHP file using Javascript (Ajax)?

I am creating a web app with a login function. The server-side works (PHP file takes post input, checks it against user database and either returns

, or
). This works perfectly when just simply POSTing to the PHP file, but I need the app to silently POST the data when the form is submitted, then either alert 'Try Again' or change the page to the application's home screen (
). The Javascript I've used (and changed, and changed), is below (form:

var frm = $('#signinform');
frm.submit(function (ev) {
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function(data) {
window.location.href = "app/index.html";
}else if(data.includes("Error:Missing-Input")){
alert("Login error! You may have missed one of the fields.");
}else if(data.includes("Error:Invalid-Credentials")){
alert("Login error! You have entered your email or password incorrectly.");

The HTML form is as follows (signin.html):

<div id="container">
<h1>Sign In</h1><hr><br><br>
<form id="signinform" method="post" action="">
<div style="text-align:left; margin-left: 15px;">Email:</div><input name="email" id="email" type="email" placeholder="" required="required" /><br><br>
<div style="text-align:left; margin-left: 15px;">Password:</div><input name="password" id="password" type="password" placeholder="*********" required="required" /><br>
<br><br><input type="submit" id="login" value="Submit" /><br><br>
<p>No account? <a href="signup.html">Click here to sign up!</a></p>
<script src="formhandle.js"></script>

I know this is a duplicate of a million and one other questions, blog posts, tutorials, etc. I just cannot make anything work.

EDIT: The current JS code seems to be ignored. The form posts to itself and ignores the AJAX url. I've tried including the
tag at the top and bottom of the HTML. PreventDefault in the JS didn't make any difference either.

EDIT 2: Various changes to JS & HTML to show what more I've tried, though this now just goes straight to the remote server (still ignoring preventdefault).

Answer Source

The code in the question now works as expected. I was missing the jquery lib declaration, I've seen many questions online relating to this problem, having perfectly written Javascript but the code for some reason fails. If any such people browse this post, the fix is:

<script src=""></script>

At the bottom of the HTML page before

<script src="myScript.js"></script>