Jump to content

Handle form with AJAX & PHP


Spunky

Recommended Posts

I am trying to use AJAX to run some PHP code and I have it working but I am not sure how to send my form information to the PHP code. I have used this PHP code before with a form but that's used something like "onsubmit="thankyou.php" where the PHP page was just like a landing page that the user reviews the information that they sent. Now that I am using AJAX, this is what I have so far:

 

HTML:

<form id="contact_form" onsubmit="submitForm();">
        <p id="fname" class="form_items">
           <input type="text" name="fname" id="fname" placeholder="First Name" required />
	</p>
	<p id="lname" class="form_items">
	   <input type="text" name="lname" id="lname" placeholder="Last Name" required />
	</p>
	<p id="email" class="form_items">
	   <input type="email" name="email" id="email" placeholder="Email" required />
	</p>
	<p id="phone" class="form_items">
	   <input type="tel" name="phone" id="phone" placeholder="Telephone" />
	</p>
	<p id="comments" class="form_items">
	   <textarea rows="4" cols="50" placeholder="Comments"></textarea>
	</p>
	<p>
	   <button class="submit" type="submit">Submit</button>
	</p>
</form>

JS:

function submitForm(){
    var xmlhttp = new XMLHttpRequest();
	
    xmlhttp.onreadystatechange = function(){
	if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
	    retrieve = xmlhttp.responseText;
	}
    }

    xmlhttp.open("POST","submit_form.php");
    xmlhttp.send();
}

PHP(submit_form.php):

$ToEmail = 'email@email.com'; 

$EmailSubject = 'Site contact form'; 

$mailheader = "From: ".$_POST["email"]."\r\n"; 

$mailheader .= "Reply-To: ".$_POST["email"]."\r\n"; 

$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; 

$MESSAGE_BODY = "Name: ".$_POST["firstName"].""; 

$MESSAGE_BODY .= "Email: ".$_POST["email"].""; 

$MESSAGE_BODY .= "Comment: ".nl2br($_POST["message"]).""; 

mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");

I am receiving an email, but everything is blank. I am not seeing any errors in my console or anything. Nothing happens when the form is submitted otherwise.

 

A little background on what I am trying accomplish:

I have a contact form appearing in a homemade modal (not bootstrap) where the user can fill it out and then submit without being sent to a landing page.

Link to comment
Share on other sites

HTML:

	<form id="contact_form">
	    <p id="fname" class="form_items">
	        <input type="text" name="fname" id="fname" placeholder="First Name" required />
	    </p>
	    <p id="lname" class="form_items">
	        <input type="text" name="lname" id="lname" placeholder="Last Name" required />
	    </p>
	    <p id="email" class="form_items">
	        <input type="email" name="email" id="email" placeholder="Email" required />
	    </p>
	    <p id="phone" class="form_items">
	        <input type="tel" name="phone" id="phone" placeholder="Telephone" />
	    </p>
	    <p id="comments" class="form_items">
	        <textarea rows="4" cols="50" name="message" placeholder="Comments" id="message"></textarea>
	    </p>
	    <p>
	        <button class="submit" type="submit" onclick="submitForm();">Submit</button>
	    </p>
	    <span id="status"></span>
	</form>

JS:

function submitForm(){
	var xmlhttp = new XMLHttpRequest();

	var fn = document.getElementById('fname');
	var ln = document.getElementById('lname');
	var e = document.getElementById('email');
	var p = document.getElementById('phone');
	var m = document.getElementById('message');

	var userdata = "firstname="+fn+"&lastname="+ln+"$email="+e+"&phone="+p+"&message="+m;

	xmlhttp.open("POST","submit_form.php",true);

	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	
	xmlhttp.onreadystatechange = function(){
		if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
			retrieve = xmlhttp.responseText;
			document.getElementById("status").innerHTML = retrieve;
		}
	}

    xmlhttp.send(userdata);
    document.getElementById("status").innerHTML = "processing...";
}

PHP(submit_form.php):

$ToEmail = 'email@email.com'; 

$EmailSubject = 'Site contact form'; 

$mailheader = "From: ".$_POST["email"]."\r\n"; 

$mailheader .= "Reply-To: ".$_POST["email"]."\r\n"; 

$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; 

$MESSAGE_BODY = "Name: ".$_POST["first"].""; 

$MESSAGE_BODY .= "Email: ".$_POST["email"].""; 

$MESSAGE_BODY .= "Comment: ".nl2br($_POST["message"]).""; 

mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");

So now what is happening is that the first time I hit the submit button, my modal closes and reopens, I see "processing..." appear briefly as this happens, but nothing gets sent to email and when the modal reappears there is no status text. When I fill the form out again however, "processing..." shows up briefly then disappears and I have an email. However, this is the contents of the email:

 

Name: Email: Comment: [object HTMLTextAreaElement]

 

There is no updated status text at this time.

 

I assume the modal closing and reopening may be a modal specific issue? Even so, anyone have any ideas why this is happening?

 

But I am sure the modal issue isn't hindering the PHP issue. I am unsure why the data is still not sending properly, or why it is showing what it is for the Comments. Any ideas? Is there suppose to be status text at this time?

Link to comment
Share on other sites

var userdata = "firstname="+fn+"&lastname="+ln+"$email="+e+"&phone="+p+"&message="+m;

the name you need to use on php side is $_post["firstname"] instead of $_post["first"].

Edited by john_jack
Link to comment
Share on other sites

$email instead of &email?

 

 

var userdata = "firstname="+fn+"&lastname="+ln+"$email="+e+"&phone="+p+"&message="+m;

the name you need to use on php side is $_post["firstname"] instead of $_post["first"].

 

 

 

2 typos.. this is what I get for staying up till midnight trying to get this to work... :facepalm:

 

ok so this is what I am getting sent to my email now:

 

Name: [object HTMLParagraphElement]Email: Comment: [object HTMLTextAreaElement]

 

I am not sure why email is still not showing anything.

 

Also I realized I was supposed to add .value to the ends like this:

	var fn = document.getElementById('fname').value;
	var ln = document.getElementById('lname').value;
	var e = document.getElementById('email').value;
	var p = document.getElementById('phone').value;
	var m = document.getElementById('message').value;

But that didn't do anything.

 

Still, the #1 issue is that the first time I press submit it just reopens the modal the form is in and then it is the second time that it submits. I can try to take it out of the modal and see if that changes anything but either way, I really need it inside the modal. --turns out getting rid of the form fixed this, no need for it I guess anyways since I am not using "onsubmit".

 

EDIT: I am trying to troubleshoot this. When I alert any one of the variables (fn, ln, e, etc) it is undefined and I am not sure why. My JS is located at the bottom of the page before the end body tag so I don't think I need a document ready function but I have tried implementing one which just seems to make it worse.

 

EDIT: Alright this is starting to tick me off.. this is the SIMPLEST JavaScript that I am unable to get to work, I even tried to put it on JsFiddle for a more clear picture and even THAT I can't get to work...https://jsfiddle.net/k1g9dq7w/ :fool: -- but anyway this is the code I am currently trying to debug.. simple.. basic.. maybe at this point I should go to the JS forum with this I don't know.

 

^^^ Ok it seems that if the input is not in a modal, the JS will retrieve the value no problem. I know this is a JS question now, so I am just going to take this to the JS Forums, instead, I have tested this manually by doing:

var userdata = "firstname=MyName&lastname=MyLastName&email=email@email.com&phone=123&message=message";

and now this works. So, the code works. I thank you. I will have to figure out my other issue.

Edited by Spunky
Link to comment
Share on other sites

I would think the form is submitting to its self, you need to disable this which you already have done, but with maybe preventDefault() or using return false, try reestablishing form as before but instead of button use another temporary element (div or span) with onclick function which will not cause the form to submit, if it works with this, you know that the form being submitted is the problem.

Link to comment
Share on other sites

this is why it wouldnt work

<p id="fname" class="form_items">
           <input type="text" name="fname" id="fname" placeholder="First Name" required />
	</p>

you are using the same id twice once for <p> and second for the <input> . id is supose to be unique .

set all your <p> ids to diferent values than <input> id . good luck

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...