AJAX/JQuery success:/error: function manipulation - php

Having some trouble with AJAX/JQuery. Here is the context of my problem followed by a code sample:
What I am attempting to do is call a PHP script called getInfo.php and check whether or not some data is contained within a database. I can write queries easily enough but in terms of the code sample below how can I "tell" the success function to fail if it cannot find data in the database and run the error function instead?
$(document).ready(function(){
getInfo();
function getInfo(){
$.ajax({
type: "GET",
url: "getInfo.php",
data: "do=getInfo",
cache: false,
async: false,
success: function(result) {
$("#myInfo").remove();
alert("Data found");
},
error: function(result) {
alert("Data not found");
}
});
}
});
Any advice would be greatly appreciated. =)

The error handler is used to handle errors in your AJAX call.
You could echo 1 in your PHP script if the data was found and 0 if it was not found. Then you could use an if statement to determine what to do. For example:
success: function(result)
{
if(result == 1)
{
$("#myInfo").remove();
alert("Data found");
}
else
{
alert("Data not found");
}
},

"success" gets called when the returned code is a "200" (successfull request).
"error" gets called whenever another code is returned (e.g. 404, 500).
So I think you can do 2 things:
Let PHP return a 404 so the error function gets called
Let your getinfo.php return a boolean value (usually my approach)
{"success":true, ...}

The 'error' function you're using is for identifying and handling an AJAX error, not a script error. If the script you're calling is found, and it executes without terminating unexpectedly (ie, it has errors!), then its considered a success.
The best thing to do is have your getInfo.php script return something you can use within the success function; such as the number of rows in your result set or something - then you can check in success() whether you have data and code accordingly.

I think your getInfo.php page should just print SUCCESS or FAIL and in your success method do
success: function(result) {
if (result == 'SUCCESS')
{
$("#myInfo").remove();
alert("Data found");
}
else
{
alert("Data not found");
}
}

Related

AJAX is skipping success function

My Ajax function is skipping my success function, but yet I can still get my php script to run.
Below is my JavaScript function containing my AJAX call. Here's an explanation of what I'm experiencing:
If I put a alert("msg"); in my success function, it NEVER gets hit.
It goes to the error function every time.
However, if I put an alert("error"); in my error function, then my php file still runs and my data is entered into the database correctly.
If I removed alert("error"); from the error function, my php file does not run and nothing is added.
... It's almost as if I need that alert message in my error function to halt the code (or something), in order for my my php file to run.
Does this make sense to anyone?
<script>
function AddItem(){
var name = document.forms["additemform"]["nc_name"].value;
var tag = document.forms["additemform"]["nc_tag"].value;
var table = "<?php echo $_SESSION['UserItemTable']; ?>";
var isValid = false;
$.ajax({
type: "POST",
url: "/AddItem.php",
data: {
"Item_Name": name,
"Tag_Num": tag,
"Table_Name": table
},
dataType: "json",
success: function(resp){
console.log(resp);
alert('msg");
if(resp.reply == "Success")
{
}
else
{
}
},
error: function(data, status){
console.log(data, status);
alert("error");
}
}); //end Ajax
The message that is dumped out in my console is this:
{
readyState: 0,
getResponseHeader: function,
getAllResponseHeaders: function,
setRequestHeader: function,
overrideMimeType: function,
…}
Not sure why my code is not executed...
I don't know if you have this typo in your code as well as in this example, but you have written:
alert('msg");
... both a single and a double-quote. That screws up the execution.

Ajax getting cancelled in browser

When I click and run my ajax script, I see this error in Chrome:
Status: cancelled
The json data returns to the page in the url bar. My sql table is updating but the error message I indicate above is displaying and the modal doesn't remain open. I suspect there could be a few problems here but I wonder if anybody notice something.
This ajax script is inside a PHP variable that is why you may see some escaped characters. Here the $row is a PHP array. Please don't get confused.
$("document").ready(function() {
$(".form-inline'.$row["userid"].'").submit(function(event) {
event.preventDefault;
var formData = new FormData($(".form-inline'.$row["userid"].'")[0]);
console.log();
$.ajax({
type: "POST",
dataType: "json",
url: "sponsorship.php",
data: formData,
success: function(response) {
if (response.success) {
$("#myModal'.$row["userid"].'").modal(\'show\');
$(".form-inline'.$row["userid"].'").hide();
$("#paypalform'.$row["userid"].'").show();
$("#alertmessage'.$row["userid"].'").show();
$("#closebutton'.$row["userid"].'").hide();
}
else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
contentType: false,
processData: false,
error: function() {
alert("this error is getting displayed");
}
});
});
});
event.preventDefault is a function. You're referencing it, but not calling it.
The default action of the submit event will therefore happen, causing you to leave the page and terminate the JS.
Don't forget to put () when you are trying to call a function.
The problem is with String conctatination on your JS :
$("#myModal'.$row["userid"].'").modal(\'show\');
$(".form-inline'.$row["userid"].'").hide();
$("#paypalform'.$row["userid"].'").show();
$("#alertmessage'.$row["userid"].'").show();
$("#closebutton'.$row["userid"].'").hide();
You have to either fix the concatination :
$("#myModal'.$row['userid'].'")
Or I'm assuming you are missing the php tags on $row

form.submit inside if-else statement not working

im trying to submit a form on ajax success under if-else statement but it is not working
i dont understand why? see the code below
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/order_validations',
data:$("#orderform").serialize(),
dataType: 'json',
success: function (data) {
if(data.length > 0){
$(".err").html(data);
$(".err").show();
$('html, body').animate({scrollTop: $(".progras-bar-area").offset().top}, 800);
}else{
$("#orderform").submit();
}
},
error:function(){
$(".err").html("Something went wrong...Please try again.");
}
});
Is the back end doing what you expect it to do?
In your signup/order_validations controller, write a simple test:
public function order_validations(){
echo json_encode(array("test"=>"test"));
}
Then, in your AJAX call, try to echo the result:
success: function (data) {
console.debug(data);
alert(data);
}
and check this in your Chrome/Firefox console.
Now you know what you're returning, you should be able to control it properly.
Also, wouldnt it be easier to handle the form submission by sending the data to the back end in your AJAX response rather than submitting it again seperately??
It looks like you are trying to get the length of a json object, which will always return as undefined or 0 because it is not an array.
You can do this to get the count:
var count = Object.keys(data).length;
if(count > 0) {
//your code here
}
There is a lot more detail here: How to list the properties of a JavaScript object
Alternately you can use something like underscore.js. It will allow you to check the size, like so:
_.size(data);

Identifying what is returned when submitting a form using jquery

Is it possible to identify what a page returns when using jquery? I'm submitting a form here using jquery like this:
$("#sform").submit(function() {
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
url: "user_verify.php",
success: function(data) {
$("#form_msg").html(data);
}
});
return false;
});
​
The user_verify.php page does its usual verification work, and returns error messages or on success adds a user to the db. If its errors its a bunch of error messages or on success its usually "You have successfully signed up". Can I somehow identify using jquery if its errors messages its returning or the success message. So that way if its errors I can use that data in the form, or if its success, I could close the form and display a success message.
Yes, it's this:
success: function(data) {
$("#form_msg").html(data);
}
You can manipulate data in any way you want. You can return a JSON (use dataType) encoded string from server side and process data in the success function
success: function(data) {
if(data->success == 'ok'){
// hide the form, show another hidden div.
}
}
so user_verify.php should print for example:
// .... queries
$dataReturn = array();
$dataReturn['success'] = 'ok';
$dataReturn['additional'] = 'test';
echo json_encode($dataReturn);
die; // to prevent any other prints.
You can make you php return 0 if error so you do something like this inside
success: function(data) {
if(data==0){
//do error procedure
}else{
//do success procedure
}
}
Hope this helps
You can do and something like this:
$.ajax({
type:"POST", //php method
url:'process.php',//where to send data...
cache:'false',//IE FIX
data: data, //what will data contain
//check is data sent successfuly to process.php
//success:function(response){
//alert(response)
//}
success: function(){ //on success do something...
$('.success').delay(2000).fadeIn(1000);
//alert('THX for your mail!');
} //end sucess
}).error(function(){ //if sucess FAILS!! put .error After $.ajax. EXAMPLE :$.ajax({}).error(function(){};
alert('An error occured!!');
$('.thx').hide();
});
//return false prevent Redirection
return false;
});
You can checke the "data" parameter in "success" callback function.
I noticed that there is a problem in your code. Look at this line :
data: $(this).serialize(),
Inside $.ajax jquery method, "this" is bind to the global window object and not $('#sform')

jQuery.AJAX post() - a few questions and issues

I'm making a site where a user spams a button and increases their score in doing so.
I don't want the page to refresh when the button is clicked, so I wanna use AJAX to send the data to the server. Here's what I have so far:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#update").click(function() {
$.ajax({
type: "POST",
url: "update.php",
data: "increase",
dataType: "Boolean",
success: function(update) {}
});
});
});
</script>
<button id="update" type="button">Button</button>
<div id="counter"></div>
It's not much at all, I know, but I'm very new to this stuff. The main problem I'm having is with the syntax that you're supposed to use. I want the server to return a Boolean variable if the request is successful, so would I have Boolean in the 'Data Type' in inverted commas, apostrophes or what?
Also, I'm struggling with grasping how the ajax script knows whether it's successful. Is there gonna be something in the 'update.php' script that will return a 'TRUE' or 'FALSE' value?
Finally, the data that's gonna be sent to the php file is supposed to tell the php to update the mysql table with the new score. How should I go about telling the php to update the mysql if it receives the data that the ajax is sending?
Thanks a lot
Something along the lines of this should work:
$.ajax({
type: "POST",
url: "update.php",
data: {"action":"increase"},
success: function(response) {
if(response.error) {
alert(response.error);
return;
}
if(response === 'true') {
//do something
} else {
//do something else
}
}
)};
On the PHP end, your code would likely look like this:
<?php
if(!isset($_POST['action'])) {
echo '{"error": "You must provide a action"}';
exit;
}
$action = $_POST['action'];
if(!in_array($action, array('increase', 'decrease')) die('{"error":"invalid parameters"}');
$action = ($action == 'increase') ? ' + 1' : ' - 1';
//$db is assumed to be a live mysqli object from here on out...
$result = $db->query("UPDATE someTable SET fieldname = fieldname {$action} LIMIT 1;");
echo ($result->affected_rows > 0) ? 'true' : 'false';
?>
The dataType attribute is one of json, xml, html, jsonp, text, or script. Boolean isn't one of the expected types. In this case, you don't want to pay attention to those expected types. jQuery makes an intelligent guess about the type if you pass nothing in based on the MIME type returned by your server.
What you want to do is create a function that will be called by the success callback.
$.ajax({
type: "POST",
url: "http://www.server/path/to/update.php",
data: "increase",
success: function(data, status, xhr) {
functionToProcess(new Boolean(data));
}
)};
The function that is given as an argument to success (an anonymous function, in this case) is called when the Ajax call is complete with a 200 value. Because Ajax is asynchronous (that's what the A is), returning things will do you no good. What you want to do is call another function that will process your boolean value. This I've called functionToProcess in my sample code. For more information, check out the jQuery docs on .ajax().
You can learn about what String values in Javascript produce true versus false boolean values here.
This syntax should work
$(document).ready(function(){
$("#update").click(function(){
$.ajax({type: "POST",
url: "update.php",
data: "increase",
success: function(update) {
if(update)
$("#anyelement").html("Thanks");
else
$("#anyelement").html("Try again !");
}
});
});
});
You can ignore the datatype, because you can parse from any direction
how the ajax script knows whether it's successful
If I understand your point, as far as there is a return to the ajax function the process is success, it is upto you to parse the return and implement the logic.
from you php you do like this:
if(you logic is correct){
//update you database and ... other login goes here
return true;
}else{
return false;
}

Categories