HTML form post to PHP call using AJAX - php

I'm trying to POST and email address entry from a HTML form to a PHP script to store the result in a database. The script is also responsible for firing an error message should the user enter an invalid email address etc. I would like the whole process to involve an AJAX call so that the page doesn't have to be reloaded each time that the user hits the submit button on the form.
As of now, each time the user hits the form submit button the page is being refreshed and i'm getting a response from the ajax call but it is immediately being written over due to the refresh.
Here's my HTML and Javascript/ajax:
<div id="emailform">
<form method="post"><!--action="planethome.php"-->
<input class="emailinput" type="text" name="email" maxlength="80" placeholder="enter your email address"/>
<input class="submitemailbutton" name="send_button" type="submit" value="Send" onClick="ajaxFunction()/>
<input type="hidden" name="submitted" value="TRUE"/>
</form>
</div>
<div id="errororsuccess">
</div>
<!--ajax stuff:---------------------------------->
<script language="javascript" type="text/javascript">
//Browser Support Code"
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Ajax is struggling in your browser.");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('errororsuccess').innerHTML = ajaxRequest.responseText;
}
}
// Create a function that will receive data sent from the server
ajaxRequest.open("POST", "addemailtodatabase.php", true);
ajaxRequest.send(null);
}
and here's my PHP:
<?php
require_once ('planetconfig.php');
if (isset($_POST['submitted'])) { /
require_once (MYSQL);
$email = FALSE;
$trimmed = array_map('trim', $_POST);
if (!empty($_POST['email']))
{
if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[#][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$_POST['email'])) {
$email = mysqli_real_escape_string ($dbc, $trimmed['email']);
} else {
echo "Invalid";
}
} else {
echo "You need to enter an email address";
}
if ($email) {
$q = "INSERT INTO planetemail (email, time) VALUES (AES_ENCRYPT('$email', 'password'), NOW())";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_affected_rows($dbc) == 1) {
echo "Thanks, we'll be in touch";
exit();
} else {
echo '<p class="error">We\'re sorry, something has gone wrong.</p>';
}
}
mysqli_close($dbc);
}
?>
I'm sure it's something to do with my POST method or how I have my ajax call set up.
I'm new to all this, can anyone tell me what I'm doing wrong or suggest a better implementation. I have a deadline of tomorrow morning to have this done.

You're problem is that you are using a submit button. The submit button will submit the form, change it from a type="submit" to type="button" and it will work and as #juzerali suggested, use jQuery, that code hurts my head.

1st, yes that is awful, use jquery. 2nd although you have bound ajax call with onclick of submit button, you have not prevented the default behaviour from executing. The form will still get submitted the usual way.

if (isset($_POST['submitted'])) { /
There is a stray / in your code.
Also, Change type="submit" to type="button"
The onClick event handler will pick up the submit becuase you are making an AJAX request, no need to POST.

return false; at the end of the script to keep it from submitting the normal way.

Related

AJAX Request with PHP

I'm working on ajax for the first time and I feel like I'm close to solving this problem but I need some help. I have my webpage file first below, that has an input field for an email address. When the user submits, the ajax doWork() function should be called which creates the request and processes the request. I have fixed the initial issue of the request being created so I'm positive that the correct object has been created based on the browser. My issue is there's no response text being submitted back and no email is created. The goal is for the user to enter the email, then an introductory email sent back to that address, when this is successful, a response string should be submitted back letting the user know that they have successfully been added to the mailing list and the submission has worked. Thanks for any help, it is greatly appreciated.
<?php include('../includes/educateHeader.php');?>
<script type="text/javascript" charset="utf-8" src="ajax.js"></script>
<div class="involve">
<h1>How to Get Involved In OEC</h1>
<span>Want to become more involved in Operation:Educate Children and don't know how? Share your email address with us, like our facebook page, or check out blog out to learn more about how you can join and help children obtain the education they deserve</span><br></br>
<form method="get">
Email: <input type="email" name="email" id="email" required><br></br>
<input type="submit" value="Send" onclick="doWork()">
</form>
</div>
<div id="outputResponse">
</div>
<?php include('../includes/educateFooter.php');?>
So here is the ajax.js file that creates the request and prints out the data recieved from the email.php file
function getHTTPObject() {
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function setOutput() {
if (httpObject.readyState == 4 && httpObject.status == 200) {
document.getElementById('outputResponse').value = httpObject.responseText;
}
}
function doWork() {
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "email.php?email=" + document.getElementById('email').value, true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
var httpObject = null;
Lastly here is the email.php script which should accept the ajax request and echo back whether a success has occurred or not.
<?php
if (isset($_GET['email'])) {
$mail = trim($_GET['email']);
$subject = 'Welcome!';
$message = 'Thank you for joining the Operation:Educate Children email list. In the future, we will send you updates about new opportunities to become more involved in the activities that we run here at OEC and you could make a difference on children\'s futures. Thank you and best wishes!';
mail($mail, $subject, $message);
echo 'Success! Thank you for your interest in Operaton:Educate Children. Stay tuned for updates!';
}
?>
First add return false; at the end of your function doWork and change onclick="doWork()" to onclick="return doWork()"
Then also change below line
document.getElementById('outputResponse').value = httpObject.responseText;
to
document.getElementById('outputResponse').innerHTML = httpObject.responseText;
Read this question too :) Setting innerHTML vs. setting value with Javascript
JQuery makes this really easy:
$.ajax({
url:'email.php',
type: "POST",
data: 'email='+$('input[name=email]').val(),
success:function(html) {
$('#mydiv').html(html);
}
});
Or for GET, even easier:
$.ajax({
url:'email.php?email='+$('input[name=email]').val(),
success:function(html) {
$('#mydiv').html(html);
}
});

data not passing from ajax post method to php call back

I am trying to pass data in textarea and make the php callback to retutn the same and display it in textarea after simple manipulation to ensure transfer took place.But i can't make my ajax function pass the data.
<script type="text/javascript" src="ajax.js"></script>
This is my form
<form action="#" method="post" onsubmit="submit_notes_call();return false;">
<textarea rows="5" cols="30" name="user_notes" id="user_notes"></textarea>
<input type="submit" name="notes_submit" id="notes_submit" value="UPDATE NOTES" >
</form>
Here is my Ajax function in ajax.js
function submit_notes_call()
{
var ajaxVar;
var user_notes = " Data from ajax call to php callback ";
/*document.getElementById("user_notes").value; */
try
{
ajaxVar = new XMLHttpRequest();
}catch (e)
{
try
{
ajaxVar = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e)
{
try
{
ajaxVar = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e)
{
alert("Your browser broke!");
return false;
}
}
}
ajaxVar.onreadystatechange=function(){
if(ajaxVar.readyState==4)
{
document.getElementById("user_notes").innerHTML = ajaxVar.responseText;
}
};
ajaxVar.open('POST','notes_submit.php',true);
ajaxVar.send(user_notes);
}
and here is my php code in notes_submit.php
<?php
$data_recieved = "Data from php call back to ajax function+".$_POST['user_notes'];
echo "Data : " . $data_recieved;
?>
I get the output as Data : Data sent from php call back to ajax function+ inside the textarea field which means that although comunication is taking place but php call back is not able read the data sent by ajax caller or may be ajax function is not able to send the data to php call back.
What is the error here??
Replace thie line
ajaxVar.send(user_notes);
by
ajaxVar.send('user_notes='+user_notes);
Read this http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

more than one form with the same input ID send just the first value with Ajax

I am doing ajax function to do insert into DB using form and input type=hidden but when I put more than form in the same page it is always take just the first value in the first form
here is the code:
the Ajax function
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("ajaxDiv");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var in1 = document.getElementById("in1").value;
var queryString1 = "?in1=" + in1;
//ajaxRequest.open("GET", "/sites/all/php/check.php" + queryString, true);
ajaxRequest.open("GET", "/sites/all/php/check.php" + queryString1, true);
ajaxRequest.send(null);
}
//–>
</script>
here is the html forms
<form name="myForm1">
<input type="hidden" value="1" id="in1">
<a onclick="ajaxFunction()" class="folloo"></a>
<form name="myForm2">
<input type="hidden" value="2" id="in1">
<a onclick="ajaxFunction()" class="folloo"></a>
<form name="myForm3">
<input type="hidden" value="3" id="in1">
<a onclick="ajaxFunction()" class="folloo"></a>
</form>
</form>
</form>
and here is the check.php code that do the DB query
<?php
//Connect to MySQL Server
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("localhost","admin","123456") or die('Cannot connect to the database
because: ' . mysql_error());
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("dbname") or die("Unable to select database");
//select which database we're using
// Retrieve data from Query String
$in1 = $_GET['in1'];
// Escape User Input to help prevent SQL Injection
$in1 = mysql_real_escape_string($in1);
//Build and run a SQL Query on our MySQL tutorial
if($in1){
mysql_query("INSERT INTO test (name)
VALUES ('" . $in1. "')");
}
?>
put when i click on any link it is always send the first value.
cah anyone tell mewhat is the problem here?
id values must be unique on the page. You've shown that you have multiple input type="hidden" elements with the same id value ("in1"). If you have more than one element with the same id value, when you try to look it up (for instance, using getElementById), most browsers will give you the first one, but it's undefined behavior because the markup/DOM is invalid.
The fix is to fix the IDs so that they're unique, or not use IDs at all and use something that isn't required to be unique, such as name or class — but then you'll need to retrieve it with querySelectorAll or similar, and deal with the fact that you have multiple matching elements.

Echoing in php without changing pages

I have a simple input form on my site for people to enter in information for submission. The code looks like this in the case they do not enter anything:
this is form.php
if ($_POST['q']) == NULL ){
echo "Please enter your information"
The code works great, but it sends the user to form.php with the echo, where I want this to be echoed on my main page index.html right below the input box - basically so it doesn't navigate away from the page. Is this doable in php or will I need some javascript. I would have searched for ways to do this but I don't know what this method is called.
Thanks!
dont set a action in the url and it will submit to its self, if that still wont work you will need rewrite rules.
If you don't want to navigate away from the page you will need to use Javascript. Add a onSubmit to the form, and then let the function you call there return false, if the input is not complete and the form should not be submitted.
you can make it postback to itsself and then redirect the page to post.php?q=value if there is a value else echo below the input field.
<?php
$qisempty = false;
if(!empty($_POST['q']))
{
header("Location:http://../post.php?q=".$_POST['q']);
}
else
$qisempty = true;
?>
<input name="q" type="text">
<?php if($qisempty) echo "Please enter your information";?>
You can use AJAX for this thing. AJAX is great for this type of problems when you don't want to reload pages to do task in specific place or Div of HTMLpages.
For your problem, You need to create a HTML file with your form in it, and submit it via AJAX. and get your response via same AJAX.
<script type="text/javascript">
function submit_ajax(val1,val2,param1,param2,subfile){
var http = new XMLHttpRequest();
var url = subfile;
var params = val1+"="+param1+"&"+val2+"="+param2;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
//Remove the alert and use whatever you want to do with http.responsetext like
// document.getElementById("YourDiv").innerHTML=document.getElementById("YourDiv").innerHTML +http.responsetext
}
}
http.send(params);
}
</script>
</head>
<body>
<form>
<input type="text" id="user" value="user" name="user" />
<input type="password" id="password" value="pass" name="pass" />
<button onclick="submit_ajax(user.name,password.name,user.value,password.value, "submit_file.php");">Submit</button>
</form>
<div id="YourDiv">
<!--Something appears here after callback-->
</div>
This was the first page. Now Use your script in your PHP file(probably, submit_file.php) as you want and then echo the text you want in your div by validation or something.. a sample would be
<?php
$username=$_POST['user'];
$password=$_POST['pass'];
if(validateuser($username,$password)){
if(checkuserpass($username,$password){
echo "You were successfully logged in!";
}
echo "Sorry Username/Password Mismatch";
}
else {
echo "There was an error in your input!Please Correct";
}
?>
Hope you got what you wanted...
The simplest way would be assigning the error message to a variable called (e.g $errorMsg)
the printing it on page using a echo or print function.
<?php
if ($_POST['q']) == NULL ){
$errorMsg =' Please enter your information';
}
?>
Place this code where you want the error to appear
<? print $errorMsg; ?>

Ajax PHP MYSQL on enter

I am using the below code to search a mysql database but cannot get the form to submit when the return key is pressed.
Does anybody have any ideas?
function ajaxFunction(){
var ajaxRequest;
{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var kw = document.getElementById('kw').value;
var division = document.getElementById('division').value;
var queryString = "?kw=" + kw + "&division=" + division;
ajaxRequest.open("GET", "search/jsearch.php" + queryString, true);
ajaxRequest.send(null);
}
Form code is:
<form name='myForm'>
Keywords<input type='text' id='kw' /> <br />
<br />
<select id='division'>
<option value='0' selected="selected">window & door</option>
<option value="1">window</option>
<option value="2">door</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
Where is your event code for the form? Are you using an onclick instead of onsubmit? I don't think we have enough code/information to answer this, but from what you describe your first step to make sure you are using an onsubmit event for the form so you can fire off the xhr.
EDIT:
Then the answer to this problem: "...cannot get the form to submit when the return key is pressed", is use onsubmit instead of onclick. You also need to attach the event to the form instead of the button, and if possible refrain from using inline js.
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
onclick fires when you click the button. You are pressing return, not clicking the button.
As mentioned earlier, you should use onsubmit which fires when the form is submitted. You will need to return false, ie use onsubmit="ajaxFunction();return false;", to prevent the normal submission from occurring.

Categories