Using AJAX to call a PHP script - php

I am using AJAX to call a PHP script. I am using conditions to echo the proper error message in my PHP. When I do this, my AJAX and JQUERY do not work properly.
My JQUERY/AJAX:
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
e.preventDefault();
}
if (taken == 1) {
alert('email taken');
e.preventDefault();
}
}
});
}
My PHP:
<?php
$email = true
if ($email == true) {
echo "taken";
}
?>
But, when I just put:
echo "taken";
The AJAX and JQUERY works exactly how it should and the respective error message pops up. "taken" is being echo'd either way, so I don't get what is going on. What could I be doing wrong?

You're missing your semicolon.
$email = true
needs to be
$email = true;
In your response, you will probably be getting a PHP error - unless your error messages are suppressed.

Related

Show all errors for user after form submit in AJAX

I have a form. If something is wrong then error message is shown. Currently it is only showing one error message, even though I am pushing the error messages into an array in PHP and json encoding the array.
What I would basically like to do is this:
$errors = []; // Array creation
if (strlen($username) < 5) {
// Add this error to our list
$errors[] = 'Username not valid.';
}
if ($password != $passwordRetype) {
// Add this error to our list
$errors[] = 'Password does not match our records.';
}
// Repeat this process for other errors
// Then handle your list of errors
foreach ($errors as $error) {
echo "Error Found: $error<br>";
}
but only in ajax and php.
Currently I have this (a lot of code so skipping some parts):
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
console.log(data);
if (data.status == 'success') {
console.log("success");
} else if (data.status == 'not_image') {
console.log("this is not an image");
} else if (data.status == 'image_exists') {
console.log("this image exists");
}
});
});
This is the PHP
$errors_query = array();
if (!empty($images)) {
$uploadOk = 0;
$errors++;
$errors_query["status"] = 'image_exists';
}elseif(!in_array($file_type, $allowed)){
$uploadOk = 0;
$errors++;
$errors_query["status"] = 'not_image';
}else{
$uploadOk = 1;
$errors_query["status"] = 'success';
}
if($errors > 0){
echo json_encode($errors_query);
exit();
}else{
echo json_encode($errors_query);
exit();
}
It works and shows only one response message, even if both data statuses "image_exists" and "not_image" are present. How can I show all the error messages for the user?
Actually Your ajax jquery code has some problem,You included extra " ); " in the closing of success function part.
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
console.log(data);
if (data.status == 'success') {
console.log("success");
} else if (data.status == 'not_image') {
console.log("this is not an image");
} else if (data.status == 'image_exists') {
console.log("this image exists");
}
});
});
If you check the result in the browser console,then you can see mentioned JavaScript error.
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
dataType :"json",
success: function(data) {
console.log(data.status);
var ajaxResult = data.status;
if (ajaxResult.indexOf("success") != -1) {
console.log("success");
}
if (ajaxResult.indexOf("not_image") != -1 ) {
console.log("this is not an image");
}
if (ajaxResult.indexOf("image_exists") != -1) {
console.log("this image exists");
}
}
});
PHP code is below.
<?php
header("Content-Type:text/json; charset=UTF-8");
$errors_query = array();
$flag1 =0 ;
$allowed = array("png","jpg","jpeg"); // Give the correct values based on your requirement
$images=""; // Assign the correct value based on your program
$file_type= ""; // Assign the correct value
$errors=0;
if (!empty($images)) {
$uploadOk = 0;
$errors++;
$errors_query["status"][] = 'image_exists';
$flag1 =1;
}
if (!in_array($file_type, $allowed)) {
$uploadOk = 0;
$errors++;
$errors_query["status"][] = 'not_image';
$flag1 =1;
}
if($flag1 == 0 ) {
$uploadOk = 1;
$errors_query["status"][] = 'success';
}
if ($errors > 0) {
echo json_encode($errors_query);
exit();
} else {
echo json_encode($errors_query);
exit();
}
?>
What I roughly understood (correct me if I'm wrong) is that
Your PHP code creates an array for errors and loops through some if-else statements to check for errors for the uploaded file and add the errors to the array under the key "status"
Encode into JSON and pass it to your AJAX code
Your AJAX code will then return the error message based on the return JSON
I found some problems with your code:
When you use if-else for your error checking in your PHP file, once the first error has been logged, the other errors will not be checked. This is because as the first if has been accessed, the subsequent if-else and else statements will be skipped. Hence, if the file is determined to exist, your code will not check if it's not an image.
The AJAX has the same fundamental problem as point 1. Once one error has been printed, it will not print out the rest, hence your issue of only showing 1 error message.
If you use the same key in the array, the older errors will be overwritten by the new ones.
To rectify, you can do the following:
Add each error message as an individual element in an subarray of your original array, such as $errors_query[errors][]. This will allow you to use the other elements - like $errors_query[status] - to populate your status. Take a look at the array_push function on how to add an element to the end of an array. The plus of such method is you don't have to worry how many error messages you'll have - just keeping adding to the end of the array.
Your AJAX code should then loop through the subarray that you have created in step 1 ("errors" here) and print them out accordingly.
Unfortunately I don't have a production software in the computer I'm using now, so I can't write a working code for you to copy, but hopefully this allows you to approach a direction.
It is very simple
Just do like this
PHP Code
$errors_query = array();
if (!empty($images)) {
$errors_query['msg'][] = 'Sorry Image not exists';
$errors_query['status'] = FALSE;
} elseif (!in_array($file_type, $allowed)) {
$errors_query['msg'][] = 'not_image';
$errors_query['msg'][] = 'msg2';
$errors_query['msg'][] = 'msg3';
$errors_query['status'] = FALSE;
} else {
$errors_query['msg'][] = 'success';
$errors_query['status'] = TRUE;
}
echo json_encode($errors_query);
jQuery Code
$.ajax({
url: 'http://localhost/welcome/raja',
cache: false,
contentType: false,
processData: false,
type: 'GET',
success: function(data) {
var data = JSON.parse(data);
if (data.status === true) {
console.log("success");
} else {
$.each(data.msg, function( index, value ) {
console.log( index + ": " + value );
});
}
},
});
It is working example i have already tested .Happy Work ............ :)

Why an AJAX call is giving an error timeout response only in Firefox

My ajax call
I make an ajax call to check if the e-mail address is already used to participate. The php-file returns 0 when it is not used and 1 if it is already used. When it is used it'll make an error label to say so.
This works perfectly in Chrome, Safari, Internet Explorer. But is a complete pain in the ass in Firefox. It checks and gives the correct response, but after 5 seconds it gives a timeout.
I have another ajax call to put all the data in the database and it has the exact same problem.
What do I do wrong?
function controleerDeelnemerEmail(){
var emailVal = $('#email').val();
$.ajax( {
type: 'POST',
url:'?page=home&action=check',
dataType:'text',
data: {'email':emailVal},
success: function( data ){
data = parseInt(data);
if(data == 1){
if( $(".emailerror").length == 0 ){
var error = "<label for='email' generated='true' class='error emailerror' style=''>Dit e-mailadres wordt al gebruikt</label>"
$(error).insertBefore( $('#email') );
}
}
}
})
}
Server Side
public function check(){
if(!empty($_POST)){
$content = $this->deelnemerDAO->controleerDeelnemerEmail( $_POST['email'] );
if( $content == 1 ){
echo 1;
}else{
echo 0;
}
exit();
}
}
You should add an error callback to see if the answer returned is one.
A wrong type can be considered as an error by ajax.
function controleerDeelnemerEmail() {
var emailVal = $('#email').val();
$.ajax({
type: 'POST',
url:'?page=home&action=check',
dataType:'text',
data: {
'email': emailVal
}
}).done(function (data) {
// equivalent to success callback
data = parseInt(data);
if (data == 1) {
if ($(".emailerror").length === 0) {
var error = $("<label>", {
'for': 'email',
'generated': 'true',
'class': 'error emailerror'
}).text("Dit e-mailadres wordt al gebruikt").insertBefore($('#email'));
}
}
}).fail(function (response, status) {
alert('fail');
});
}

Get returned data from PHP to ajax

I have this code
$.ajax({
type: 'POST',
url: 'ajaxfunctions.php',
data: {email: email},
success: function(data)
{
if(data == "true" || data == "false")
{
alert("Response")
}
else
alert("Data: " + data);
}
});
with this PHP-Script
if(isset($_POST['email']))
{
$email = $_POST['email'];
$countEmail = $db->getCountEmail($email);
if($countEmail == 1)
echo "true";
else {
echo "false";
}
}
The problem is, that it never comes in the alert("Response") case. Always in the other. In the alert window I then got my full index.html content.. What am I doing wrong?
#devShuba monitor your Ajax request in Chrome here is a previous related post
Request Monitoring in Chrome
maybe the isset($_POST['email']) is returning false, that's why.
can you do a var_dump(isset($_POST['email'])); and check if it evaluates to true?
if no, then you have to check if the email is correctly posted using your javascript.

jQuery AJAX return variable + value possible?

I'm submitting a form via jQuery.ajax()
Now my PHP script is checking if a specific input field is empty, example:
$is_error = $user->is_error;
if($is_error !=0)
{
echo $is_error;
}
Back to my jQuery.ajax() , I'd like to check if the value of $error was true or not, within the sucess: part of the jQuery.ajax() call.
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(data)
{
// show response from the php script if there is an error message
// like:
// if(is_error) {show specific error message}
// else {show everything positive message}
}
});
Is it possible to check the PHP variable's value in there? Like if/else ?
Best regards!
if($_POST['name'] == "")
{
$error = 1;
}
else
{
$error = 0;
}
echo $error;
This code will echo the value.
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(data)
{
// show response from the php script if $error == 0 or $error == 1.
if(data==1)
....
}
});
Then you check what is the returned value.
With your variable data, you can return values from PHP. And after in your scope success you can check.
You have to echo the error so that it can be returned as data.. The ajax only returns what has been created in html..
In instances like this I would use the following:
if($_POST['name'] == "")
{
$error = 1;
}
else
{
$error = 0;
}
echo $error;
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(response)
{
if(response == 1){
alert('Error');
}else{
alert('No error');
}
}
});
i think you should try the following in php script
echo $error;
and then in jquery.ajax() do
success: function(data){
//data is $error
}

how to output the mysqli_error message at during ajax calling while using jquery?

how to output or alert the mysqli error message during an ajax call?
here's my php code
if(isset($_POST['resumetitle']) || isset($_POST['name']) || isset($_POST['dob']) || isset($_POST['gender']) || isset($_POST['cvid'])){
$result = $db->updatepdetails($_POST['resumetitle'],$_POST['name'],$_POST['dob'],$_POST['gender'],$_POST['cvid']);
if($result){
echo "success!";
} else {
echo "failed! ".$result->error;
}
}
//here's my js code
$.ajax({
type: "POST",
url: "classes/ajax.resumeupdate.php",
data: "resumeid="+cvid+"&resumetitle="+resumetitle+"&name="+name+"&dob="+dob+"&gender="+gender,
success: function(msg){
//window.location = "resumeview.php?cvid="+cvid;
alert(msg);
},
});
after the ajax call, it only pop out the word "failed!" ...i wish to see the mysqli_error too, how's that?
You use $db->error and not $result->error

Categories