AJAX error when calling it inside a function into JavaScript file - javascript

I'm facing a weird error using JavaScript.
I have a file add_account.js in my project that it throw JQuery error, when my AJAX function is inside a function.
It occurs the same problem when I use components like bloodhound and typehead.
By the way it's not throwing even the error set up by AjaxSetup. It stops and no alert.
Error:
TypeError: e is undefined
setRequestHeader:function(e,t)
{var n=e.toLowerCase();return x||(e=v[n]=v[n]...
jquery-....min.js (line 5, col 11629)
var testAjaxRun = function(){
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
$.ajax({
type: "GET",
dataType: "json",
url: "../controllers/fde.php",
success: function(data) {
alert('success');
return data;
}
});
//...
}
// outside function and in the end of file
$(document).ready(function() {
testAjaxRun();
});
If I remove the AJAX instructions to outside function it works normally.
Error:
TypeError: e is undefined
setRequestHeader:function(e,t)
{var n=e.toLowerCase();return x||(e=v[n]=v[n]...
jquery-....min.js (line 5, col 11629)
Any idea of this problem? All the rest inside the script is working perfectly.
It is project I'm migrating from Java to PHP. The javascript file into the Java Project works normally as well.

Folks,
I found the problem. Actually there is nothing wrong with the javascript.
The problem was that the project had another file.js that had this instruction which screwed up my ajax call.
Then I commented _jquery.init and all works. After 2 nights without sleeping and testing all the other things I got the error. :)
_jquery.init()
_jquery = {
init: function () {
$(document).ajaxSend(function (e, xhr, options) {
xhr.setRequestHeader(sync.csrfHeader, sync.csrf);
});
} };
Java project probably is treating this field, but I don't need it for now.

Related

jQuery Synchrnus issue with alertifyjs success method

I m facing a strange issue. i have used alertify library to show messages to user, but in this case alertify is not working. Here is the success portion of my ajax call.
success: function(data) {
if (data.status == 'success') {
alertify.success(data.msg);**// this line should dislay a message but instead of calling this , it directly calls employee_details(), data.msg is "Data saved Successfully"**;
data.user_type =3;
if(data.hasOwnProperty('user_type')){
if(data.user_type==2){
employeeDetails(data.id, tab_id);
}else{
employee_details(data.id);
}
} else {
return false;
}
}
}
if i remove employee_details(data.id), this works perfectly.

JQuery If Else statement never executed

I'm using a simple if else statement to check for response from a POST form.
This is weird: I can check for response in form of error. Using elseif: or else: just does absolut nothing. Even though the response is valid.
Current code:
post_data = {
'someData': someData
}
// Ajax post data to server
$.post('register.php', post_data, function(response) {
if (response.type == 'error') {
if (response.errorType == 'something') {
$("#someThing").addClass('has-error');
}
} else {
window.location.reload(true);
}
}, 'json');
This is so weird. I've tried to insert alerts to really check if the else statement ran in background or something.
When the response is: "error" the error statement is executed.
However when the response is: success/done/cleared/failed etc. (whatever i try) nothing happens.
I receive the respond in console - but JQuery doesnt run the } else { ... statement.
Actually its not what you think.
The function is only called on Success. For error handling you have to chain another function
For example try this:
post_data = {
'someData':someData
}
// Ajax post data to server
$.post('register.php', post_data).done(function (response) {
// This is your success function
window.location.reload(true);
})
.fail(function (xhr, textStatus, errorThrown) {
console.log("Post error: " + errorThrown);
$("#someThing").addClass('has-error');
});
I hope this help you to understand that weird behavior :P
jQuery documentation have different handling functions for different jQuery version. so better to use $.ajax

TypeError: 'null' is not an object (evaluating 'response.productType')

hey guys i'm somewhat new to Ajax but my code is throwing up this error: TypeError: 'null' is not an object (evaluating 'response.productType') and I don't know why. Here's the code, thanks in advance. all of this is wrapped in document.ready
function handleLupGoBrowseResponse(response){
if(response.productType == "MSG"){
if(LOCALE == 'en_US'){
$('p.success').html(lupSuccessEn);
$(lupUpsellEn).insertAfter('.headerTopBar');
//alert("yes"); remove for prod
}else if(LOCALE == 'fr_CA'){
$('p.success').html(lupSuccessFr);
$(lupUpsellFr).insertAfter('.headerTopBar');
}else if(LOCALE == 'ja_JP'){
$('p.success').html(lupSuccessJp);
$(lupUpsellJp).insertAfter('.headerTopBar');
}
}else{
//alert("no"); remove for prod
//alert(lupMobile); remove for prod
}
}
if(lupAjaxUrl != ""){
$.ajax({
url: lupAjaxUrl,
cache: false,
pageCache: false,
dataType: "jsonp",
success: handleLupGoBrowseResponse
});
}
The response of your ajax call is not an object, it is evaluated as null. Add a condition to the beginning of your function to test this value
function handleLupGoBrowseResponse(response){
if(response) {
// execute your code
} else {
console.log(response);
}
}

Javascript Logic Fail?

I'm really confused on this one. I'm trying to do a simple ajax request, and I have php executing 'echo "true";' if the ajax request is successful, or return a string containing the error if it isn't. I'm using this exact technique elsewhere in the code and it compares as expected (msg != "true") { //do something }. The first function I'll post below works with that method, the second doesn't (also I am checking with Firebug the response is "true", and I've done console.log(typeof msg) to verify it is of type string).
This works as expected (the php echoes "true", and it executes show_step2()):
function step2_register() {
var values = $('.signup .txt').serialize();
$.ajax({
type: "POST",
url: base_url+"login/create_account",
data: values,
success: function(msg) {
if (msg != "true") {
$("#login_form.signup .error_container #error1").html(msg).css("visibility", "visible");
}
else {
show_step2();
}
},
error: function(error) {
alert(error);
}
});
}
This doesn't work (the php echoes "true", but the js always executes the slideDown() part of the code):
function register() {
var data = $("#login_form .input").serialize();
$.ajax({
type: "POST",
url: base_url+"login/register",
data: data,
success: function(msg) {
if (msg != "true") {
$("#login_form.signup #error2").html(msg).slideDown();
}
else {
show_success();
}
},
error: function(error) {
alert(error);
}
});
}
What's going on here?
Your php is likely outputting something else invisible like a newline character after the word "true". Either make sure you call die(); or exit(); right after outputting "true", (and doing everything else you need), or make sure there are no line breaks in your PHP editor before the <?php and after the ?>.
You can also check that the string begins with "true" instead of equals "true" by trying something like msg.substring(0,4) == "true"

PHP/ Ajax/ jQuery - Equivalent for my code

I have the following code and would like to use jquery to make it simpler:
var auctionBidAjax;
function auctionBid(auction_id) {
auctionBidAjax=GetXmlHttpObject();
if (auctionBidAjax==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="/cms/ajax/auctionBid.php?auction_id="+auction_id;
auctionBidAjax.onreadystatechange=function() { auctionBidReady(auction_id); };
auctionBidAjax.open("GET",url,true);
auctionBidAjax.send(null);
}
And...
function auctionBidReady(auction_id) {
if (auctionBidAjax.readyState==4) {
if (auctionBidAjax.responseText == "Bid Placed") {
document.getElementById('auctionBid' + auction_id).innerHTML=
"Place Bid";
userBids();
} else if (auctionBidAjax.responseText == "Not Logged In") {
popupCentre('popupLogin');
popupLoad('popupLogin');
} else if (auctionBidAjax.responseText == "No Bids"){
popupCentre('popupNoBids');
popupLoad('popupNoBids');
}
}
}
My PHP script adds a bid etc and echos the responseText.
You've tagged this question as jquery so you can use $.ajax():
function auctionBid(auction_id) {
$.ajax({
url: "/cms/ajax/auctionBid.php",
type: "GET",
data: {
auction_id: auction_id
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// act appropriately
},
success: function(data, textStatus) {
// do whatever
}
});
}
If you didn't need an error handler you could use the simpler form of $.get() instead:
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.get(url, { auction_id: auction_id }, function(data, textStatus) {
// do whatever
});
}
I actually prefer not to use error handlers. It's a little uglier than it needs to be. Use that for actual errors. Things like "not logged in" could be handled by the success handler. Just pass back a JSON object that contains the required information to tell the user what happened.
For this you could use the $.getJSON() shorthand version.
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.getJSON(url, { auction_id: auction_id }, function(data) {
if (data.notLoggedIn) {
alert("Not logged in");
}
...
});
}
To return some information as JSON from PHP use json_encode() and set the MIME type appropriately:
<?php
session_start();
header('Content-Type: application/json');
echo json_encode(array(
'highBid' => get_new_high_bid(),
'loggedIn' => $_SESSION['loggedIn'],
));
exit;
?>
I'm making assumptions about your login system so the above is a gross simplification.
Return that to a $.getJSON() callback and you should be able to do:
alert(data.highBid);
alert(data.loggedIn);
JQuery.get is what you need
http://docs.jquery.com/Ajax/jQuery.get

Categories

Resources