$.ajax not working first time - javascript

I have a button in html page.
<input type="image" src="images/login_button.png" id="imageButton" onclick="LoginButtonClick();" />
I am calling this method on button click:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
alert ("Inside Ajax."); // This alert not executing first 1 or 2 times.
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
}
});
}
As I mentioned above $.ajax not working first 2 , 3 button click attempts.
In mozilla it throws an error "[Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: JQuery.js :: :: line 20" data: no]"
Is there any way to fix this issues..

I'm not sure why it is executing later. But here's the deal--you're placing the alert in the object literal that defines the parameters for the .ajax method. It doesn't belong there. Try putting the alert in your success and/or error handlers.
UPDATE
How long are you waiting? When you initiate an ajax request, it isn't going to hang the UI. It could be that you're seeing the result of the first click on your 3rd or 4th attempt and think that you're triggering it on that 3rd or 4th attempt.

The $.ajax() function receives as a parameter a set of key/value pairs that configure the Ajax request. I don't think that the syntax will be correct by placing the alert() in there.

Note - entering an absolute path isnt going to work if the domain is not the current one - it is against the Same Origin Policy that browsers adhere too - this might explain why nothing happens when its executed - i suggest you look in your browser debugger to verify.
You should be binding the click event like this :
$(document).ready(function() {
$('#imageButton').click(function() {
// code here
});
});
so your complete code will look like this :
HTML
<input type="image" src="images/login_button.png" id="imageButton" />
JavaScript
$(document).ready(function () {
$('#imageButton').click(function () {
alert("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function (response, status, xhr) {
if (response != "") {
alert("Response receive ");
} else {
alert("Invalid Data.");
}
}
});
});
});
I have removed the alert ("Inside Ajax."); line as this will not be executed - you pass an object {} of parameters not code to execute. If you want to execute before the ajax request is sent do this :
$.ajax({
beforeSend: function() {
alert('inside ajax');
}
// other options here
});
Docs for the $.ajax() function are here

I agree that you have the second alert in the wrong place, and dont know what pmamml.ajaxError function is but may be your call returns with error and therefore your success alerts are not firing. You can check with error and complete functions as follows:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: function(jqXHR, textStatus, errorThrown){
alert ("ajax call returns error: " + errorThrown);
},
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
},
complete:function(jqXHR, textStatus){
alert('completed with either success or fail');
}
});
}
You can test with Google Chrome's Developer tools -> Network tab, if a request is made and returned (https://developers.google.com/chrome-developer-tools/docs/network)

Related

Inconsistent execution of Error function for Jquery Ajax POST request

I am running into an issue in my error handling of a Jquery Ajax request, and I'm having trouble finding the root of it.
I have a staging site where I am testing error responses for a form submission. The first time I fill out the form fully and click submit, the form is replaced with a brief "processing" message, and then input fields re-appear with the expected error message for Invalid Token.
However, when I click subsequent times sometimes it gets stuck on showing the "processing" message, even though I can see an Error response. It is strange because the console.error() that I have in my Error: function gets triggered, but the Jquery calls that should handle the Form's state don't seem to get complete even though they are in the same scope.
Here is are the jquery variables handling the form's state:
const $formErrorState = $('#SIM-Order-Error-State');
const $formErrorStateText = $('#SIM-Order-Error-State-Text');
const $formCompleteState = $('#SIM-order-complete-state');
const $formSuccessState = $('#SIM-order-success-state');
const $formInitialState = $('#SIM-order-form');
and the call itself:
function simOrderRequest(token, fData){
console.log(fData);
console.log(JSON.stringify(fData));
$.ajax({
method: 'POST',
url: 'https://control.dev.yomobile.xyz/api/v1.0/sim-request/confirm/?token='+token,
data: JSON.stringify(fData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.type=="bad_request" || data.status==400) {
$formErrorState.show();
$formSuccessState.hide();
$formErrorStateText.text(data.responseJSON.type+": "+data.responseJSON.description);
$formInitialState.show();
}
if (data.status==500){
$formErrorState.show();
$formSuccessState.hide();
$formErrorStateText.text(data.responseJSON.type+": "+data.responseJSON.description);
$formInitialState.show();
}else {
$formCompleteState.show();
$formSuccessState.hide();
}
},
error: function (error) {
$formSuccessState.hide();
$formErrorState.show();
$formInitialState.show();
$formErrorStateText.text(error.responseJSON.type+": "+error.responseJSON.description);
console.error(error);
},
});
}
});
This is the expected behavior
But sometimes it gets stuck here, once the error is returned, and does not return to the input fields

Bootstrap modal hidden event reload the body via ajax

I have a page that popup a modal and using hidden.bs.modal event, I want to reload the same page contents i.e body tag html via ajax. I have the following code:
$("#actions-modal").on('hidden.bs.modal', function(){
alert(document.location)
$.ajax({
url: document.location,
type: "get",
sucess: function(data){
alert('hhhh')
return $("#body1").html($(data).find('#body1'));
},
error: function(xhr){
console.log(xhr);
}
})
})
In the above code, alert(document.location) works fine. However, both alert('hhhh') in success handler of the ajax and console.log(xhr) in the error handler of the ajax don't work at all. i.e there is no success nor error! Additionally, there is no any errors in the browser's console.
document.location will return you the object, So try using document.location.href which will return you the string of URL. Then the AJAX call will start working.
Remove the return from your success function. You don't need to return when changing the html of an element. The return is only required when doing something like this:
function getHTML()
{
$.ajax({
url: document.location,
type: "get",
sucess: function(data){
return data;
},
error: function(xhr){
return "Failed";
}
});
}
var myHTML = getHTML();
$('#body1').html(myHTML);
However, when you are immediately setting the html you don't need it.

jquery ajax post sends me to action page and wont show result data

I have the following script for making Ajax/Jquery post request.
The script works (I get correct response on back-end).
But I cant seem to make any alerts, so I think there is some problem with the success function.
Do you guys see any obvious mistakes?
The browser gets the correct responses (Inspect webpage in chrome).
<script>
$(document).ready(function() {
var frm = $('#registerform');
frm.submit(function(x) {
x.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/v1/register',
data: frm.serialize(),
crossDomain: true,
success: function(data){
if(data == 200){
alert("successfully registered");
$('#alert').append("successfully registered");
}
if (data == 400){
alert("email or password empty");
}
if(data == 403){
alert("passwords do not match");
}
}
});
});
});
</script>
You are trying to compare your data that you are getting back from your request with HTTP status codes. So, what you need do is put in some additional parameters in your success function. Here is a nice Fiddle that I seen on another stackoverflow question that might help you out. http://jsfiddle.net/magicaj/55HQq/3/.
$.ajax({
url: "/echo/xml/",
type: "POST",
data: {
//Set an empty response to see the error
xml: "<response></response>"
},
dataType:"text xml",
success: function(xml, textStatus, xhr) {
console.log(arguments);
console.log(xhr.status);
}
});
The xhr.status is what you will need to compare against instead of your data.
When playing with console.log i found out that sending res.sendStatus(200) from the backend results in the client (browser) getting the response "OK". So when changing to res.json on the server it works...

Ajax post working but not callback message in Android browser

im implementing sign up with ajax on my site its working perfectly on desktop but causing problem in Android Browser The problem is after i click on signup button in android browser it post data to database but do not replace the html message.And alert native code error.
function postdata(){
var chkfrm = checkdata();
if(chkfrm == 0){
var url = '<?php echo base_url();?>index.php/Signup/signin';
$.ajax({
type: "POST",
url: url,
data: $("#formI").serialize(), // serializes the form's elements.
beforeSend:function(){
$("#signupdiv").html('<h1>Loadinng...........</h1>');
},
success:function(data)
{
$("#signupdiv").html(data);
},
error:function () {
alert(console.log);
}
});
e.preventDefault();
}
else {
$("#msgjava").html('<p>We need a little bit information from you.Please fill it.</p>');
return false;
}
You can't do e.preventDefault(); where you are because e is not passed into this function (thus it is undefined). This will cause an error and stop JS execution.
In what you posted, you are also missing a closing brace at the end of the postdata() function.
Your alert says "native code" because that's what this line of code:
alert(console.log)
will do. console.log is a native function so alerting a native function won't do anything useful. You need to make that alert a lot more useful. To see in more detail what error is coming back from the ajax function, change your error handler to something like this:
error: function(jqXHR, textStatus, errorThrown) {
alert("status = " + textStatus + ", errorThrown = " + errorThrown);
}
And, then see what it says.

AJAX request confusion in jQuery

I am unable to understand that why the jquery AJAX is not fetching data from the ajax page.
Can someone please help.
<script type="text/javascript">
$(function() {
$('#lms_id').change(function(){
if ($(this).val() != "") {
// alert("1");
} else {
// alert("0");
}
});
$('#lms_user_role_id').change(function(){
if (($(this).val() == "7" || $(this).val() == "8")) {
$('#t_lms_dealers').show();
} else {
$('#t_lms_dealers').hide();
}
});
});
function loadAjax(message)
{
//alert(message);
//$.get("<?php echo $App['wwwroot'].'er.php' ?>?activity="+message);
$.get("http://www.abc.loc/er.php");
}
</script>
In loadAjax function, alert is alerting fine, but only the AJAX part is not working.
How do you know it is "not working"?
$.get("http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php");
Even if it did, this statement would accomplish nothing. You need to put a handler in there:
$.get(
"http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php",
function (data) {
alert("Retrieved :"+data);
}
);
You should also use some kind of in browser developer tool (eg, firebug) that will allow you to trace the request in real time. Finally, the plain jquery get lacks an error handler; you might want to instead use:
$.ajax ({
url: "http://www.abc.loc/lmsapi/LMS_L2/templates/admin/user/tpl.user_dealer.php",
success: function (data) {
alert(data);
},
error: function (xhr, err, code) {
alert("Error: "+err);
}
});
And read the query documentation:
http://api.jquery.com/category/ajax/
if i am not wrong 2nd possibility is may be you are trying "cross domain ajax call", if yes then you have to set header "Access-Control-Allow-Origin" and "crossDomain: true" for $.ajax call.

Categories