jQuery POST handling errors - php

Explanation
I am sending a POST, and in PHP I am checking if username already exists in database.
If yes, return an error.
But the thing is, I can't use the same function(data) because I want the error to be located in another div.
$.post("events.php?action=send", { data : $(this).serialize() }, function(data)
{
$("#processing").html('');
$("#comments").html(data);
});
Problem
I can't have two variables in anonymous function, like function(data, error), then how am I supposed to fetch the 'error' PHP printed e.g 'User already exist's in database', and then put it in the #errors div?

It depends on how you are handling the error in your PHP code.
In order to even end up in the error handler you need to set the HTTP statuscode to "5XX".
What you probably want to do is to serialize an error object in case the user already exists, and handle it in the success handler like you are doing now:
PHP:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$data = array('error' => 'something went wrong');
echo json_encode($data);
JS:
function(data){
if(data && data.error){
//there was an error, handle it here
console.log(data.error);
} else {
//do something else with the user
console.log(data);
}
}

In PHP you can return json error, like print '{"error":'.json_encode($error).'}' and then, in your js put in desired div
$.post("events.php?action=send", { data : $(this).serialize() }, function(data)
{
$("#processing").html('');
$("#comments").html(data);
$("#error").append(data.error);
});

I suggest you to return data as a json string from your server. If you do that, you can get an object from $.parseJSON(data);
// In your php code
$result = new stdClass();
$result->userExists=false;
echo json_encode($result);
Now inside your anonymous function:
// Javascript
data = $.parseJSON(data);
console.log(data);
if (data.userExists) alert("User exists!");

Related

Send html answer from PHP to Ajax

Here is what I'm trying to do:
I use an Ajax call to select messages from my database, I echo the content in my PHP and i try to get the echoed html in the Ajax success. But it does not work. Here is the code.
JQUERY:
function SelectMessages()
{
console.log("Selecting messages");
console.log("Talk = " + talk);
$.ajax({
url: "select_messages.php",
type: "GET",
data: "talk=" + talk,
success: function (html) {
alert(html);
console.log("In success");
$("#message_box").prepend(html)
},
error: function (html) {
alert(html);
console.log("In error");
}
});//ajax()
}//SelectMessages()
PHP:
<?php
//SELECTING MESSAGES
require 'dbconnect.php';
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
if ($_GET['talk'] != "") {
$request = $bdd->prepare('SELECT AUTHOR,CONTENT FROM MESSAGE WHERE TALK = :talk');
$request->execute(array("talk"=>$_GET['talk']));
while ($data = $request->fetch(PDO::FETCH_ASSOC)) {
echo' <p> '.$data['CONTENT'].'</p>';
}
}
?>
Using this code, I get "In error" displayed on the console and the code in the alert is "[object Object]". However, the status of my query is "OK" in my browser and the echoed result in the network window is the one expected with all the right values of messages.
I just don't understand why I get through the error instead of success.
Please do not mark this as a duplicate as I have already checked and tested the Ajax/PHP solutions and did not get any result.
In your php file you have set content type header as follows
header('Content-type: application/json');
but normally echoed the response as plain text/html. Either you have to send the response in json.
echo json_encode($data['CONTENT']);
Or remove content-type header as json.

Jquery Callback Was Not Called

I've Googled every instance of this error I can find, and none of the solutions work for me. In essence, I am doing what others have suggested. Despite that, I am receiving an error that my callback function is not being called. I am using Ajax/Jquery/JASONP to do a cross domain form submission using GET. Here is my code on the form side:
$(document).ready(function() {
$("#ajaxform1").submit(function(e){
e.preventDefault();
var surl = "http://blahblah/test_create_user.php?callback=?";
$.ajax({
type: 'GET',
url: surl,
crossDomain: true,
data: $('#ajaxform1').serialize(),
dataType: "jsonp",
success: function(msg) {
$.each(msg, function (index, value) {
if(value==1)
{
alert("New User Added");
} else {
alert("User Already Exists")
} }
});
},
error: function(xhr, status, error) {
var myerror = xhr+" "+status+" "+error;
alert("Failure Connecting to Kayako. Please Try Again("+myerror+")"); }
});
Here is the applicable snippet of my PHP Code:
if($USER_CHK->first()->id){
$data = array('msg' => '0'); // user exists
else {
$data = array('msg' => '1'); // User added
}
//echo customerAdded(FALSE);
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization,X- Requested- With');
header("Content-type: application/json");
$data = array('msg' => '0');
print $_REQUEST['callback']. '('.json_encode($data).')';
exit;
});
});
My debugging shows that all form variables are getting posted.
The PHP code returns: jQuery11020900643879813015_1397599599587({"msg":"1"})
Yet the error indicating the callback was not called is thrown.
How does the request looks like on the server side?
I have a working example which is very similar to what you have. The only difference is that the content type I am replying with is:
'text/javascript'
Also, my JSONP message includes a semicolon at the end (which I think is not really a cause for failure).
returnJSONP = $_REQUEST['callback']. '('.json_encode($data).');';
If you were able to resolve, could you please post the solution?
I gave up trying to get this working and, instead, posted to a local php script which then used CURL to post to the remote server. I echo the CURL results back to the jQuery function and all works well.

jQuery JSON PHP Request

I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).

How to return a null json_encode object

I basically have an ajax function which gets the latest posts from a database, what I want to know is if no data is found what should I return seeing as returning null seems to be an issue for firebug?
php code
function getLatestChat(){
global $session, $form;
$data = $session->getLatestChat(mysql_real_escape_string($_REQUEST['withUser']),
mysql_real_escape_string($_REQUEST['ignoreMessages']));
if($data){//successful
echo json_encode($data);
}
return;
}
jquery code
function getLatestChat(){
var ignoreMessagesArr = $(".chatID").map(function(){ return this.value;}).get().join(",");
$.ajax({
traditional: true,
dataType: "json",
type: "GET", url: "include/process.php",
data:{
getLatestChat: "true",
withUser: currentCCID,
ignoreMessages: ignoreMessagesArr
},
success: function(data){
$.each(data, function(i, elem){
$('.chat-latestContainer').append(elem.value);
});
}
}
});
at the moment the method either returns the $data object or null.
You can return an empty object to represent no data in the object:
return '{}';
Or if your Javascript code expects an array, return an empty array:
return '[]';
Run a simple
if(isset($retunValue)){
//code
}
check on it to check to see if its set.
you can also try a
if(!empty($returnValue)){
//code
}
in your if code you can set it to whatever fits your needs for further use. If it's unneeded you can disregard it and just pass your function something back that wont throw an error.
Rewrite as (for example):
function getLatestChat($session, $form){
$ret = {};
$data = $session->getLatestChat(mysql_real_escape_string($_REQUEST['withUser']),
mysql_real_escape_string($_REQUEST['ignoreMessages']));
if($data){//successful
$ret = json_encode($data);
}
return $ret;
}
echo getLatestChat($session, $form);
In this situation, I'm inclined to explicitly state th response type, but maybe there are more established practices...
<?php
header('Content-Type: application/json');
// ... do stuff here: fetch data, json_encode etc.
// No data, no response
if (strlen($json) === 0) { // assuming we json encoded the data above
header('HTTP/1.1 204 No Content');
exit();
}
// everything is ok
header('HTTP/1.1 200 OK');
echo $json;
I just checked this on FF11 and the latest Firebug, and it seems to work okay.

How do I return a proper success/error message for JQuery .ajax() using PHP?

I keep getting the error alert. There is nothing wrong with the MYSQL part, the query gets executed and I can see the email addresses in the db.
The client side:
<script type="text/javascript">
$(function() {
$("form#subsribe_form").submit(function() {
var email = $("#email").val();
$.ajax({
url: "subscribe.php",
type: "POST",
data: {email: email},
dataType: "json",
success: function() {
alert("Thank you for subscribing!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
});
</script>
The server side:
<?php
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
if($senderEmail != "")
$query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();
$response_array['status'] = 'success';
echo json_encode($response_array);
?>
You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.
<?php
header('Content-type: application/json');
echo json_encode($response_array);
?>
Additional fix, you should check whether the query succeed or not.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
On the client side:
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
Hope it helps.
Just so you know, you can use this for debugging. It helped me a lot, and still does
error:function(x,e) {
if (x.status==0) {
alert('You are offline!!\n Please Check Your Network.');
} else if(x.status==404) {
alert('Requested URL not found.');
} else if(x.status==500) {
alert('Internel Server Error.');
} else if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
Some people recommend using HTTP status codes, but I rather despise that practice. e.g. If you're doing a search engine and the provided keywords have no results, the suggestion would be to return a 404 error.
However, I consider that wrong. HTTP status codes apply to the actual browser<->server connection. Everything about the connect went perfectly. The browser made a request, the server invoked your handler script. The script returned 'no rows'. Nothing in that signifies "404 page not found" - the page WAS found.
Instead, I favor divorcing the HTTP layer from the status of your server-side operations. Instead of simply returning some text in a json string, I always return a JSON data structure which encapsulates request status and request results.
e.g. in PHP you'd have
$results = array(
'error' => false,
'error_msg' => 'Everything A-OK',
'data' => array(....results of request here ...)
);
echo json_encode($results);
Then in your client-side code you'd have
if (!data.error) {
... got data, do something with it ...
} else {
... invoke error handler ...
}
In order to build an AJAX webservice, you need TWO files :
A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)
So, first you call your webservice using this JQuery syntax, in the JavaScript file :
$.ajax({
url : 'mywebservice.php',
type : 'POST',
data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
dataType : 'json',
success: function (data) {
alert("The file is "+data.fichierZIP);
},
error: function(data) {
//console.log(data);
var responseText=JSON.parse(data.responseText);
alert("Error(s) while building the ZIP file:\n"+responseText.messages);
}
});
Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:
<?php
//...
//I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
//$errors is a string that may contain an error message while preparing the ZIP file
//In the end, I check if there has been an error, and if so, I return an error object
//...
if ($errors==''){
//if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['ZIPFILENAME'] = basename($filename);
print json_encode($result);
} else {
//if there is an error, you should return a special header, followed by another JSON object
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['messages'] = $errors;
//feel free to add other information like $result['errorcode']
die(json_encode($result));
}
?>
Server side:
if (mysql_query($query)) {
// ...
}
else {
ajaxError();
}
Client side:
error: function() {
alert("There was an error. Try again please!");
},
success: function(){
alert("Thank you for subscribing!");
}
adding to the top answer: here is some sample code from PHP and Jquery:
$("#button").click(function () {
$.ajax({
type: "POST",
url: "handler.php",
data: dataString,
success: function(data) {
if(data.status == "success"){
/* alert("Thank you for subscribing!");*/
$(".title").html("");
$(".message").html(data.message)
.hide().fadeIn(1000, function() {
$(".message").append("");
}).delay(1000).fadeOut("fast");
/* setTimeout(function() {
window.location.href = "myhome.php";
}, 2500);*/
}
else if(data.status == "error"){
alert("Error on query!");
}
}
});
return false;
}
});
PHP - send custom message / status:
$response_array['status'] = 'success'; /* match error string in jquery if/else */
$response_array['message'] = 'RFQ Sent!'; /* add custom message */
header('Content-type: application/json');
echo json_encode($response_array);
I had the same issue. My problem was that my header type wasn't set properly.
I just added this before my json echo
header('Content-type: application/json');
...you may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.
Typically, right mouse->inspect on your html page.
Then look in the error console for errors like
Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by
CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource.

Categories