XMLHttpRequest responding with undesired response - javascript

I ran into trouble that i have failed to understand at all. I have a sign up form,ajax script and php script.My goal is that,i want to submit data to the php from the sign up form using ajax. My problem is that i can send but do not get the results that i desire as the response.
This is my sign-up form
<form method="post" action="../../includes/seller.inc.php" id="form">
<label for="names">First name and last name: </label><input type="text" name="names" id="names"> <br><br>
<label for="phone">phone number: </label><input type="text" name="phone" id="phone"> <br><br>
<label for="shopName">shop name: </label><input type="text" name="shopName" id="shopName"> <br><br>
<label for="email">Email: </label><input type="text" name="email" id="email"> <br><br>
<label for="pwd">Password: </label><input type="password" name="pwd" id="pwd"> <br><br>
<label for="pwd2">Retype Password: </label><input type="password" name="pwd2" id="pwd2"> <br><br>
<label for="description">Provide a brief Description</label><textarea name="description" id="description" cols="30" rows="5"></textarea> <br><br>
<button type="submit" name="submit">submit</button><br>
</form>
And this is my PHP script(action specified by the form):
$names = mysqli_real_escape_string($conn, $_POST["names"]);
$phone = mysqli_real_escape_string($conn, $_POST["phone"]);
$shopName = mysqli_real_escape_string($conn, $_POST["shopName"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$pwd = mysqli_real_escape_string($conn, $_POST["pwd"]);
$pwd2 = mysqli_real_escape_string($conn, $_POST["pwd2"]);
$description = mysqli_real_escape_string($conn, $_POST["description"]);
//validating the user input data
if(!empty($names && $phone && $shopName && $email && $pwd && $pwd2)){
if (preg_match("/^[a-zA-Z\s]+$/",$names)) {
if (preg_match("/^[0-9+](\d)+$/",$phone)) {
if(preg_match("/^[a-zA-Z\s]+$/",$shopName)) {
if(filter_var($email,FILTER_VALIDATE_EMAIL)) {
if ($pwd !== $pwd2) {
header("Location: ../sell/auth/sell.signup.php?passwordsdoNotMatch");
} else {
$hashed_pwd = password_hash($pwd, PASSWORD_DEFAULT);
$sql = "INSERT INTO seller(name,phone,shopName,email,password,description,approval_status) VALUES ('$names','$phone','$shopName','$email','$hashed_pwd','$description','0');";
if(!mysqli_query($conn, $sql)) {
echo "sorry not added".mysqli_error($conn);
} else {
header("Location: ../index.php");
$_SESSION['actionmsg-success'] = "successfully Added .Wait for approval!! so that you may post your products.";
}
}
And this is the ajax
function loadFunc() {
const names = document.getElementById('names');
const phone = document.getElementById('phone');
const shopName = document.getElementById('shopName');
const email = document.getElementById('email');
const pwd = document.getElementById('pwd');
const pwd2 = document.getElementById('pwd2');
const description = document.getElementById('description');
var form = document.getElementById('form');
form.addEventListener('submit', function (e) {
e.preventDefault();
var params = `names=${names}&phone=${phone},shopName=${shopName},email=${email}&pwd=${pwd}&pwd2=${pwd2}&description=${description}`;
var xhr = new XMLHttpRequest();
xhr.open('post', '../../includes/seller.inc.php');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
if (this.readyState == 4) {
console.log(this.responseText);
}
}
xhr.send(params);
});
}
When running them i dont get an error but i get a response of my own html code printed to the browser.

Related

Ajax call php function breaks all javascript functions and page

I'm trying to validate if a username is already taking or not. This onchange of an input field. I already got other checks but they don't work anymore since I added the ajax call. I'm new to ajax and javascript so the error can be there.
the html form:
<form action="test" method="post">
<input id="username" type="text" placeholder="Gebruikersnaam" name="username" required onchange="checkUserName()">
<br>
<input id="email" type="text" placeholder="Email" name="email" required onchange="validateEmail()">
<br>
<input id="pass1" type="password" placeholder="Type wachtwoord" name="password1" required>
<br>
<input id="pass2" type="password" placeholder="Bevestig wachtwoord" name="password2" required onchange="passwordCheck()">
<br>
<select name="typeAccount">
<option value="bedrijf">Bedrijf</option>
<option value="recruiter">Recruiter</option>
<option value="werkzoekende">Talent zoekt job</option>
</select>
<p id="demo1">
</P>
<p id="demo2">
</P>
<button type="submit">Scrijf mij in!</button>
</form>
the javascript that I use:
<script src="jquery.js">
function passwordCheck(){
var password1 = document.getElementById('pass1').value;
var password2 = document.getElementById('pass2').value;
if(password1 !== password2){
document.getElementById("pass1").style.borderColor = "#ff3333";
document.getElementById("pass2").style.borderColor = "#ff3333";
}else{
document.getElementById("pass1").style.borderColor = "#1aff1a";
document.getElementById("pass2").style.borderColor = "#1aff1a";
}
}
function validate(email){
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateEmail(){
var email = document.getElementById('email').value;
if(validate(email)){
document.getElementById("email").style.borderColor = "#1aff1a";
}else{
document.getElementById("email").style.borderColor = "#ff3333";
}
}
function checkUserName(){
var username = document.getElementById('username').value;
if(username === ""){
document.getElementById("username").style.borderColor = "#ff3333";
}else{
$.ajax({
url: "userCheck.php",
data: { action : username },
succes: function(result){
if(result === 1){
document.getElementById("username").style.borderColor = "#1aff1a";
}else{
document.getElementById("username").style.borderColor = "#ff3333";
}
}
});
}
}
</script>
The php script I use this is in a different file:
<?php
include("connect.php");
$connect = new Connect();
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query('select username from usermaindata where username = "'. $username .'"');
if(mysql_num_rows($result)>0){
echo 0;
}else{
echo 1;
}
?>
The script and the html form is in the same html-file and the php is in a seperate PHP-file.
I just want to check if the name is already in the database or not.
I assume your database connection is perfect.
$username = mysql_real_escape_string($_POST['username']);
change above code to
$username = mysqli_real_escape_string($db_connection,$_REQUEST['action']);
because in your ajax you're doing like
$.ajax({
url: "userCheck.php",
data: { action : username },
succes: function(result){
if(result === 1){
document.getElementById("username").style.borderColor = "#1aff1a";
}else{
document.getElementById("username").style.borderColor = "#ff3333";
}
}
});
You have not specified request type and you're fetching value using $_POST with different variable name username which is actually value
You should use $_REQUEST['action']
And make sure you've added jquery.js file in your html.

jQuery Ajax not working with $.ajax()

I am trying use for fetching data and displaying it through jQuery. This is my script
<script>
$("#kys_SignUp_form").submit(function(event){
event.preventDefault();
var $form = $(this);
var $url = $form.attr('action');
var $email = $("#email").val();
var $username = $("#username").val();
var $password = $("#password").val();
$.ajax({
type: 'POST',
url: $url,
data: { email: $email, password: $password, username: $username },
success: function(data) {
alert("Transaction Completed!");
}
});
});
</script>
And this is my form:
<form role="form" action="kys_SignUp.php" method="post" id="kys_SignUp_form">
<div class="form-group">
<label for="email" >Email address:</label>
<input type="email" style="width: 300px" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="Username" >Username:</label>
<input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I am new to jQuery. The problem that I am facing is the page is being redirected to the php file even after using ajax, I think ajax function is not at all called.
This is my php file:
<?php
include "kys_DbConnect.php";
$email = $username = $password = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = cleanData($_POST["email"]);
$username = cleanData($_POST["username"]);
$password = cleanData($_POST["password"]);
}
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();
if(isset($kys_username)){
echo "Username or Email already exists";
}
else{
$insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)");
$insert->bind_param("sss",$username,$email,$password);
$insert->execute();
header("Location: http://localhost/KeyStroke/index.html");
exit();
}
function cleanData($data){
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I am not able find out what's wrong with my code.
Updated try this :
<form role="form" action="kys_SignUp.php" method="post" id="kys_SignUp_form">
<div class="form-group">
<label for="email" >Email address:</label>
<input type="email" style="width: 300px" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="Username" >Username:</label>
<input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>
<button id="submit_btn" class="btn btn-default">Submit</button>
</form>
UPDATED 2 :
<script>
$(function() {
// Handler for .ready() called.
$("#submit_btn").on('click',function(event){
//alert is not being called at all . That means .submit() is never beign called
alert("hello there");
event.preventDefault();
var form = $('#kys_SignUp_form'); //changed from $(this)
var url = form.attr('action');
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: 'POST',
url: url,
dataType:"json", //<-- add this
data: { email: email, password: password, username: username },
success: function(data) {
if(data.success){
window.location.href=data.result;
}else {
alert("ERROR. "+data.result);
}
}
});
});
});
</script>
and in your PHP code
<?php
include "kys_DbConnect.php";
$email = $username = $password = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = cleanData($_POST["email"]);
$username = cleanData($_POST["username"]);
$password = cleanData($_POST["password"]);
}
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();
if(isset($kys_username)){
echo json_encode(array("success"=>false,"result"=>"Username or Email already exists"));
}
else{
$insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)");
$insert->bind_param("sss",$username,$email,$password);
$insert->execute();
echo json_encode(array("success"=>true,"result"=>"http://localhost/KeyStroke/index.html"));
}
function cleanData($data){
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script>
$("#clickbutton").click(function(){
var $url = 'kys_SignUp.php';
var $email = $("#email").val();
var $username = $("#Username").val();
var $password = $("#password").val();
$.ajax({
type: 'POST',
url: $url,
data: 'email='+$email+'&password='+$password+'&username='+$username,
success: function(data) {
alert("Transaction Completed!");
}
});
});
</script>
and also remove action in your form and change your submit button
<button type="button" id="clickbutton" class="btn btn-default">Submit</button>
Try this function:
<script>
$(function() {
$('#kys_SignUp_form button[type="submit"]').on('click',function(event){
alert("hello there");
event.preventDefault();
var form = $("#kys_SignUp_form");//note here we select the form element to get the url
var url = form.attr('action');
var email = form.find("#email").val();
var username = form.find("#username").val();
var password = form.find("#password").val();
$.ajax({
type: 'POST',
url: url,
dataType:"json",
data: { email: email, password: password, username: username },
success: function(data) {
if(data.message == "Success") {
window.location ='http://localhost/KeyStroke/index.html';
} else {alert(data.message)}
});
});
});
</script>
php:
include "kys_DbConnect.php";
function cleanData($data){
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function isUser($username,$email)
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();
if(isset($kys_username)){
return true;
}
}
function inserNewUser($username,$email,$password)
$insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)");
$insert->bind_param($username,$email,$password);
$insert->execute();
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = cleanData($_POST["email"]);
$username = cleanData($_POST["username"]);
$password = cleanData($_POST["password"]);
if (isUser($username,$email)) {
echo json_encode(['message'=>'Username or Email already exists'])
} else {
inserNewUser($username,$email,$password);
echo json_encode(['message'=>'Success']);
}
} else {
echo json_encode(['message'=>'Error get method not allowed'])
}
Look at my way, may be it will help you.
$('#frmReportWithparams').submit(function () {
$.ajax({
url: "#Url.Content("~/LeftMenu/SendReportWithParameter")",
type: "POST",
data: $('#frmReportWithparams').serialize(),
success: function (result) {
if (result.IsSuccess == true) {
alert("Thank You.")
$('#modalHomeIndex').dialog('close')
}
else {
alert("'Error Occurs.Try Later.")
$('#modalHomeIndex').dialog('close')
}
}
})
return false;
})
actually the code is for C#, but i just set where to post a form in ajax.
look at #Url.content where i passed the values where my form will be posted.
and the parameters are serialized in data field.
if you have any other query then ask further...
Why Use $ in js variable this is wrong.
Use This One.
var form = $(this);
var url = $form.attr('action');
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
try this may be this will work
<script>
$(document ).ready(function() {
$('#kys_SignUp_form').on('submit', function(e) {
e.preventDefault();
});
});
// ================ SUBMIT =====================
$('#kys_SignUp_form .form_submit').on('click', function(e){
e.preventDefault();
var $form = $(this);
var $email = $("#email").val();
var $username = $("#username").val();
var $password = $("#password").val();
$.ajax({
type: 'POST',
url: 'kys_SignUp.php',
dataType: 'json',
data: { email: $email, password: $password, username: $username },
success: function(data) {
alert("Transaction Completed!");
},
error : function( errorThrown) {
alert('errorThrown ' + errorThrown);
}
});
});
</script>
HTML
<form role="form" method="post" id="kys_SignUp_form">
<div class="form-group">
<label for="email" >Email address:</label>
<input type="email" style="width: 300px" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="Username" >Username:</label>
<input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-default form_submit">Submit</button>
You need to do two things.
1- Change var var url = $form.attr('action'); to
var url = $("#kys_SignUp_form").attr('action');
2- Add a return statement just before you submit function ends
complete script will look like below-
<script>
$( document ).ready(function() {
// Handler for .ready() called.
$("#kys_SignUp_form").submit(function(event){
alert("hello there");
event.preventDefault();
var form = $(this);
var url = $("#kys_SignUp_form").attr('action');
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: 'POST',
url: url,
data: { email: email, password: password, username: username },
success: function(data) {
alert("Transaction Completed!");
}
});
return false;
});
});
</script>

How do I POST multiple form data to PHP

I am trying to send data from a form into a php for it then to write it into a html, without loading into onto php file page. The var_dump shows the data is ready, it somehow just doesn't want to pass over to the php...
<!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
<meta charset="UTF-8" content="bla bla bla">
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" language="javascript">$(function(){$('body').on('click', 'input.sumbit', function(){gogosend();});});</script>
</head>
<body>
<form method="post">
<ul class="form">
<li class="short">
<label>First Name<span class="required"></span></label>
<input type="text" name="first" id="first"/>
</li>
<li class="short">
<label>Last Name<span class="required"></span></label>
<input type="text" name="last" id="last" />
</li>
<li class="long">
<label>Email Address<span class="required"></span></label>
<input type="text" name="email" id="email"/>
</li>
<li class="short">
<label>Company Name</label>
<input type="text" name="company" id="company"/>
</li>
<li class="short">
<label>Telephone Number</label>
<input type="text" name="phone" id="phone" />
</li>
<li class="textarea">
<label>Message<span class="required"></span></label>
<textarea name="message" id="message" rows="20" cols="30"></textarea>
</li>
<li class="button">
<input class="sumbit" name="sumbit" id="sumbit" value="Submit" type="submit" />
</li>
</form>
<script>
function gogosend()
{
var dfirs = document.getElementById("first").value;
var dlast = document.getElementById("last").value;
var demai = document.getElementById("email").value;
var dcomp = document.getElementById("company").value;
var dphon = document.getElementById("phone").value;
var dmess = document.getElementById("message").value;
alert(dfirs);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data_first = "first=" +dfirs ;
var data_last = "last=" +dlast ;
var data_email = "email=" +demai ;
var data_company = "company=" +dcomp ;
var data_phone = "phone=" +dphon ;
var data_message = "message=" +dmess ;
alert(data_first);
xhr.open("POST", "mailer.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data_first);
xhr.send(data_last);
xhr.send(data_email);
xhr.send(data_company);
xhr.send(data_phone);
xhr.send(data_message);
}
</script>
<?php
var_dump($_POST);
echo "</br>";
?>
</body>
</html>
And here is the php file code :
<?php
$first = $_POST["first"];
$last = $_POST["last"];
$email = $_POST["email"];
$company = $_POST["company"];
$phone = $_POST["phone"];
$message = $_POST["message"];
$text = "NAME: $first $last <br>
EMAIL: $email<br>
COMPANY: $company<br>
TELEPHONE NUMBER: $phone<br>
MESSAGE: $message<br><hr><br><br><br>";
$file = fopen("contactrequests.html","a+");
fwrite($file, $text);
fclose($file);
?>
How do I rewrite the above for it to work ? For example now it gives me the var_dump for random data that I entered :
array (size=7)
'first' => string '24' (length=2)
'last' => string '225' (length=3)
'email' => string '25g2' (length=4)
'company' => string '2d5' (length=3)
'phone' => string '2d5' (length=3)
'message' => string '2d5' (length=3)
'sumbit' => string 'Submit' (length=6)
I tried How to pass multiple values from ajax to php file But that did not help.
I would suggest sending a JSON object extracted from your form to be accessed by the PHP script... In the PHP script create a PHP class instance or an indexed array from this JSON using this function http://php.net/manual/en/function.json-decode.php
To serialize form to a JSON in javascript client side you can use this http://api.jquery.com/serializearray/
And if I might give an advice, skip using xhr directly... use the jQuery ajax wrapper... it will ensure running on all major browsers the same way without hassle
You just need to format those data according to application/x-www-form-urlencoded.
function gogosend()
{
var dfirs = document.getElementById("first").value;
var dlast = document.getElementById("last").value;
var demai = document.getElementById("email").value;
var dcomp = document.getElementById("company").value;
var dphon = document.getElementById("phone").value;
var dmess = document.getElementById("message").value;
alert(dfirs);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data_first = "first=" +dfirs ;
var data_last = "last=" +dlast ;
var data_email = "email=" +demai ;
var data_company = "company=" +dcomp ;
var data_phone = "phone=" +dphon ;
var data_message = "message=" +dmess ;
var data = ([data_first, data_last, data_email, data_company, data_phone, data_message]).join('&');
alert(data_first);
xhr.open("POST", "mailer.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.send(data);
}
As easy as add a return false; to your gogosend function
( the form submission requires a return false; at the end to stay on the page, btw the data is allready submitted to mailer.php )
VoilĂ  :)

Cannot get form to submit

I'm hoping someone could look over my code and let me know what's going on. I have a form. When it is submitted the popup comes up and tells me that it failed and I get a page that just says "undefined". Anyone got any ideas on A: why the send is failing and B: How I need to amend my JavaScript to get the page to go back to the homepage after submission.
HTML:
<div class="contact-form">
<p class="mandatory">* indicates Manadatory Field</p>
<div data-role="fieldcontain" class="text-field">
<label for="firstname">First Name*:</label>
<input type="text" name="firstname" value="" placeholder="" class="required" id="firstname" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="surname">Last Name:</label>
<input type="text" name="surname" value="" placeholder="" id="surname" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="email">Email Address*:</label>
<input type="email" name="email" value="" placeholder="" class="required" id="email" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="mobilephone">Mobile Number:</label>
<input type="number" name="mobilephone" value="" placeholder="" id="mobilephone" />
</div>
<div data-role="fieldcontain">
<label for="message">Message*:</label>
<textarea name="message" id="message" placeholder="" class="required"></textarea>
</div>
<div class="send">Send Message</div>
JAVASCRIPT
$(function () {
$("#symptomsemployersbutton").click(function () {
$("#symptomsemployers").toggle("slow");
});
});
$('#send-feedback').live("click", function () {
var url = 'submit.php';
var error = 0;
var $contactpage = $(this).closest('.ui-page');
var $contactform = $(this).closest('.contact-form');
$('.required', $contactform).each(function (i) {
if ($(this).val() === '') {
error++;
}
}); // each
if (error > 0) {
alert('Please fill in all the mandatory fields. Mandatory fields are marked with an asterisk *.');
} else {
var firstname = $contactform.find('input[name="firstname"]').val();
var surname = $contactform.find('input[name="surname"]').val();
var mobilephone = $contactform.find('input[name="mobilephone"]').val();
var email = $contactform.find('input[name="email"]').val();
var message = $contactform.find('textarea[name="message"]').val();
//submit the form
$.ajax({
type: "GET",
url: url,
data: {
firstname: firstname,
surname: surname,
mobilephone: mobilephone,
email: email,
message: message
},
success: function (data) {
if (data == 'success') {
// show thank you
$contactpage.find('.contact-thankyou').show();
$contactpage.find('.contact-form').hide();
} else {
alert('Unable to send your message. Please try again.');
}
}
}); //$.ajax
}
return false;
});
PHP
<?php
header('content-type: application/json; charset=utf-8');
if (isset($_GET["firstname"])) {
$firstname = strip_tags($_GET['firstname']);
$surname = strip_tags($_GET['surname']);
$email = strip_tags($_GET['email']);
$mobilephone = strip_tags($_GET['mobilephone']);
$message = strip_tags($_GET['message']);
$header = "From: ". $firstname . " <" . $email . ">rn";
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$today = date("F j, Y, g:i a");
$recipient = 'mark#launchintervention.com';
$subject = 'Contact Form';
$mailbody = "
First Name: $firstname
Last Name: $surname
Email: $email
Mobile Phone: $mobilephone
Message: $message
IP: $ip
Browser info: $httpagent
Referral: $httpref
Sent: $today
";
$result = 'success';
if (mail($recipient, $subject, $mailbody, $header)) {
echo json_encode($result);
}
}
?>
Your conditional statement never fires in your success function because it will always be false. (data == 'success') will never work because your json encoding of that string returns the value, "success" as opposed to success. I don't know why you're json encoding it anyway, but you should do something else such as
$result = array(
'status' => 'success'
);
echo json_encode($result);
Then you can do
(data.status == 'success')
As far as redirecting after the result returns successful, after the following line:
$contactpage.find('.contact-form').hide();
You should do something like:
setTimeout(function(){
window.location = 'mydomain.tld/my-homepage.ext';
}, 5000);
And your element with the class of contact-thankyou should have some type of text like, "We have received your submission. You will be redirected to the home page in 5 seconds.". Then after 5 seconds they will be redirected based on the previously defined setTimeout function.
You also have an rn at the end of your header declaration which i assume should be \r\n, however you do not continue concatentation of the headers and therefore it is not required. Please review the RFC2822 on this.

Trying to add form data to a database using an Ajax request with PHP

I cant quite get my form to add its data to a local database I have setup.
I have a addproducts.php page:
<?php
$title = "Products";
include("Header.php");
include("PHPvalidate.php");
?>
<script src="AjaxProduct.js"></script>
<article>
<section>
<fieldset><legend><span> Add a product to the database </span> </legend>
<form id ="productsform" method="post" onsubmit="return false;">
<input type="hidden" name="submitted" value="true">
<label> Enter a product name: <input type="text" id="name" name="name"/> </label>
<label> Enter a product quantity: <input type="number" id="quantity" name="quantity"/> </label>
<label> Enter a product description: <input type="text" id="description" name="description"/> </label>
<label> Enter a product price: <input type="text" id="price" name="price"/> </label>
<label> Upload a image of the product: <input name="image" accept="image/jpeg" type="file"></label>
<input id="submit" name="submit" type="button" class="reg" value="Add Product">
<div id="check"></div>
</form>
</fieldset>
</section>
</article>
I then have a ajax fetch request to gather up the data to get ready to be posted to the database:
fetch = function () {
var xhr, name, quantity, description, price, target;
xhr = new XMLHttpRequest();
target = document.getElementById("check");
name = document.getElementById("name").value;
quantity = document.getElementById("quantity").value;
description = document.getElementById("description").value;
price = document.getElementById("price").value;
var vars = "name="+name+"&quantity="+quantity+"&description="+description+"&price="+price;
changeListener = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
target.innerHTML = xhr.responseText;
} else {
target.innerHTML = "<p>Something went wrong.</p>";
}
};
xhr.open("POST", "addSQL.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = changeListener;
xhr.send(vars);
}
pageLoaded = function() {
var fetchbutton = document.getElementById("submit");
if(fetchbutton) {
fetchbutton.addEventListener("click", fetch);
}
}
window.onload = pageLoaded;
And finally an addSQL.php
That send the data to the database:
//Stores all information passed through AJAX into the query
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$price = $_POST['price'];
//Adds information to database
$query = "INSERT INTO products (name, quantity, description, price) VALUES ('$name','$quantity','$description','$price')";
//Runs the query
$result = $mysqli->query($query) OR die("Failed query $query");
echo $mysqli->error."<p>";
//
?>
When i try to add dummy data into the form and submit nothing happens with no errors or anything so Im not sure where the point of failure is.
Any help would be appreciated.
I think you're missing this:
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Edit: also now that I look at it, you're vulnerable to SQL injection and an apostrophe in your data will break the query:
$name = $mysqli->real_escape_string($_POST['name']);
$quantity = $mysqli->real_escape_string($_POST['quantity']);
$description = $mysqli->real_escape_string($_POST['description']);
$price = $mysqli->real_escape_string($_POST['price']);
You add some alert() in your code to find the error.
add alert in the every line when you get a value in variable like alert(vars); after the assign value in vars variable

Categories

Resources