Why is my newsletter form not working on Amazon CloudFront? - javascript

I am using HTML and using amazon EC2 (Linux free tier). I would like to use CloudFront, but my newsletter won't work. I am not an AWS expert, and I don't have a clue as to why it won't work on CloudFront.
My newsletter form looks like this:
<form id="subscribe" class="form" action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group form-inline">
<input size="15" type="text" class="form-control required" id="NewsletterName" name="NewsletterName" placeholder="Your name" />
<input size="25" type="email" class="form-control required" id="NewsletterEmail" name="NewsletterEmail" placeholder="your#email.com" />
<input type="submit" class="btn btn-default" value="SUBSCRIBE" />
<span id="response">
<? require_once('assets/mailchimp/inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</span>
</div>
</form>
and my js file looks like this:
jQuery(document).ready(function() {
jQuery('#subscribe').submit(function() {
// update user interface
jQuery('#response').html('<span class="notice_message">Adding email address...</span>');
var name = jQuery('#NewsletterName').val().split(' ');
var fname = name[0];
var lname = name[1];
if ( fname == '' ) { fname=""; }
if ( lname == '' || lname === undefined) { lname=""; }
// Prepare query string and send AJAX request
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()),
success: function(msg) {
if (msg.indexOf("Success") !=-1) {
jQuery('#response').html('<span class="success_message">Success! You are now
subscribed to our newsletter!</span>');
} else {
jQuery('#response').html('<span class="error_message">' + msg + '</span>');
}
}
});
return false;
});
});
and my php file looks like this:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('mymailchimpapi');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "myuniqueid";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a
confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The form works when I access it without using CloudFront, but I am worried of the server bandwidth that's why I want to use CloudFront. What happens is that when you click the submit button, the "adding email address" message will just appear for 1 second, and the email address entered is ignored.

Please make sure your CloudFront distribution is actually configured to handle POST/PUT requests. Take a look here for details: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesAllowedHTTPMethods

Related

stop page from redirecting to php file after form submit

I have a php file that retrieves information entered in an html form and saves it into a mysql db. The problem I am facing is that I cannot figure out how to stop the page from redirecting to insertinfo.php. I want the user to stay on the same index.html page where a modal will appear on form submission. Below is my index.html and insertinfo.php
The index.html file:
<div class="form ">
<form class="container" action="insertinfo.php">
<input type="text" id="firstname" class="form_input" placeholder="First Name" name="firstname" required>
<input type="text" id="lastname" class="form_input" placeholder="Last Name" name="lastname" required>
<input type="text" id="email" class="form_input" placeholder="Email Address" name="email" required>
<input type="submit" id="myBtn" class="submit" value="Download eBook">
</form>
</div>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<div class="icon-box">
<i class="material-icons">check</i>
</div>
</div>
<div class="modal-body">
<h4>An email with a download link towards the eBook has been sent to you.</h4>
<p>Please check your inbox and your spam/bulk messages.</p>
Continue
</div>
</div>
</div>
<script type="text/javascript">
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// When the user clicks the button, open the modal
btn.onclick = function(event) {
var fnameInput = document.getElementById("firstname").value;
var lnameInput = document.getElementById("lastname").value;
var emailInput = document.getElementById("email").value;
if(fnameInput.length == 0 || lnameInput.length == 0 || emailInput.length == 0){
event.preventDefault();
alert("You must complete all existing fields");
} else {
modal.style.display = "block";
}
}
</script>
The insertinfo.php:
if (isset($_POST["submit"])){
// Escape user inputs for security
$first_name = $conn->real_escape_string($_REQUEST['firstname']);
$last_name = $conn->real_escape_string($_REQUEST['lastname']);
$email = $conn->real_escape_string($_REQUEST['email']);
$date_added = 'NOW()';
$sql = "INSERT INTO userinfo (firstname, lastname, email, date_added) "
. "VALUES ('$first_name', '$last_name', '$email', $date_added )";
if ($conn->query($sql) === TRUE) {
echo 'not working';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
If you want your user to be index.html and submit the form to other php file then you will need to use ajax post request to the insertinfo.php. Ajax can post form data and retrieve PHP processed response
This is a example how you can submit the form with ajax
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'superheroAlias' : $('input[name=superheroAlias]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
The action form attribute describes where the <form> is going to be submitted to.
If you remove it, the form will submit to the current page.
So deleting this part: action="insertinfo.php" will stop the <form> from redirecting you to insertinfo.php
If you still want to submit your data to insertinfo.php without reloading, use an ajax library or check out: How to use XMLHttpRequest.

POST request problems during JSON response using AngularJS

I am having an issue while using JSON server for login form. I have login credentials like Username and password and trying to execute it. I have used POST on the server, specifying username and password inserted by the user. The server should execute a query on the specified condition, to check if there are any rows with that name and password. If yes return true, if false return false. then the client should parse this response.
This is my HTML code :
<form ng-submit="loginform(logcred)" name="logform"><br/><br>
<tr ng-repeat="logcred in loginfo"></tr>
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username" >
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="submit()">Login</button>
</div>
</form>
This is the Javascript code using AngularJS:
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
$http.get('http://localhost:3000/loginfo')
.then(
function successCallback(response){
$scope.loginfo == response.data;
$scope.loginform = function(loginfo,username,password){
console.log(loginfo);
$http({
url :'http://localhost:3000/loginfo',
method : 'POST',
data : loginfo
})
.then(
function successCallback(response){
$scope.loginfo = response.data;
if (username === username && password === password) {
console.log(response);
}
else
{
console.log("Error: " + response)
}
});
}
});
I am getting the response properly from my server. But when I match the data using POST request using if condition, there I am not understanding what mistake I am doing ?
Any help / advice would be greatly appreciated.
i didnt understand if your problem is server side or client ? is your problem at
if (username === username && password === password) {
console.log(response);
}
you may use == insted of ====
You are comparing the data with itself.
username === username && password === password
Should be
username === $scope.loginfo.username && password === $scope.loginfo.password
Still, any kind of security validation should be done on the server rather than on the client.
Also, you seem to be new to Angular. Let me recommend to you the John Papa's Styleguide.

How to implement reCAPTCHA with AJAX for sending mail in php?

I'm trying to add Google's recaptcha in my website's contact form. I've used the <input type="submit"> instead of button tag for submitting the form. But it doesn't work with AJAX. And with button tag, the captcha response is always empty. You can check the problem on vipiny.com.
This is the contact form.
<form action="" method="post" id="contactForm" name="contactForm">
<div>
<label for="contactName">Name <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactName" name="contactName">
</div>
<div>
<label for="contactEmail">Email <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactEmail" name="contactEmail">
</div>
<div>
<label for="contactSubject">Subject</label>
<input type="text" value="" size="35" id="contactSubject" name="contactSubject">
</div>
<div>
<label for="contactMessage">Message <span class="required">*</span></label>
<textarea cols="50" rows="3" id="contactMessage" name="contactMessage"></textarea>
</div>
<div class="g-recaptcha captcha" data-theme="light" data-sitekey="6LfAkhQUAAAAAC2D3LxhB9XtYeoJGhuvR31sq9HW"></div>
<div>
<button class="submit">Submit</button>
</div>
</form> <!-- Form End -->
And I'm using ajax to send the data to sendMail.php file.
$('form#contactForm button.submit').click(function() {
$('#image-loader').fadeIn();
var contactName = $('#contactForm #contactName').val();
var contactEmail = $('#contactForm #contactEmail').val();
var contactSubject = $('#contactForm #contactSubject').val();
var contactMessage = $('#contactForm #contactMessage').val();
var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
'&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false; }); });
And this is so far my sendMail.php file. I'm trying to validate that if $error['captcha'] is empty along with other input field checks, the mail will be sent.
$secret = "<--secret key-->";
$user_ip = $_SERVER['REMOTE_ADDR'];
if(isset($_POST['g-recaptcha-response'])){
$response = $_POST['g-recaptcha-response'];
// echo "GOT response:".$response."<br/>";
}
else{
// echo "No reCAPTCHA response.<br/>";
}
//Verify response data
$verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$user_ip");
$responseData = json_decode($verifyResponse);
if(!$responseData->success){
$error['captcha'] = "Please prove that you're not a robot.";
}
Any suggestions what might be going wrong?
You forgot to add the ? after the url
url: "inc/sendEmail.php?",
OR
you could leave out the ? and send your data like
data: { this: this, that: that, another: another},
also since you are not posting the g-recaptcha-response to the php file with the form, but instead with AJAX you have to send the post manually to your php file.
var g-recaptcha-response= $('#contactForm .g-recaptcha-response').val();
var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
'&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage + '&g-recaptcha-response=' + g-recaptcha-response;
you made also need this to confirm the recaptcha in php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
https://developers.google.com/recaptcha/old/docs/php

Can't get AJAX calls or session to function

I have an extremely similar service like the one in this thread:
Php: Form auto-fill using $_SESSION variables with multiple php files
I would have asked there but since I don't have 50 reputation, I'll have to ask a new question.
To understand Ajax better I wanted to re-create rkmax's files and see if they would work. So I saved them as 5 separate files.
The SESSION does not seem to store any posted information. Added a print_r($_SESSION); to keep track of what's currently in there. Furthermore the .blur event to retrieve account information via the phone number doesn't work either.
Been banging my head against the wall for days with this one. It won't work when working either hosted locally via Apache/XAMPP or on an actual web server. All 5 files are in the same folder and titled exactly the same as rkmax's file titles.
I understand the logic behind each of the functions and can't seem to find a problem anywhere. I'm pretty new to coding so it could easily be something obvious like file structure or my own computer's settings?
Read a bunch of other StackOverflow threads with similar problems, but none of them seemed whatsoever applicable.
Thanks for your time.
Here's everything copied from rkmax's code:
index.php
<?php
session_start();
if (!isset($_SESSION['customers'])) {
$_SESSION['customers'] = array(
'1234567' => '{"lname": "Berg", "mi": "M", "fname": "Thomas", "account": "1234"}',
'1122334' => '{"lname": "Jordan", "mi": "C", "fname": "Jacky", "account": "4321"}',
);
}
require __DIR__ . '/index_template.php';
index_template.php
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div style="margin-left: 300px">
<form id="dataForm" method="post">
<fieldset>
<legend>User info</legend>
<label for="fname">First name</label>
<input id="fname" type="text" name="fname" placeholder="First name"/>
<label for="mi">Middle inicial</label>
<input id="mi" type="text" name="mi" placeholder="Middle Initial"/>
<label for="lname">Last name</label>
<input id="lname" type="text" name="lname" placeholder="Middle Initial"/>
<label for="phone">Phone number</label>
<input id="phone" type="text" name="phone" placeholder="000000"/>
</fieldset>
<fieldset>
<legend>Account info</legend>
<label for="account">Account</label>
<input id="account" type="text" name="account"/>
</fieldset>
<input type="submit" name="submit"/>
<input type="reset" name="clear"/>
</form>
</div>
</body>
</html>
postCustomerInformation.php
session_start();
// example: converts $_POST['phone'] into $post_phone if exists
extract($_POST, EXTR_PREFIX_ALL, 'post');
// Validates that all required information was sent
if (isset($post_lname) && isset($post_fname) && isset($post_phone) && isset($post_account)) {
$customer = array(
'fname' => $post_fname,
'lname' => $post_lname,
'account' => $post_account,
'mi' => isset($post_mi) ? $post_mi : '' // optional
);
$_SESSION['customers'][$post_phone] = json_encode($customer);
// returns a valid json format header
header('Content-Type: application/json');
header("HTTP/1.0 204 No Response");
} else {
// returns error
header('Content-Type: application/json');
header("HTTP/1.0 400 Bad Request");
}
getCustomerInformation.php
session_start();
// example: converts $_GET['phone'] into $get_phone if exists
extract($_GET, EXTR_PREFIX_ALL, 'get');
if (isset($get_phone) && isset($_SESSION['customers'][$get_phone])) {
header('Content-Type: application/json');
echo $_SESSION['customers'][$get_phone];
} else {
header('Content-Type: application/json');
echo '{}';
}
scripts.js
;(function () {
"use strict";
function getCustomerInformation() {
var phone = jQuery(this).val();
if (!phone) {
return;
}
jQuery.ajax({
type: 'get',
url: 'getCustomerInformation.php',
data: {
phone: phone
},
success: function getCustomerInformation_success(data) {
// for each returned value is assigned to the field
for (var i in data) {
if (data.hasOwnProperty(i)) {
$('#' + i).val(data[i]);
}
}
}
});
}
function postCustomerInformation(event) {
event.preventDefault();
var form = jQuery(this);
jQuery.ajax({
type: 'post',
url: 'postCustomerInformation.php',
data: form.serializeArray(),
success: function postCustomerInformation_success() {
alert("OK");
},
error: function postCustomerInformation_error() {
alert("Error");
}
})
}
// set behaviors when document is ready
jQuery(document).ready(function document_ready() {
jQuery('#phone').blur(getCustomerInformation);
jQuery('#dataForm').submit(postCustomerInformation);
});
})();
I would try and do something a bit scaled down, see if this is what you are trying to do. You only need 3 pages, the original form page, the php page, and the js file:
/ajax/dispatch.php
/*
** #param $phone [string] Gets key from session
*/
function getCustomerByPhone($phone)
{
if(!empty($_SESSION['customers'][$phone])) {
// I am decoding, but if you have the ability to set,
// create an array like below with success and data
$values = json_decode($_SESSION['customers'][$phone]);
die(json_encode(array("success"=>true,"data"=>$values)));
}
}
function makeError()
{
// Send back error
die(json_encode(array("success"=>false,"data"=>false)));
}
/*
** #param $array [string] This will be a query string generated from the
** jQuery serialize, so it's to be turned to array
*/
function updateSession($array)
{
// This should come back as a string, so you will need to parse it
$data = false;
parse_str(htmlspecialchars_decode($array),$data);
// Update the session
$_SESSION['customers'][$data['phone']] = json_encode($data);
die(json_encode(array("success"=>true,"data"=>$data)));
}
if(isset($_POST['phone'])) {
// If already exists, return to ajax the data
getCustomerByPhone($_POST['phone']);
}
elseif(isset($_POST['data'])) {
updateSession($_POST['data']);
}
// If not exists, return false
makeError();
/scripts.js
// I try not to duplicate things as much as possible
// so I would consider making an object to reuse
var AjaxEngine = function($)
{
this.ajax = function(url,data,func,method)
{
method = (typeof method === "undefined")? 'post' : 'get';
$.ajax({
url: url,
data: data,
type: method,
success: function(response) {
func(response);
}
});
};
};
$(document).ready(function(){
// Create instance
var Ajax = new AjaxEngine($);
var dispatcher = '/ajax/dispatch.php';
// On submit of form
$(this).on('submit','#dataForm',function(e) {
// Get the form
var thisForm = $(this);
// Stop form from firing
e.preventDefault();
// Run ajax to dispatch
Ajax.ajax(dispatcher,
// Serialize form
$('#dataForm').serialize(),
// Create an anonymous function to handle return
function(response) {
// Parse
var resp = JSON.parse(response);
// See if data exists
if(typeof resp.data === "undefined") {
console.log(resp.data);
return false;
}
// If there is a hit in session
else if(resp.success == true) {
// Loop through it and fill empty inputs in form
$.each(resp.data, function(k,v){
var input = $("input[name="+k+"]");
if(input.length > 0) {
if(input.val() == '') {
input.val(v);
}
}
});
}
// Run the session update
Ajax.ajax(dispatcher,
// This time send an action
// (just to differentiate from check function)
{
"action":"update",
"data":thisForm.serialize()
},
function(response) {
// Check your console.
console.log(response);
});
});
});
});
Started from scratch working on my answer pretty much nonstop, but gotta go to work soon, here's what I've got so far; I'm currently stuck on successfully sending the SESSION data back to the javascript and decoding it and displaying it successfully. Once I have that working I think sending those to the appropriate forms as well as the POST will be trivial. If anyone has any suggestions to speed me through this last part I would appreciate it.
Edit: Edited with the final solution.
index2.php
<?php
session_start();
if (!isset($_SESSION['customers'])) {
$_SESSION['customers'] = array(
'1111111' => '{"phone": "1111111", "fname": "Za", "lname": "Zo", "mi": "Z", "account": "1234"}',
'2222222' => '{"phone": "2222222", "fname": "La", "lname": "Li", "mi": "L", "account": "4321"}',
);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title> Assignment5 </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type = "text/javascript" src = "scripts.js"></script>
</head>
<body>
<form id="myform">
<input placeholder="Phone Number" name="phone" type="text" id="phone" maxlength="7" autofocus>
<input placeholder="First Name" name="fname" type="text" id="fname">
<input placeholder="Last Name" name="lname" type="text" id="lname">
<input placeholder="Middle Initial" name="mi" type="text" id="mi">
<input placeholder="Account Number" name="account" type="text" id="account" maxlength="4">
<input type="submit" value="Submit">
</form>
</body>
</html>
scripts.js
$(document).ready(function(){
$("#phone").blur(function(){
var session;
var currentPhone = $("#phone").val();
$.get("getPhone.php", {phone: currentPhone}, function(data) {
for (var i in data) {
if (data.hasOwnProperty(i)) {
$('#' + i).val(data[i]);
}
}
});
});
$("form").submit(function(){
var form = jQuery(this);
$.post("postPhone.php", form.serializeArray(), function(data) {
alert(data);
});
});
});
getPhone.php
<?php
session_start();
$nowPhone = $_GET["phone"];
if (array_key_exists($nowPhone, $_SESSION['customers'])) {
header('Content-Type: application/json');
echo $_SESSION['customers'][$nowPhone];
} else {
header('Content-Type: application/json');
echo '{}';
}
?>
postPhone.php
<?php
session_start();
if (isset($_POST["phone"]) && isset($_POST["fname"]) && isset($_POST["lname"]) && isset($_POST["mi"]) && isset($_POST["account"])) {
echo ("Submitted");
$customer = array(
'phone' => $_POST["phone"],
'fname' => $_POST["fname"],
'lname' => $_POST["lname"],
'mi' => $_POST["mi"],
'account' => $_POST["account"],
);
$_SESSION['customers'][$_POST["phone"]] = json_encode($customer);
}
else
echo ("All Information is Required");
?>

ajax request function does not work when its called

<script type="text/javascript"src="prototype.js"></script>
<script type="text/javascript">
//<![CDATA[
document.observe("dom:loaded", function() {
function sendRequest() {
var oform = document.forms[0];
var sBody = getRequestBody(oform);
var oOptions = {
method: "post",
parameters: sBody,
onSuccess: function (oXHR, oJson) {
saveResult(oXHR.responseText);
},
onFailure: function (oXHR, oJson) {
saveResult("An error occurred: " + oXHR.statusText);
}
};
var oRequest = new Ajax.Request("edit_status.php", oOptions);
}
function saveResult(sMessage) {
var divStatus = document.getElementById("divStatus");
divStatus.innerHTML = "Request completed: " + sMessage;
}
});
//]]>
</script>
I am new to ajax. i have a project at hand that really need a lot of ajax functionality. I am following this above code from a book i bought. when i copy this code on my local server, the ajax.request function is not working when i click the submit button. It takes me straight to the php page. Please can someone help me look at this?
**
<form method="post" action="SaveCustomer.php"
onsubmit="sendRequest(); return false">
<p>Enter customer information to be saved:</p>
<p>Customer Name: <input type="text" name="txtName" value="" /><br />
Address: <input type="text" name="txtAddress" value="" /><br />
City: <input type="text" name="txtCity" value="" /><br />
State: <input type="text" name="txtState" value="" /><br />
Zip Code: <input type="text" name="txtZipCode" value="" /><br />
Phone: <input type="text" name="txtPhone" value="" /><br />
E-mail: <input type="text" name="txtEmail" value="" /></p>
</form>
<div id="divStatus"></div>
**
**
header("Content-Type: text/plain");
//get information
$sName = $_POST["txtName"];
$sAddress = $_POST["txtAddress"];
$sCity = $_POST["txtCity"];
$sState = $_POST["txtState"];
$sZipCode = $_POST["txtZipCode"];
$sPhone = $_POST["txtPhone"];
$sEmail = $_POST["txtEmail"];
//status message
$sStatus = "";
//database information
$sDBServer = "localhost";
$sDBName = "ajax";
$sDBUsername = "root";
$sDBPassword = "";
//create the SQL query string
$sSQL = "Insert into Customers(Name,Address,City,State,Zip,Phone,`Email`) ".
" values ('$sName','$sAddress','$sCity','$sState', '$sZipCode'".
", '$sPhone', '$sEmail')";
$oLink = mysql_connect($sDBServer,$sDBUsername,$sDBPassword);
#mysql_select_db($sDBName) or $sStatus = "Unable to open database";
if ($sStatus == "") {
if(mysql_query($sSQL)) {
$sStatus = "Added customer; customer ID is ".mysql_insert_id();
} else {
$sStatus = "An error occurred while inserting; customer not saved.";
}
}
mysql_close($oLink);
echo $sStatus;
?>
**
you arent firing the ajax i see you define the options but thats it try
using jquery u can wait for form submission
$('your form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:'your url',
type:'post',
data:'your data',
success:function(data, jxhr){
//your success function
},
error:function(){}
});
});
the e.preventDefault() prevents the synchronous submission from firing default methods
looking at your code the sendRequest() can be changed to sendRequest(event) then add the event.preventDefault. I always have issues with return false

Categories

Resources