jQuery serialized data not successfully posting to PHP form handler - javascript

I’m trying to post some data via jQuery Ajax to a PHP form handler file. It was working earlier, but I wasn’t getting errors when I should have (ie it was always sending an email), so I modified the mess out of my stuff and now the PHP file is no longer receiving the serialized data. Would greatly appreciate some eyes on this. I have a feeling it’s a stupid syntax error, but I’m not seeing it.
JS (jQuery)
$form.submit(function(e) {
e.preventDefault();
var data = $(this).serialize(),
url = $(this).attr('action');
console.log(data);
$(this).addClass('sending');
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success:
function(response) {
console.log("Success: " + data);
if(!response.success) {
formError(response);
} else {
// on success
console.log(`✔ Form submission successful!`);
console.log(response);
// Add success message
$form.append(
'<div class="success-message"><h3>Your Message Was Sent</h3><p>'
+
successMsg
+
'</p></div>'
).delay(10)
.queue(function(){
$(this).find('.success-message').addClass('visible');
$(this).dequeue();
});
$form
.delay(10)
.queue(function() {
$(this)
.removeClass('sending')
.addClass('sent')
.dequeue();
});
$form[0].reset();
}
},
error:
function(xhr, status, error){
console.log("Fail: " + data);
formError(xhr, status, error);
}
});
function formError(xhr, status, error) {
//on failure
console.log('✘ Form submission failed.');
console.log(xhr);
console.log(status);
console.log(error);
if (!$form.hasClass('error')) {
$form
.addClass('error')
.delay(2000)
.queue(function() {
$(this)
.removeClass('error')
.removeClass('sending')
.dequeue();
});
}
};
});
PHP Handler
<?php
$errors = '';
$myemail = '#####';//<-----Put Your email address here.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$company = $_POST['company'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$data = array($name, $email, $phone, $company, $subject, $message);
if(
empty($name) ||
empty($email) ||
empty($phone) ||
empty($company) ||
empty($message)
) {
$errors .= "\n You must fill out required fields.";
}
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email))
{
$errors .= "\n Invalid email address.";
}
if( empty($errors) ) {
$to = $myemail;
$email_subject = "Contact Form: $name";
$email_body = "<html><body>".
"<p>Name: $name<br>".
"<p>Company: $company<br>".
"Email: $email<br>".
"Phone: $phone<br></p>".
"<p><b>Subject:</b></p>".
"<p>$subject</b></p>".
"<p><b>Message:</b></p>".
"<p>$message</p>".
"</body></html>";
$headers = "From: $myemail\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to,$email_subject,$email_body,$headers);
echo json_encode(array("success" => true, "data" => $data));
} else {
echo json_encode(array("success" => false,"error" => $errors, "data" => $data));
}
?>
The PHP handler is returning data so that I can see what's going on, and then I'm console logging it. Here's what I'm getting:
{success: false, error: "↵ You must fill out required fields.↵ Invalid email address.", data: Array(6)}
data: (6) [null, null, null, null, null, null]
error: "↵ You must fill out required fields.↵ Invalid email address."
success: false
__proto__: Object
In other words, the data isn't actually passing to the PHP file. I'm assuming I have some stupid syntax error, but I'm not seeing it. Help! 🙏🏼

You send GET data in Ajax and you try to get POST in your PHP.
Change type to POST in your Ajax function.
$form.submit(function(e) {
e.preventDefault();
var data = $(this).serialize(),
url = $(this).attr('action');
console.log(data);
$(this).addClass('sending');
$.ajax({
url: url,
type: 'POST',
async: true,
dataType: 'json',
data: data,
success:
function(response) {
console.log("Success: " + data);
if(!response.success) {
formError(response);
} else {
// on success
console.log(`✔ Form submission successful!`);
console.log(response);
// Add success message
$form.append(
'<div class="success-message"><h3>Your Message Was Sent</h3><p>'
+
successMsg
+
'</p></div>'
).delay(10)
.queue(function(){
$(this).find('.success-message').addClass('visible');
$(this).dequeue();
});
$form
.delay(10)
.queue(function() {
$(this)
.removeClass('sending')
.addClass('sent')
.dequeue();
});
$form[0].reset();
}
},
error:
function(xhr, status, error){
console.log("Fail: " + data);
formError(xhr, status, error);
}
});
function formError(xhr, status, error) {
//on failure
console.log('✘ Form submission failed.');
console.log(xhr);
console.log(status);
console.log(error);
if (!$form.hasClass('error')) {
$form
.addClass('error')
.delay(2000)
.queue(function() {
$(this)
.removeClass('error')
.removeClass('sending')
.dequeue();
});
}
};
});

Related

Ajax undefined value in PHP

When I call the function I always get an undefined value, I don't understand what can ruin it.
You are logged in as undefined, Error undefined
Ajax script:
function Submit() {
console.log('asd')
$.ajax({
url: "Server.php",
type: "POST",
dataType: "json",
data: {
name: "Test2",
email: "Test#gmail.com"
},
success: function(data, textStatus, jqXHR) {
console.log("You are logged in as: ", data.name);
$('#user').html("You are logged in as: " + data.name);
},
error: function(request, error, data) {
console.log(arguments);
alert(" Can't do because: " + error + " DATA: " + data);
}
})
}
PHP Script:
<?php
header("Content-type: application/json; charset=utf-8");
$errors = [];
$data = [];
if (empty($_POST['name'])) {
$errors['name'] = 'Name is required.';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name'];
}
echo json_encode($data);
?>
I tried every solution in vain, so I still get an indefinite value. I’m slowly starting to think there’s nothing wrong with the script.
You want to use data.name but you never return name. hence the undefined.
I've added data.name in the example below and it seems to work fine.
<?php
header("Content-type: text/html; charset=utf-8");
$errors = [];
$data = [];
if (empty($_POST['name'])) {
$errors['name'] = 'Name is required.';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name'];
}
echo json_encode($data);
?>
Also the parameters used in the succes function are in a different order than you seem to use, in your case the request will have your data in it
the callback parameter not
success:function(request, data, error)
but
success: function(data, textStatus, jqXHR)
data.name of course undefined because it is string
and your Server.php return this
{"success":true,"message":"Success!"}
no data.name but data.success and data.message
so you have to write
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name']; // add this
}

Little problem with ajax. Error-function is executed

i have a little problem with ajax and mysql.
I want to save same data to a database via ajax.
Javascript:
$.ajax({
type : "POST",
url : url_save,
async : false,
data : { item : nr, var : text },
success: function(result_save){
if (result_save.includes('Error')) {
alert("!!! Error !!!");
}
},
error: function(xhr, textStatus, errorThrown) {
alert("!!! Error !!!");
}
});
My PHP-File looks like:
PHP:
<?php
require "config.inc.php";
$db = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME) or die ('Error');
$db->set_charset("utf8");
$sql="INSERT INTO tbl (item, var) VALUES ('$_POST[item]','$_POST[var]')";
if (!mysqli_query($db,$sql))
{
return 'Error';
die();
}
mysql_close($db);
return 'i.O.';
?>
It saves to the database, but the error-function of ajax is executed every time. What is wrong?
A few observations:
jcubic is correct- you don't want to use a JS keyword as a parameter name.
catcon is also correct. Using a prepared statement is FAR preferable to reading the variable directly into your SQL text.
Even if mysqli_query() returns 0, you still want to do a mysql_close($db), don't you?
You would also like to know the specific error, wouldn't you?
SUGGESTION:
PHP:
<?php
require "config.inc.php";
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO tbl (item, var) VALUES (?, ?)");
$stmt->bind_param("is", $_POST[item_id], $_POST[item_value]);
if (!$stmt->execute()) {
$result = "Execute failed: (" . $stmt->errno . "): " . $stmt->error;
}
$stmt->close();
$conn->close();
return ($result) ? 'Success' : $result;
...
JS:
$.ajax({
type : "POST",
url : url_save,
async : false,
data : { item_id: nr, item_value: text },
success: function(result_save){
if (result_save === 'Success') {
console.log('Insert was successful', nr, value);
} else {
alert('mySql Error: ', JSON.stringify(result_save));
}
},
error: function(xhr, textStatus, errorThrown) {
alert('XHR Exception: ' + textStatus + ', ' + JSON.stringify(errorThrown));
}
});

Setting style based on php return through ajax

My AJAX return isn't styling errors with css.
What I am finding is that all my returns from the PHP are displaying with the success property function. All my returns are displaying with the successCSS (Bootstrap).
I am not sure if there is a better way to receive data from my PHP and then style the output accordingly.
<a class="btn btn-primary" onclick="validateForm()">Send</a>
<div class="alert hide" role="alert hide">
<div class="status" id="status"></div>
</div>
function validateForm() {
$.ajax({
url: "register.php",
type: "POST",
data: $('#registration-form').serialize(),
success: function(data, textStatus, jqXHR) {
$('#status').text(data.message).addClass('successCSS');
if (data.code) //If mail was sent successfully, reset the form.
$('#registration-form').closest('form').find("input[type=text],
textarea ").val("
");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text(jqXHR).addClass('errorCSS');
}
});
}
<?php
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
header('Content-Type: application/json');
if ($firstname === '')
{
print json_encode(array(
'message' => 'firstname cannot be empty',
'code' => 0
));
exit();
}
if ($surname === '')
{
print json_encode(array(
'message' => 'Surname cannot be empty',
'code' => 0
));
exit();
}
if ($email === '')
{
print json_encode(array(
'message' => 'Email cannot be empty',
'code' => 0
));
exit();
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
print json_encode(array(
'message' => 'Email format invalid.',
'code' => 0
));
exit();
}
}
$content = "Email: $email \nMessage: $message";
$recipient = "#gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array(
'message' => 'Registration successful !',
'code' => 1
));
exit();
You need to check for code === 0 and code === 1 and reset the class names before making ajax call, so you don't end up adding too many classes.
Try this
function validateForm() {
$('#status').text('').removeClass('successCSS').removeClass('errorCSS');
$.ajax({
url: "register.php",
type: "POST",
data: $('#registration-form').serialize(),
success: function(data, textStatus, jqXHR) {
if(data.code && data.code === 1) {
$('#status').text(data.message).addClass('successCSS');
} else {
$('#status').text(data.message).addClass('errorCSS');
}
if (data.code) //If mail was sent successfully, reset the form.
$('#registration-form').closest('form').find("input[type=text],
textarea ").val("
");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text('error when submitting form ' + textStatus + ' : ' + errorThrown).addClass('errorCSS');
}
});
}

If and else condition inside success in ajax

As the title says I want to run the if and else inside the success condition in Ajax, For example after running the Ajax and sees that there is a record it will go to success then inside the success it must look for the "if statement" and display the alert inside the "if statement" if the statement is true but instead it always display the "else statement" with the alert('no') inside of it, even if there is a record, Thank you
<script>
function renderAttendees(id)
{
///$("#attendeesContent").empty();
var dataString = { "id": id };
$.ajax({
type: 'POST',
url: server+'webservice/crm/viewAttendeesDetails',
data: dataString,
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
cache: true,
success: function(data)
{
if($.trim(data) === 'error')
{
alert('yes');
}
else
{
alert('no');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error connecting to server. " + XMLHttpRequest + ", " + textStatus +", "+ errorThrown);
}
</script>
//My Controller Code
public function viewAttendeesDetails()
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
$data = array();
$id = $_POST['id'];
$AttendeesDetails = $this->model->GetAttendeesDetail($id);
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
}
echo json_encode($data);
exit;
}
?>
//My Model Code
db->prepare("SELECT * FROM crm_contact_list WHERE id = :AttendId");
$stmt->bindParam(":AttendId", $id);
$stmt->execute();
return $stmt;
}
catch (Exception $e)
{
return $e->getMessage();
return $stmt;
}
return;
}
?>
//Here is the result of console.log(data);
Object
email:"kyle#localhost.com"
full_name:"Test kim"
id:"1"
interest:"Test"
number:"123456"
position:"Prog"
venueID:"1"
I would return from your controller something like
{status: 'success', data: myArrayWithFoundData}
so when you receive the ajax response you could do a json_decode, and check the status.
So in you controller you would have
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
$rsp_data = {status: 'success', data: $data};
}else{
$rsp_data = {status: 'error', data: null};
}
echo json_encode($resp_data);
Something like that, so in the ajax response you would do a
var a = JSON.parse(data);
and check the a.status for error

Ajax form submitting successfully but alert error showing up

I created an AJAX form that submits to a php page. This form is submitting successfully in terms of, I am getting the email address in my database and I have a confirmation email that sends out.
However, I am getting an alert message saying "Error|", so obviously it is coming from this:
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
I am unsure of why an error is throwing if it works. Another thing, this form is reloading the page. I have event.preventDefault(); in place, so why would the page be reloading?
I appreciate any help.
<form action="" method="POST">
<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address">
<input type="submit" id="footer-grid1-newsletter-submit" name="submit">
</form>
$(document).ready(function(){
$("#footer-grid1-newsletter-submit").on("click", function () {
event.preventDefault();
var newsletter_email = $("#footer-grid1-newsletter-input").val();
$.ajax({
url: "newsletterSend.php",
type: "POST",
data: {
"newsletter_email": newsletter_email
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert email!");
alert(data);
} else {
/*$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);*/
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
ini_set('display_errors', 1);
error_reporting(E_ALL);
$newsletter_email = $_POST['newsletter_email'];
try {
$con = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("INSERT INTO newsletter (email, subscribed) VALUES (?, NOW())");
if ( false===$stmt ) {
die('Newsletter email prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param('s', $newsletter_email);
if ( false===$stmt ) {
die('Newsletter email bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
if ( false===$stmt ) {
die('Newsletter email execute() failed: ' . htmlspecialchars($stmt->error));
}
} catch(Exception $e) {
die($e->getMessage());
}
Your event doesn't have any reference
.on("click", function () {
should be
.on("click", function (event) {
Then clearing your form. you can do
$("YOUR_FORM")[0].reset()

Categories

Resources