The title almost says it all. I have a jquery code i've written, im not good at it but this is what i achieved:
$("#myForm").submit(function(){
//alert($(this).serialize());
$.post("submit.php", $(this).serialize(), function(data){
if(data == success) {
$("#add_vote").fadeOut("fast");
$("#verification_sent").fadeIn("fast");
$("#wrong").fadeOut("fast");
} else {
$("#wrong").fadeIn("fast");
}
});
return false;
});
The form gets submitted well but the fadeIn and fadeOut's I have does not work. Do anyone know why?
Verify what submit.php returns, and what is in data.
if(data == success) {
This looks suspicious, did you meant if (data == "success") { ? (success is a variable, probably undefined; "success" is a string.)
What is success in:
if(data == success) {
Maybe you mean:
if(data == "success") {
Or else you maybe have misunderstood the $.post function?
$.post("submit.php", $(this).serialize(), function(data){
Lets break it up:
"submit.php" // the url (OK)
$(this).serialize() // The data (OK)
function(data){ // The callback on success
And its only a helper function for the $.ajax method, Witch also have a error callback:
var ajaxObj = $.ajax({
type: 'POST',
url: "submit.php",
data: $(this).serialize()
});
ajaxObj.success(function(){
// Success
});
ajaxObj.error(function(){
// Error
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm wanting to use AJAX to determine whether or not a form's values are acceptable to me (this is not form validation). The AJAX result will determine if the form is submitted or not.
Below, you'll see that I perform an AJAX call when the form is submitted and depending what is returned (either blank which is acceptable, or an error message which is not acceptable), I'd like to return true; or return false; the $("form").submit.
I suspect my trouble to be in the AJAX's success:. Please help me get the result out of the AJAX call so that I can do something like if (result == "") { return true; } else { return false; }.
WORKING:
$("form").submit(function(e) {
e.preventDefault();
var form = this;
var tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "")
form.submit();
else
alert(result);
}).fail(function() {
alert('ERROR');
});
});
ORIGINAL:
$("form").submit(function() {
var tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false,
success: function(result) {
alert(result);
},
error: function(result) {
alert(result); //This works as expected (blank if acceptable and error msg if not acceptable)
}
});
/*
if (result == "")
return true;
else
return false;
*/
return false; //this is here for debugging, just to stop the form submission
});
As the ajax call is asynchronous, you have to prevent the form from submitting, and then when a result is returned, you check if it matches the condition and submit the form with the native submit handler, avoiding the preventDefault() in the jQuery event handler :
$("form").submit(function(e) {
e.preventDefault();
var self = this,
tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "") self.submit();
}).fail(function() {
alert('error');
});
});
use e.preventDefault(); to prevent the form from submitting, and then use this.submit() (isn't calling the jQuery .submit() trigger function, but rather the native <form> .submit() function) to submit the form.
$("form").submit(function(e) {
e.preventDefault();
var tray = $('select[name=tray_id]').val();
var form = this;
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false,
complete : function(result){callback(result, form)}
});
});
var callback = function(result, form){
if(!result)
form.submit();
};
I have a simple PHP script which, when it executes correctly from an AJAX call, ends with:
echo "ok";
Yet when I try to parse this information it tells me its not a string.
In the example below the result is: alert('error: Type Mismatch');
Why does JQuery not read the php echo as a string?
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
success: function (response) {
if(typeof response == typeof 'string'){
if( response == 'ok')
alert('all is good');
else
alert('error:');
} else {
alert('error: Type Mismatch');
}
}
});
Screenshot below shows that the response is correct and simply says 'ok'
As I'm reading from jquery Api Doc I understand that you can get a "string" or something else as a response, based on what kind of dataType you passed (if u did) in your $.ajax object. Otherwise it will be assumpted from jQuery, based on some its own logic.
In my opinion you should avoid every assumption and explicitly pass your dataType based on the response format you'll send.
So,
in case you'll set response.php to return
echo "ok";
you should set dataType "text" in your ajax call:
$.ajax({
url: 'imageUpload.php',
type: 'POST',
dataType: "text",
...
and get the response with:
if(typeof response == "string")
{
console.info(response);
...
Or
in case you'll set response.php to return something like
echo json_encode(array("data" => "ok"));
you should set dataType "json":
$.ajax({
url: 'imageUpload.php',
type: 'POST',
dataType: "json",
...
and get the response with:
if(typeof response == "object")
{
console.info(response.data);
...
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
success: function (response) {
if (typeof response === "string"){
if (response == 'ok')
alert('all is good');
else
alert('error:');
} else {
alert('error: Type Mismatch');
}
}
});
Do it another way:
In you php script echo back a JSON: json_encode("ok");
In AJAX specify dataType: "json" and add event:
complete: function(jsondata, stat)
{
if(stat == "success")
alert( $.parseJSON( jsondata.responseText ) );
}
The response is not string type, it is a PlainObject object.
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
typeof response == 'object' // true
Try this:
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
dataType: "text",
success: function (response) {
if( response == 'ok')
alert('all is good');
else
alert('error:');
}
});
I apologize for my bad english :)
I'm doing php file with ajax request. json response comes in the format of. but in some cases can be redirect. In this case I want the redirect of the page.
Could you please help me. Thank's.
Example PHP File :
<?php
$status = $_POST['status'];
if($status == 'a'){
// return json response
}else{
echo "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>";
}
?>
Example JS File :
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com'
});
Use success function https://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com'
data: { status : statusVar },
success: function(response){
if (response.status == 'a'){
$( "#results" ).append( response);
}else{
window.location = 'http://www.url.com'
}
});
});
Try this.
url: "http://www.my_php_file.com",
success: function(data) {
document.location.href='YouNewPage.php';
}
You need to detect if the response data is valid JSON:
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com',
success: checkAJAX
});
function checkAJAX(data)
{
var response = $.parseJSON(data);
if(typeof response === "object")
{
}
else
{
// If the AJAX response is not JSON, append the HTML to the document
$('body').append(data);
}
}
Return the html that you want to echo as JSON also:
if($status == 'a'){
// return json response
} else {
echo json_encode(array("redirect" => "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>"));
}
And check redirect in the ajax response:
$.ajax({
type: "POST",
dataType: "json",
url: 'http://www.my_php_file.com',
success: function(data) {
if(typeof data.redirect !== "undefined") {
$("body").append(data.redirect);
}
}
});
Just two reminders, there will be no redirection if request fails( no fail callback) and I assume your casual JSON response doesn't have an attribute redirect.
so i am making a $.ajax call and returning json data. in said data there is an element named status. I am testing this: if(data.status === "success"){ ..do something..}. I know that the json data from the $.ajax call is in fact "success" (i know from the developers tools in chrome that the php script is returning {status: success}) however nothing in the if statement is being evaluated. and if i add an else statement to the if statement, that code DOES get evaluated. here is my code:
$.ajax({
type: "POST",
url: "./php/checkuser.php",
datatype: "json",
success: function(data){
console.log(1);
if(data.status === "success"){
console.log(2);
$.get("./mainmenu.html", function(html){
$("#content").html(html);
console.log(3);
});
$.ajax({
type:"POST",
url:"./php/loaduserdata.php",
dataType:"json",
success:function(data){
console.log(4);
if(data.status === "success"){
console.log(5);
var lastlevel = data.lastlevel;
if(lastlevel === 0){
console.log(6);
$("#continue-wrapper").removeClass("enabled").addClass("disabled");
$('<img />').attr('src', "./images/menuitem_continue-disabled.png").attr('id', "continue").attr('alt', "Continue").load(function(){
$("#continue-wrapper").html($(this));
});
} else {
console.log(7);
$("#continue-wrapper").removeClass("disabled").addClass("enabled");
$('<img />').attr('src', "./images/menuitem_continue-enabled.png").attr('id', "continue").attr('alt', "Continue").load(function(){
$("#continue-wrapper").html($(this));
});
}
}
}
});
} else {
console.log(8);
}
},
error: function(thrownError){
console.log(thrownError);
}
});
in the console for output i get 1 and 8. I'm stumped can someone see something that i can't?
In the first ajax request you have datatype it should be dataType, so data is just a string and data.status is undefined.
Im trying to use if else statement in success ajax function, but the value always false and data inserted
I use jQuery v1.7.1, here my code
// Contact Submiting form
function Contact_form(form, options){
$.ajax({
url: 'contact.php',
data: $('#contactform').serialize(),
success: function(data){
if(data.check == '1'){ // if Ajax respone data.check =1 or Complete
$('.notifications').slideDown(function(){
setTimeout("$('.notifications').slideUp();",7000);
}); // Show notifications box
$('#contactform').get(0).reset(); // reset form
}
else if(data.check == '0'){
$('#preloader').fadeOut(400,function(){ $(this).remove(); });
alert("No complete");
return false;
}
},
cache: false,type: 'POST',dataType: 'json'
});
}
if else is bad in success function use
function Contact_form(form, options){
$.ajax({
url: 'contact.php',
data: $('#contactform').serialize(),
success: function(data){
$('.notifications').slideDown(function(){
setTimeout("$('.notifications').slideUp();",7000);
}); // Show notifications box
$('#contactform').get(0).reset(); // reset form
unloading(); // remove loading
},
error: function(data){
$('#preloader').fadeOut(400,function(){ $(this).remove(); });
alert("No complete");
return false;
},
cache: false,type: 'POST',dataType: 'json'
});
}
Can you try to use data.result in logic statement