if statement in Ajax callback - javascript

Hi im having a problem refreshing my page when a condition is met in php using ajax, if the php script is successful i want it to reload the page but when it is not then i only want to echo the errors.
The following is the part of my PHP code that returns the 'success' or error message:
if ($login) {
echo "success";
} else {
echo '<p>Username and Password does not match</p>';
};
This is working as i have tested it separately and the user gets logged in even though ajax
The problem i think comes in the ajax call back with the if statement.
Here is the my js script that is running the ajax call back.
$('form.ajax').on('submit', function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
if(response == "success") {
//location.reload();
window.location = "index.php";
} else {
$('#loginError').html(response);
};
}
});
return false;
});
I have tried everything on the net but every time the PHP script is successful it just echo's out the word success rather then redirecting the page or reloading

Thanks chris85 for the perfect advice worked like gold and was able to fix the problem, that was that there was a extra line at the top of my PHP script that I missed and saw it when i used console.log(response), also read the post you linked and it will help with future problems like this for me so thanks again.

Related

AJAX PHP - response is an object with null values

I have a small problem maybe because i am a beginner in ajax programming, i make a function in ajax jquery that calls a php file, which makes a request to the database for informations about a player. When the php file replies to the ajax function, i get an object with null values as an answer.
Is there a line i've missed in my code? or something i forgot to do?
Here is my code,
AJAX function:
$.ajax({
method: 'GET',
url: "webservices/get_infos.php",
timeout: kTimeout,
success: function(response) {
alert(response);
},
error: function() {
alert('error');
}
});
And the php file :
<?php
include("connexion_bdd.php");
$_GET['mail'] = $mail;
$req = $bdd->prepare('SELECT * FROM joueurs WHERE mail = ?');
$req->execute(array($mail));
$reponse = $req->fetch();
$return = array();
$return["user_name"] = $reponse["nickname"];
$return["profile_pic"] = $reponse["profile_pic"];
$return["user_id"] = $reponse["id"];
print(json_encode($return));
?>
In the success of the ajax function, i get this :
{"user_name":null,"profile_pic":null,"user_id":null}
Although the database is not null.
Where do you think is my mistake? php file or ajax function? or both?
Thanks for helping :)
Edit :
I've changed my code according to the remarks i had on the way i pass the variable AJAX->PHP.
I've tested my sql query on my database and it works fine, but i still have the problem of null values after i pass the object from my php file to the succes function of the AJAX/JS file.
Any ideas about what's wrong with my code?
Thanks again.
You have two problems here.
First, you are not sending the mail parameter in your jQuery AJAX request. You need to append the GET parameter to the end of the URL under the url key:
$.ajax({
method: 'GET',
url: "webservices/get_infos.php?mail=youremail#gmail.com",
timeout: kTimeout,
success: function(response) {
alert(response);
},
error: function() {
alert('error');
}
});
The second problem is that you have your $mail variable assignment in your PHP script backwards. It should be
$mail = $_GET['mail'];
$_GET['mail'] is automatically set by PHP when you call the script with a GET request. But since you are referencing $mail in your prepared SQL statement, you want to assign the value of $_GET['mail'] to $mail.

PHP JSON Encoded Object causes Ajax Error

This has been bugging me for the last few hours, and I've tried various searches but never found exactly this issue with an answer. Maybe asking and showing some code will help me get this figured out.
I am using ajax to do a post to PHP, which I want to just give a notification so that I may update a div on the page. In this case, I just need the PHP to say something like "Cfail" which the javascript would use to update page content.
Originally, I was going to try just text responses. So, my PHP for example would be like this:
<?php
session_start(); //Because have an encoded captcha answer.
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
echo 'Cfail';
}
?>
The Javascript would be:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'text',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned=='Cfail'){
alert("I read it right!");
}
}
});
});
});
It would run through the script just fine, but the result never would be what I was asking for. Alert showed the corrct text, however, research indicated that the issue with this was PHP apparently adding white space. The common answer was the encode a JSON response instead. So, I tried that.
Updated PHP:
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
$result = array('result' => 'Cfail');
echo json_encode($result);
exit;
}
?>
Updated Javascript:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'json',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
}
});
});
});
Which now no longer runs successfully. The alert doesn't come up, and the loader object remains visible(indicating the success never goes through). I tried putting an error section to the ajax, and it indeed fired that. However, I had no idea how to parse or even figure out what the error was exactly. The most I got in trying to get it was what PHP was outputting, which was {"result":"Cfail"} .... Which is what I would EXPECT PHP to give me.
I can work around this, I've done a similar set-up with just echoing a number instead of words and it used to work just fine as far as I knew. I'd just like to figure out what I am doing wrong here.
EDIT:
I managed to figure out what the issue was in my case. I had a require('config.php'); between the session start and the json_encode if statement. For some reason having the external file added, which was just me setting a couple variables for the code further down, some hidden character was added before the first { of the JSON object.
No idea why. As I said, it was just a $var='stuff'; situation in the require, but apparently it caused the issues. :/
Use this like
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
//$result = array('result' => 'Cfail');
$data['result'] = 'Cfail';
echo json_encode($data);
exit;
}
?>
This works for your javascript
use the below code, in your success call back, first parse the encoded json object that you are recieving from the back end and access the object property result to check it's value
success: function(returned){
returned = JSON.parse(returned);
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}

How to reload page in ajax based on comparison

I tried to reload the page if session is empty but I am unable to do this as the ajax code as below
function test()
{
$this = $(this);
$.ajax({
url: 'view/test/test.php',
datatype: 'html',
async:true,
beforeSend : function(){
$('#ajax_loader').show();
$('#content').hide();
},
success: function(data){
if(data=='cannot')
{
location.reload(true);
}
else
{
$('#ajax_loader').hide();
$box = $('#content');
$box.after(data);
$box.remove();
}
}
});
}
$(document).on('click','#test',$(this),test);
and the view test file as
<?php include '../../config.php';
if(empty($_SESSION['college_id']))
{
echo "cannot";
return;
}
?>
The above code is used to check whether session exist or not. If session is empty is simply send "cannot". As the I got the success data as "cannot", I tried to reload the page but the reload function does not work in if condition. Without if condition, it does work. What's wrong?
can u try this once in you code it may work for you
if($.trim(data)=='cannot')
{
alert("your session has been expired");
document.location.reload(true);
}
Try to change dataType to text and try . Also try to trim the success call back response data before string comparision
Before using the $_SESSION superglobal variables you must start or resume the session by writing
session_start()
Note: This has to be the very first thing (even before the HTML tags)

Jquery Ajax Fails... randomly succeeds

Here is my problem:
I try to make an Ajax call with JQuery,
this calls a PHP page, the code gets executed, and echoes OK if alright, STOP if not.
I don't get any text back (first problem),
and the real problem is that:
SOMETIMES the query succeeds, but ALWAYS returns an error. (even if my sql query in php page gets executed)
Here is the code :
<script>
$("a.confirm").click(function(event){
var id = event.target.id;
$.ajax({
type :"POST",
url :'./PHP/UTILS/confirm.php',
data :{ "id" : id,
},
beforeSend: function(){
alert("in progress");
},
complete: function(){
alert("done");
},
success: function(){
alert("OK");
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err + "\n");
}
});
});
</script>
This is for the ajax, now the page it calls :
<?php
include "./functionsExt.php";
$db = connectToDb('mydb');
$id = $_POST['id'];
$mysql = $db->prepare("UPDATE `test` SET `test_date_p` = CURRENT_TIMESTAMP, `test_status` = '2' WHERE `test_id` = '$id'");
if($mysql->execute()){
echo "OK";
}else{
echo "STOP";
}
?>
Thanks for help
i would like to suggest that you should try it after removing the comma in data after 'id'.
And i please do mention the following :
echo the post variable and check the response.
then echo that you want and check whether it is coming or not in response
a better way to write the success and failure
success: function(data)
{
alert(data);
}
failure : function(){
alert(failed);
}
It will eventually alert you with the data that you are receiving in response. So it is good for testing purpose.
hope it helps:)
i think i found something interesting...
i tried echoing the post...
The post is well sent to the php file,
But i noticed that :
if i add event.preventDefault(); in my jquery code, i have the post echo + the "ok" displayed in an alert (guess it's the success alert cuz i don't have the log message this time...)
i will try again... (if it works like this, i need then to find a way to re-enable default link click function, i need to refresh the page... the page content is not the same after calling the ajax...)
tried again, and it seems to work now...
but, i don't close the topic, cause i have to add few more queries in my php file now... and i still need a way to refresh the page after execution... any idea?
(thanx stacky, you advice seems to have solved the "main" problem :P )

Ajax, handling the php response in javascript

So I'm learning Ajax and I followed this tutorial: https://phpacademy.org/course/submitting-a-form-with-ajax to create a function that works for any form. This is the complete function:
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
alert(url + ' ' + response);
}
})
return false;
});
As you see all I'm doing is alerting the response, which in this case is php echo. That's where my problem starts, I need a flexible and secure way to handle the javascript/php communication. Preferrably one function for all forms, maybe with if () statements instead of alert(url + ' ' + response); depending on the form url.
The function I need is not very complicated, based on the response I get I will just update the current form with errors.
Aslong as I know what to use in the communication I'm fine from there, echo '1'; as I have now doesn't feel like the ideal solution but it's all I could handle.
So, what type of response should I send from the php page, and where (in the javascript) and how is the best way to handle it? I've heard of json but having a hard time wrapping my head around it. Could someone show a json response sending a basic integer thats easy for my response to pick up as an int?
You can send back a simple JSON response via PHP and check it in your success callback. Make sure you're setting the type to json and in your AJAX call, and using json_encode on the PHP side:
$response = array('response' => 1);
echo json_encode($response);
Output should be:
{ 'response' : 1 }

Categories