Ajax form submitting successfully but alert error showing up - javascript

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()

Related

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));
}
});

jQuery serialized data not successfully posting to PHP form handler

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();
});
}
};
});

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

Sometime Error Using Session With HTML AJAX

here's my html code
js at index.html
<script>
function get_session() {
$.ajax({
url: 'http://mydomain/getsession.php',
cache: false,
type: 'POST',
success: function (data) {
if (data == "1") {
window.location.href = "home.html";
} else {
window.location.href = "login.html";
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error Code: " + jqXHR.status + ", Type:" + textStatus + ", Message: " + errorThrown);
}
});
};
</script>
and getsession.php at server-side
<?php session_start();
if(isset($_SESSION['username']))
echo "1";
else
echo "0";?>
but sometimes isnt working for getsession ..
*im using vps at digital ocean, maybe wrong at my php.ini ??
Put your website ip address there and try it
http://domain_ip/getsession.php
Try like this....
Script
<script>
function get_session() {
$.ajax({
dataType:'JSON',
type: 'POST',
url: 'http://mydomain/getsession.php',
success: function (data) {
var result=eval(data);
if (result.status == true) {
window.location.href = "home.html";
} else
{
window.location.href = "login.html";
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error Code: " + jqXHR.status + ", Type:" + textStatus + ", Message: " + errorThrown);
}
});
};
</script>
PHP
<?php session_start();
if(isset($_SESSION['username']))
{
$status = TRUE;
}
else
{
$status = FALSE;
}
echo json_encode(array('status'=>$status));
?>
PHP code can be -
<?php session_start();
if(isset($_SESSION['username']))
{
$status = TRUE;
}
else
{
$status = FALSE;
}
echo json_encode(array('status'=>$status));
?>
and ajax code -
<script>
function get_session()
{
$.get('http://mydomain/getsession.ph', function(data) {
//access data variable here for responce
});
}
</script>

Receiving "Uncaught SyntaxError: Unexpected token (" with AJAX

I'm trying to integrate a validation plugin with a form in Bootstrap. When I use the code below, I get the following error:
"Uncaught SyntaxError: Unexpected token (".
I can't figure out whether the issue is with the PHP, the Javascript, or both. Is the PHP coded correctly here?
JavaScript:
$(document).ready(function() {
$('#formBasic').formValidation({
framework: 'bootstrap',
fields: {
firstName: {
validators: {
notEmpty: {
message: 'Name is required'
}
}
},
lastName: {
validators: {
notEmpty: {
message: 'The password is required'
}
}
}
}
})
.on('success.form.fv', function(e) {
e.preventDefault();
var $form = $(e.target);
var bv = $form.data('formValidation');
$.post($form.attr('action'), $form.serialize(), function(result) {
error: function () {
alert("There was an error processing this page.");
return false;
},
success: function (output) {
$('#formBasicResults').html(output.responseText);
alert('success');
}
}, 'json');
});
PHP:
function formBasic(){
$output = 'Output from Form Basic:
';
foreach ($_POST as $key => $value) {
$output .= $key . ': ' . $value . '
';
}
echo $output;
}
if(in_array($_POST['function'], array('formBasic','formAdvanced'))){
$_POST['function']();
}else{
echo 'There was an error processing the form';
}
Your $.post syntax is incorrect where you are declaring the success and error handlers. Try this:
$.post($form.attr('action'), $form.serialize())
.done(function(result) {
$('#formBasicResults').html(result.responseText);
alert('success');
})
.fail(function() {
alert("There was an error processing this page.");
});
You will get the freedom to specify the datatype as json or jsonp or text using $.ajax
So instead of $.post use $.ajax, only additional thing you need to include is the type:post.
$.ajax({
type: "POST",
url: "some.php",
dataType: "json"
data: { name: "John" },
success:function () { //handle success calls},
error:function () { //handle failure calls}
});
REF: http://api.jquery.com/jquery.ajax/

Categories

Resources