How to Enable Submit Button After API Call and Within if Statement - javascript

I am disabling the submit button #myButton after i execute an api call doAjax();
$("#myButton").click(function (e) {
doAjax();
$('input:submit').attr("disabled", true);
});
But it wont enable after the callback .. i want to enable it if the call back meets a certain criteria i.e.
$.ajax({
type: "GET",
url: "api5.php",
data: dataString,
dataType: "json",
//if received a response from the server
success: function (response) {
var status = response.status;
enter code here
if ((status == 'READY' && response.endpoints[0].statusMessage == 'Ready')) {
$('input:submit').attr("disabled", false);
doesn't seem to work though.. button stays disabled.

Are you sue the your if block is getting executed ? Try doing console.log or alert inside the if block. Also, try the following :
$('input:submit').removeAttr('disabled');
or you can also try input[type=submit] as the selector or give a class or id and make it selector.

the code works for me, only comment this line enter code here
$.ajax({
type: "GET",
url: "api5.php",
data: dataString,
dataType: "json",
//if received a response from the server
success: function (response) {
var status = response.status;
//enter code here
if ((status == 'READY' && response.endpoints[0].statusMessage == 'Ready')) {
$('input:submit').attr("disabled", false);

Try : $(el).prop('disabled', false)

Related

Jquery ajax error callback is executed even though the response http status is 200

I have written simple ajax code, in success callback I have written an alert but it does not work.
The code is:
$(".change_forex_transaction_status").click(function(){
$("#insufficient_funds").css("display","none");
var id = $(this).attr('data-transaction_id');
//var ttype = $(this).attr('data-ttype');
if (confirm("Are you sure you want to mark this transaction as complete?")) {
$(this).unbind("click");
$.ajax({
url:"<?php echo Yii::app()->getBaseUrl(true);?>/customer/changeForexTransactionStatus",
type:"POST",
dataType: "json",
//data:{id:id,tidentify:2,ttype:ttype},
data:{id:id,tidentify:2},
success:function(res){
if(res == "unauthorized"){
alert("You Are not authorize to perform this action.");
}else{
if(res == "success"){
location.reload();
} else if(res == "insufficient_fund"){
alert('Insufficient Fees');
$("#insufficient_funds").css("display","block");
} else if(res == 'invalid_fee_account'){
alert('Invalid Merchant Fees Account');
}
}
},
error:function(t) {
console.log(t);
}
});
}
});
Even though the response http status code is 200, it goes into error callback whereas it should have gone in success callback and opened an alert box.
Can anyone please help on this.
You are expecting json back not text so change the ajax dataType to text
dataType: "text",
Use JSON.stringify to post data on server, and when you post data to server in json so use content type "application/json". Now if you expect data in json from server then use dataType: "json". If data from server is html then you can use dataType: "html" or it is text then you can use dataType: "text".
data: JSON.stringify({ id: id, tidentify: 2 }),
contentType: "application/json",
dataType: "json"

Check if alert box was shown in PHP using AJAX

I am sending data to a PHP file using AJAX and depending on what data is sent, an alert() is either shown or not shown.
Inside the success function in AJAX, how do I detect if an alert box was shown?
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if(alert box was shown) {
// something happens
}else{
// alert box wasn't shown, something else happens.
}
}
});
send.php:
<?php
if($_POST['name'] == 'john') {
echo'
<script>
alert("Correct name");
</script>
';
}
It would be better to send back a result form the ajax request and show/don't show the alert in the success callback:
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,,
success: function(data) {
if ( data == "show" ) {
// something happens
alert("Correct name");
} else {
// alert box wasn't shown, something else happens.
}
}
});
And on your server:
if ( $_POST['name'] == 'john' ) {
echo "show";
}
You could use json_encode() php function to return data from php.
This will be a better approach :
PHP :
if (!isset($_POST['name'] || empty($_POST['name']) {
die(json_encode(array('return' => false, 'error' => "Name was not set or is empty")));
} elseif ($_POST['name'] == "John") {
die(json_encode(array('return' => true)));
} else {
die(json_encode(array('return' => false, 'error' => "Name is different than John.")));
}
At this point, you will be allowed to check the returned values from JS and decide if you need to display the success alert or send an error message to the console (or do what ever you want...).
JS :
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
dataType: "JSON", // set the type of returned data to json
data: {name: called}, // use more readable syntaxe
success: function(data) {
if (data.return) { // access the json data object
alert("Congrats ! Your name is John !");
} else {
console.log("Sorry, something went wrong : " + data.error);
}
}
});
So, json_encode() allows to return easy accessible object from JS and will also allows you to set and display error messages easily in case the return is false.
Hope it helps !
PHP does not know if an alert has been shown, because in javascript the alert() function has no return value and no events which you could use to send an ajax request a click confirmation to the server.
One solution is to use a confirm() command inside the success event of your $.ajax(), which sends anothe ajax request if the user clicked "ok" or "cancel".
Something like this
var called = $("#called").val();
$.ajax({
type: "POST",
url: "send.php",
data: "name=" + called,
success: function(data) {
if (data == "show") {
var clicked = confirm("Correct name");
if (clicked == true || clicked == false) {
$.ajax({
url: "send.php?clicked=1",
});
}
}
else {
// Whatever to do than...
}
}
});

JSON is null but data passes to success in ajax

I'm running into a problem in ajax. the scenario is: I would like to verify if the user is available or not when typing his email. So I create a function in javascript to do this with an Ajax script within it.
here my code :
$('#username').keyup(function () {
var email = $(this).val();
$.ajax({
type: 'GET',
url: 'http://localhost:8080/MeublesTunisv4/web/app_dev.php/email-verification/' + email,
dataType: "json",
beforeSend: function () {
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/loading.gif')}}"></img>');
},
success: function (data) {
$('#email_status').remove();
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/green_tick.png')}}"></img>');
}
});
});
my problem is : when I type any words it calls the function of keyup then it passes into success even if the data is null. I would like to let it pass to the success only if the data is correctly done.
thank you.
Try Following..Hope it works as you want...
$('#username').keyup(function () {
var email = $(this).val();
if(email != "") {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/MeublesTunisv4/web/app_dev.php/email-verification/' + email,
dataType: "json",
beforeSend: function () {
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/loading.gif')}}"></img>');
},
success: function (data) {
// Check response data...
if(data == 'true') {
$('#email_status').remove();
$('#email_status').html('<img id="loading" src ="{{ asset('bundles/theme_front_end/images/green_tick.png')}}"></img>');
}
}
});
}
});
Try some error checking before doing anything. Therefore, the success callback will be invoked (you cannot stop it conditionally), but the code inside will be prevented.
Encapsulate everything in the success event handler with the following so that it only executes if data is not null (empty string):
if(data != "") {
// action here
}
I'm not sure what you mean when you say that "the data is null", so a simple empty-string conditional as shown above may not be sufficient to check whether or not the data is null. This will simply check if the data parameter is empty.

Given a form submit, how to only submit if the server first responses back with a valid flag?

I have a form, with a text input and a submit button.
On submit, I want to hit the server first to see if the input is valid, then based on the response either show an error message or if valid, continue with the form submit.
Here is what I have:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
if (data.valid) {
return true
} else {
// Show error message
return false;
e.preventDefault();
}
}
});
});
Problem is the form is always submitting, given the use case, what's the right way to implement? Thanks
Try like this:
$('#new_user').submit(function(e) {
var $form = $(this);
// we send an AJAX request to verify something
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
// if the server said OK we trigger the form submission
// note that this will no longer call the .submit handler
// and cause infinite recursion
$form[0].submit();
} else {
// Show error message
alert('oops an error');
}
}
});
// we always cancel the submission of the form
return false;
});
Since you're already submitting via AJAX why not just submit the data then if it's valid rather than transmit the data twice?
That said, the function that makes the Ajax call needs to be the one that returns false. Then the successvfunction should end with:
$('#new_user').submit()
The fact that AJAX is asynchronous is what's throwing you off.
Please forgive any typos, I'm doing this on my cell phone.
Submitting the same post to the server twice seems quite unnecessary. I'm guessing you just want to stay on the same page if the form doesn't (or can't) be submitted successfully. If I understand your intention correctly, just do a redirect from your success handler:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
location.href = "success.htm";
},
// if not valid, return an error status code from the server
error: function () {
// display error/validation messaging
}
});
return false;
});
Another approach
EDIT: seems redundant submitting same data twice, not sure if this is what is intended. If server gets valid data on first attempt no point in resending
var isValid=false;
$('#new_user').submit(function(e) {
var $form = $(this);
/* only do ajax when isValid is false*/
if ( !isValid){
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
isValid=true;
/* submit again, will bypass ajax since flag is true*/
$form.submit();
} else {
// Show error message
alert('oops an error');
}
}
});
}
/* will return false until ajax changes this flag*/
return isValid;
});

jquery ajax call taking too long or something

I have a form that I want to ensure the paypal email address is valid before I submit. So i am making a jquery submit call like this
$('#new_user').submit(function(){
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('#user_paypal_email').append('<span style="color:#E77776;">This is not a valid email address</span>');
return false;
}else{
return true;
}
}
});
but the problem is this call thats a second and the page already refreshes before the ajax is complete....if I put the return false at the end of the call I can see my json is correct but for some reason the way I have it now wont finish...any ideas on how to correct this
Just use preventDefault() immediately when the submit event is fired. Then wait for the response from paypal and then call submit() on the form.
$('#new_user').submit(function(e){
e.preventDefault();
var form = $(this); //save reference to form
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('#user_paypal_email').append('<span style="color:#E77776;">This is not a valid email address</span>');
return false;
}else{
form.unbind('submit'); //remove binding
form.submit(); //submit form
}
}
});
If you want to do something right away you would need to set async false in the request

Categories

Resources