My ajax request is always failing with status 0. The PHP file being called is executing all the code. I am unable to locate the reason why the request is failing.Here is the ajax code:
$(document).ready(function() {
// Get the form.
var form = $('#reg-form');
// Get the messages div.
var formMessages = $('#login_form');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
//e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
alert("Data submitted");
var submitresponse = $.ajax({
type: 'POST',
url: "mailer.php",
data: formData,
dataType: "json",
});
submitresponse.done(function(response) {
alert("Hi");
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
alert(response);
// Set the message text.
$(formMessages).text(response);
// Clear the form.
//$('#name').val('');
//$('#email').val('');
//$('#Address').val('');
});
submitresponse.fail(function(xhr,status,response) {
alert("Hii");
console.log(arguments);
alert(status);
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
//if (data.responseText !== '') {
alert(xhr.responsetext);
// $(formMessages).text(data.responseText);
//} else {
//$(formMessages).text('Oops! An error occured and your message could not be sent.');
//}
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
// This is the default error handler for ajax request.
// Extract all the information required to understand.
var requestResponse = {
url: ajaxSettings.url,
method: ajaxSettings.type,
data: ajaxSettings.data,
httpStatus: jqXHR.status,
error: thrownError || jqXHR.statusText,
data: ajaxSettings.data
};
console.error(requestResponse)
// Notify the user so he might not wonder.
alert('Something went wrong, Please try again');
});
});
});
});
The PHP Code is as follows:
<?php
$servername = "*";
$username = "*";
$password = "*";
$dbname = "*";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
//die("Connection failed: " . $conn->connect_error);
die("Something went wrong. Please try again or contact front desk. <br/>");
}
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$address = trim($_POST["Address"]);
$class = $_POST["class"];
$school = $_POST["school"];
$city = $_POST["City"];
$fname = $_POST["f_name"];
$mobileno = $_POST["mobileno"];
// Check that data was sent to the mailer.
if ( empty($name) OR empty($address) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$sql = "INSERT INTO registrations(Name, Father_Name,Email,Class,School,Address,City,Mobile_No,Reg_time) values ('$name','$fname','$email','$class','$school','$address','$city',$mobileno,now())";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
//echo "Your Information Was Successfully Posted";
mysqli_close($conn);
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = $email;
// Set the email subject.
$subject = "ISMART Registration";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$address\n";
$email_content .= "Class: $class\n";
// Build the email headers.
$email_headers = "From: ismart#asd.co.in";
// Send the email.
if (mail($recipient, $subject, $email_content,$email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Console log shows:
Object {url: "mailer.php", method: "POST", data: "name=Nitish+Garg&f_name=sdfs&class=11&school=DAV+P…+1-A%2C+PWSSB+House%2C+Barakuan+Road&City=Patiala", httpStatus: 0, error: "error"}
Please help!
httpStatus with a 0 means that the Ajax call isn't getting a complete response from the server. There's a disconnect somewhere and you're either not getting anything from the server or just not the full response. I'd check on timeouts first.
Related
My AJAX function is not running my PHP script. I have a similar function for my signup and it is working without any issues. The AJAX function runs to the end of the done call but the first line in the PHP file that creates a cookie does not run.
I have outputted the data(result) to console and that all looks good. No errors come up and I have enabled PHP errors on my server which I have full control over. The server is fine as this exact approach was used for the sign-up portion of the website and it works.
JQuery
$('#login-form').on("submit", function(e){
var dataString = $(this).serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "bin/login.php",
data: dataString
}).done(function (result, status, xhr) {
// Display message back to the user here.
window.location.replace('./app/');
console.log("Login Completed!");
}).fail(function (result) {
// TASK: Add a visual element on the page for errors.
if (result.status == 522){
alert("Email not verified!");
} else if (result.status == 523){
alert("Password was incorrect!");
} else if (result.status == 524) {
alert("User account not found!");
}
});
return false;
});
PHP
<?php
setcookie("TestCookie", "login.php", none, "/");
if (array_key_exists('emailAddress', $_POST) && array_key_exists('password', $_POST)){
$emailAddress = $_POST["emailAddress"];
$password = $_POST["password"];
// Connect to the database with this standard connect PHP script.
include('connectDB.php');
// Check the link was established.
if (!mysqli_connect_error()) {
$sqlget = "SELECT id, emailAddress, userPassword, userRole, emailVerified FROM users WHERE emailAddress=\"$emailAddress\"";
$sqldata = mysqli_query($dbconn, $sqlget);
if (mysqli_num_rows($sqldata) == 1){
// One user was found.
$userInfo = mysqli_fetch_array($sqldata);
setcookie("Account", "found", none, "/");
if ((password_verify($password, $userInfo["userPassword"])) {
setcookie("Password", "OK", none, "/");
if ($userInfo["emailVerified"] == true) {
setcookie("loginId", $userInfo["id"], none, "/");
} else {
// Email was not verified.
header('HTTP/1.1 522 Email Not Verified');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
} else {
// Password verification failed.
header('HTTP/1.1 523 Password verification Failed');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
} else {
// No user found in the system
header('HTTP/1.1 524 User not Found');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
} else {
// Place code to tell the user there was an internal DB error.
// Possibly a standard error message. Lets not scare the user.
header('HTTP/1.1 500 Internal Server Error');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
}
?>
I found the problem. I had one too many brackets on line 18. I changed the line to the following and the PHP script ran.
if (password_verify($password, $userInfo["userPassword"])) {
if ($userInfo["emailVerified"] == true) {
setcookie("loginId", $userInfo["id"], 0, "/");
} else {
// Email was not verified.
header('HTTP/1.1 522 Email Not Verified');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
} else {
// Password verification failed.
header('HTTP/1.1 523 Password verification Failed');
header('Conent-Type: application/json; charset=UTF-8');
die(json_encode($result));
}
I am doing email verification on my website. When user submits the form, it starts ajax post request, which posts the email to PHP which compares it with a datebase.
Than still in the form verification process, I have ajax GET request, which should return from the same PHP file whether the email has already been used.
But. Everything works fine when I proceed to the PHP, but GET request is always blank. URL of POST request is EmailDuplication.php but URL of GET is EmailDuplication?_=somerandomnumbers. Might that be the problem?
I am not experienced in this, will be glad for any help.
Here are the codes
JavaScript
function EmailSendForDupe()
{
$.ajax({ url: '/files/EmailDuplication.php',
type: 'post',
async: false,
cache: false,
timeout: 30000,
data: {email: email.toString},
success: function (){
window.alert("email sent");
}
});
}
function EmailDuplication()
{
$.ajax({ url: '/files/EmailDuplication.php',
type: 'get',
async: false,
cache: false,
timeout: 30000,
success: function (callback){
console.log(callback.length);
console.log(callback);
if (callback.length !== 0){
window.alert("Email is already in use");
return false;
}
else {
window.alert("Email valid");
return true;
}
}
});
}
PHP
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
$conn = mysqli_connect($servername, $username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
$email = $_POST['email'];
echo "AHOJ";
$Emailquery = "SELECT * FROM Members WHERE email='$email' ";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
}
else {
echo "User Email is already in use.";
}
}
?>
First, I would advise cleaning up your PHP and making sure it is not vulnerable to SQL Injection.
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
$returnData = new array();
$conn = mysqli_connect($servername, $username,$password,$dbname);
if (mysqli_connect_errno()) {
$returnData['SQL Error'] = "Connect failed: %s\n", mysqli_connect_error();
header('Content-Type: application/json');
echo json_encode($returnData);
exit();
}
if(isset($_POST['email'])){
// POST
$email = mysqli_real_escape_string($conn, $_POST['email']);
$resultData["AHOJ"] = true;
$Emailquery = "SELECT * FROM Members WHERE email='$email' LIMIT 1;";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
$resultData['inUse'] = false;
$resultData['email'] = $_POST['email'];
} else {
$resultData['inUse'] = true;
}
} else {
// GET
$resultData["AHOJ"] = false;
$resultData['inUse'] = true;
}
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($returnData);
die();
?>
This will return JSON details back to your jQuery script and can be more helpful than plain text.
I also use mysqli_real_escape_string() to help escape any potential injection attempts. I would advise switching to Prepared statements: http://php.net/manual/en/mysqli-stmt.prepare.php
In your JavaScript, you will want to make a few changes too.
function EmailSendForDupe(email){
$.ajax({
url: '/files/EmailDuplication.php',
type: 'post',
cache: false,
timeout: 30000,
data: {
email: email.toString()
},
dataType: "json",
success: function (json){
console.log(json);
if(json.inUse == false){
alert("Email Sent to " + json.email);
} else {
alert("There may have been an error: " + json.error);
}
}
});
}
function EmailDuplication(email){
$.ajax({ url: '/files/EmailDuplication.php',
type: 'get',
data: {
email: email.toString()
},
dataType: "json",
cache: false,
timeout: 30000,
success: function (json){
console.log(json);
if (json.inUse){
window.alert("Email is already in use");
} else {
window.alert("Email valid");
}
}
});
}
Hope this helps.
Generally you want to use async: true.
Also, you do not want to allow the form submit to actually Happen, as that blows away your whole page (reloads the entire thing, if not navigates to somewhere else entirely). So in fact the blank get you could be seeing could be the form submit blowing away your page.
If you are sending ajax requests, the trigger for those simply needs to be a button with a click handler, not an actual submit (unless in that submit input you do something like "onclick='doMyAjax();return false;'" so that the submit action does not actually occur).
If you are actually uploading a file, which for the purpose you appear to be showing here dear goodness please don't let the client drive that functionality via files on their system, the upload post needs a target to post To, so it does not hit your page. For that, the classic embedding of an iframe is still the way to go. Ugh.
posting to an iframe
I have no idea why Two requests need to be sent to do the job. It should probably be just one POST (assuming the ultimate outcome here is you want to send an email if it is a valid email), and the server checks the email and then does the send if it is valid.
And do not use GET versus POST to distinguish what the server should do (such as verifying an email versus sending one) - the Request itself or the Url, for example include "action=verifyEmail" in your form data being passed up, to tell the server what to do rather than it assuming just because it's a POST.
Hopefully some of this is helpful.
you are missing to handle GET Request Data.if some try to using get URL then your code don't have any condition to handle it. check modified code.
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
$conn = mysqli_connect($servername, $username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
$email = $_POST['email'];
echo "AHOJ";
$Emailquery = "SELECT * FROM Members WHERE email='$email' ";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
}else {
echo "User Email is already in use.";
}
}else{
echo " Get Method Data";
}
?>
Please try it and give your feedback.
so I am a php beginner and i was making a login app with server and client side validation .I want to throw an error to the login page when the password is wrong after matching it with db or if email is not unique ..well something like that.
Thank you
To display authentication error after checking from DB you need to use ajax
var username = "....";
var password = "....";
$.ajax({
url: "/login",
method: "POST",
data:{username,password}
}).done(function(data) {
if(data.success){
$("#msg").html("Success");
}else{
$("#msg").html(data.err_msg);
}
});
In php files
<?php
function checkAuthentication(){
$errormsg = "";
$result = true;
try {
//your data and query to check 'username' and 'password'
if(!$password_match){
$result = false;
$errormsg = 'Invalid credential';
}
} catch (Exception $exception) {
$result = false;
$errormsg = 'Database error! ' . $exception->getMessage();
}
//return json data
return json_encode(["success"=>$result,"err_msg"=>$errormsg]);
}
?>
There are much more things to do but you can think this way to start
Please be patient with me. I've been spending 1 hour on internet trying to look for a solution, but nothing seems working. And yet I thought I understood how it works.
I'm hosting my website on Altervista. What I would like to do is the following: I send login credentials, if there is some problem, echo an error message (depending on the type of error), else go to the home page:
process_info.php
<?php
ob_start();
if($_POST["nickname"] and $_POST["password"]) {
$username = $_POST["nickname"];
$password = $_POST["password"];
}
else
{
echo "Please fill the form";
exit();
}
$conn = new mysqli("localhost", $username, $password, "db");
if ($conn->connect_error) {
echo "Connection failed"; // $conn->connect_error
}
$conn->close();
session_start();
$_SESSION["nickname"] = $username;
$_SESSION["password"] = $password;
ob_end_clean();
header("location: ../interno/home/home.php");
exit();
?>
This is how I send the login information in my login.php:
<script>
$(document).ready(function(){
$("#invia").click(function(){
var n = $("#nickname").val();
var p = $("#password").val();
$.post("php/invia_credenziali.php",
{
nickname: n,
password: p
},
function(data,status){
//alert("Data: " + data + "\nStatus: " + status);
window.alert(data);
});
});
});
</script>
But my browser doesn't jump to home. Instead I get the window.alert message.
How can I solve this?
I have finally managed to get a form to post data using ajax to a php file however i keep encountering the following error:
"Notice: Undefined index: course_title in /Applications/XAMPP/xamppfiles/htdocs/insights/ManageCourses_UpdateSubmit.php on line 26
Notice: Undefined index: course_code in /Applications/XAMPP/xamppfiles/htdocs/insights/ManageCourses_UpdateSubmit.php on line 27
NULL
NULL
record updated"
i find to be bizarre because it does update the record fine when i check the mysql table and when i refresh the page the updated values are shown.
the ajax script which is triggered when the button is clicked is:
<script>
function myCall() {
var request = $.ajax({
url: "ManageCourses_UpdateSubmit.php",
type: "GET",
dataType: "html"
});
var data = $('#updateForm').serialize();
$.post('ManageCourses_UpdateSubmit.php', data);
request.done(function(msg) {
$("#updateForm").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
I have noticed when i remove this from the AJAX code i don't get the error message however i need the page to refresh once the value has been updated.
request.done(function(msg) {
$("#updateForm").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
sorry about that forgot to submit the main file
the ManageCourses_UpdateSubmit.php file is:
<?php
include "db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $db_conx->prepare("UPDATE course_details SET course_title = :course_title
WHERE course_code = :course_code");
$course_title = $_POST['course_title'];
$course_code = $_POST['course_code'];
echo var_dump($course_title)."<br>";
echo var_dump($course_code)."<br>";
$sql->bindParam(':course_title', $course_title, PDO::PARAM_STR);
$sql->bindParam(':course_code', $course_code, PDO::PARAM_STR);
/*** execute the prepared statement ***/
$sql->execute();
/*** success message ***/
$message ='record updated';
}
catch(Exception $e)
{
$message = 'Message: ' .$e->getMessage();
}
?>
<html>
<head>
<title>Update Course</title>
</head>
<body>
<p><?php echo $message; ?>
</body>
</html>
any ideas?
You are making 2 requests. The 1st is a GET request, so there are no POST variables set. There is no need for this request, the post request will also return a response, so you can use that:
function myCall() {
var data = $('#updateForm').serialize();
$.post('ManageCourses_UpdateSubmit.php', data, function(response){
//display message
$("#updateForm").html(response);
//'soft'reload parent page, after a delay to show message
setTimeout(function(){
window.location = window.location;
},1000);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
Also, note that you dont want the response to contain <head> and <body> tags, as it is being added to an existing page, so ManageCourses_UpdateSubmit.php should end like this:
catch(Exception $e)
{
$message = 'Message: ' .$e->getMessage();
}
die($message);
//nothing else after this