In the AJAX call below, I am attempting to debug the JavaScript call to understand why I cannot get to the error block when checking for failures. Whenever I debug in Chrome Developer tools, it jumps to the last line of the function and not the error block. Is there a easier way to test why this isn't being hit?
$("#input-userName").blur(function () {
var userNameTxt = $("#input-userName").val();
if (userNameTxt != prevUserName) {
if (userNameTxt.length >= 6 && userNameTxt.length <= 20) {
$("#divVerifyUserName").show();
$("#input-userName").prop("disabled", true);
$.ajax
({
type: "GET",
url: BASE_URL + "MyCall",
async: true,
data: { 'userName': userNameTxt },
success: function (resultset) {
prevUserName = userNameTxt
$("#userNameValidationMessage").removeClass("error");
if (resultset != null) {
$("#divVerifyUserName").hide();
$("#input-userName").prop("disabled", false);
if (resultset.status) {
$("#userNameValidationMessage").addClass("message");
}
else {
$("#userNameValidationMessage").removeClass("message");
$("#userNameValidationMessage").addClass("error");
}
$("#userNameValidationMessage").text(resultset.msg);
}
},
error: function (xhr, error) {
$("#userNameValidationMessage").text("Error while processing the request. Please try again.");
}
});
}
}
});
Related
I am currently trying to make a tool for my work and the timing is messing me up a lot. Hopefully someone can help here. Below is my code that I currently have. The issue is when I grab a selected item and run the $("#JJ_HOLDER").load(), it is sometimes not waiting to finish. I need everything to finish in the callback function THEN run the submitTaskbyHolder() but only when it is complete. Any and all help is appreciated!
End Goal: Run RunCad() and have it load data into $("#JJ_HOLDER") then run submitTaskbyHolder() then empty and repeat with another data set (parseInt(selected[i]))
function submitTaskbyHolder(){
var loginUser = $("#hdnUserID").data('value');
$.ajax({
type: "POST",
url: app.global.AppPath + 'WorkRequestDetails/SubmitWorkRequestDetails/',
data: $('#FormID').serialize(),
dataType: 'json',
success: function (result) {
if (result.Status == "Show Add Module") {
app.workRequestDetails.OpenWorkRequestDetailsPopup("Submit");
}
else {
if (result.Status == "Module submitted.") {
if (result.ModuleAndStatus.CurrentAssignedId == loginUser) {
app.modalPopup.isCancel = false;
$("#BTNStop").click();
app.workRequestDetails.display_notifyresultA("Successfully submitted work request.");
$('#HFCurrentModuleID').val(result.ModuleAndStatus.ModuleId);
$('#HFCurrentStatusID').val(result.ModuleAndStatus.StatusId);
$('#txtModule').val(result.ModuleAndStatus.ModuleName);
$('#txtStatus').val(result.ModuleAndStatus.StatusName);
console.log('submitted');
}
else {
app.modalPopup.isCancel = false;
app.layoutdash.display_notifyresult("Successfully submitted work request.");
console.log('submitted');
}
}
else {
swal(result.Status);
}
}
},
error: function (result) {
swal(result.Status);
}
});
}
var i = 0;
function RunCad() {
selected = app.dashboardGridview.selectedItems;
if(selected.length == 0){
swal({title: "Error",
text: "Ensure there is more than one selected!",
icon: "error",
button: "Okay",
});
}else{
setTimeout(function () {
$("#JJ_HOLDER").empty();
$("#JJ_HOLDER").load(app.global.AppPath + 'WorkRequestDetails/GetWorkRequestDetails/', { projectID: parseInt(selected[i]) },function() {
$(body).css('padding-right', '0px');
app.addWorkRequest.LoadTooltipsterToPopup();
app.multiSelectSettings.MultiSelectSettings();
app.modalPopup.Loadfunctions('WorkRequestDetails/GetWorkRequestDetails/');
app.modalPopup.FixTabPressModalPopup();
submitTaskbyHolder();
console.log(selected[i] + ' is complete!');
});
i++;
if (i+1 < app.dashboardGridview.selectedItems.length) {
RunCad();
}else{
app.modalPopup.ReloadDashboardView();
}
}, 3000)
}
}
I have a program written in angularjs. I'm receiving json data from server when online. I'm developing offline mode now..
I have the problem here but i dont know why i cant fix.
I saved json info to localStorage when program to offline get this json string.
service.js - For webservicecall
webServiceCallPost: function(data, action) {
console.log("data "+JSON.stringify(data));
console.log("action "+JSON.stringify(action));
var deferred = $q.defer();
if (navigator.connection.type != "none") {
return $.ajax({
type: "POST",
url: appConst.serviceUrl.service + action,
crossDomain: true,
dataType: "json",
data: data,
timeout: 2000000,
async: true,
success: function(response) {
localStorage.setItem(data + action, JSON.stringify(response));
deferred.resolve();
},
error: function(xhr, ajaxOptions, thrownError) {
$ionicLoading.hide();
if (xhr.status == 0) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else if (xhr.status == 404) {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
} else {
window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
}
},
beforeSend: function() {},
complete: function() {}
});
} else {
window.plugins.toast.showShortBottom($translate.instant("checkNetWorkConnection"));
$ionicLoading.hide();
var response1 = JSON.parse(JSON.stringify(localStorage.getItem(data + action)));
return $http.get('').then(function(response) {
return response1;
});
}
}
Controller.js - Retriveing response.
Services.webServiceCallPost('', appConst.services.get_menu_card).then(function(response) {
$ionicLoading.hide();
console.log("Response: " + JSON.stringify(response));
if (response[1].response.status == 1) {
if (response[0].data.menu.length > 0) {
var categoryResponse = [];
angular.forEach(response[0].data.menu, function(value, key) {
if (value.menu_image_name != '') {
var extraData = {
imageUrl: appConst.serviceUrl.menu_image_url + value.menu_image_name
}
}
else {
var extraData = {
imageUrl: 'img/screen.png'
};
}
angular.extend(value, extraData);
categoryResponse.push(value);
});
$rootScope.categories = globalMethods.getDashboardGridView(categoryResponse, 2);
}
if (response[0].data.addons.length > 0) {
$rootScope.totalAddons = [];
angular.forEach(response[0].data.addons, function(value, key) {
var extraData = {
"finalCost": value.price,
"quantity": 1,
imageUrl: appConst.serviceUrl.addon_image_url + value.addon_image
};
angular.extend(value, extraData);
$rootScope.totalAddons.push(value);
});
}
$scope.getSiteSettings();
}
$rootScope.dashboardHistoryId = $ionicHistory.currentHistoryId();
});
Console Output :
When i check from json pretty print its looking same.
Online Response : https://codepaste.net/op0boq
Cached Response : https://codepaste.net/y3bkd6
Problem:
TypeError: Cannot read property 'status' of undefined
When i want to get response1.response.status ok is getting.
But when i'm offline and i get cachedResponse1.response.status its retriving status is undefined. But exactly same data, why ?
if this code
var cachedResponse = JSON.parse(JSON.stringify(localStorage.getItem('' + appConst.services.get_menu_card)));
uses an asynchronous call
console.log("Cached Response: " + cachedResponse);
won't wait for it to finish and would print undefined
Thanks for answer to #PatrickEvans
Then you might have not returned the right thing... but also you shouldn't be doing JSON.parse(JSON.stringify(localStorage.getItem()) it should just be JSON.parse(localStorage.getItem()) localStorage items are already strings, stringifying it is going to mess up what you are trying to do
and
return $q.when(response1);
I see that there is a question about this, but I don't know how I would implement it in my case (since I'm not using multiple sessions). Also, I must say that the long-polling itself works, but nothing else does while it runs.
There is javascript file which sets the method, and chat.php file which on this basis either receives messages (starts polling) or sends them. The issue is I can't send the messages if I include the "while" function. Here it is:
from chat.js:
chat.fetchMessages = function ()
{
if(localStorage.getItem("amInQueue") != 1)
{
$.ajax({
url: '../ajax/chat.php',
type: 'post',
data: { method: 'fetch' },
async: true,
cache: false,
timeout: 50000,
success: function(data)
{
if(data!='')
{
chat.printMessages(data);
}
setTimeout(chat.fetchMessages, 1000);
}
});
}
}
chat.throwMessage = function (message, byuser)
{
if ($.trim(message).length != 0 && localStorage.getItem("amInQueue") != 1)
{
$.ajax({
url: '../ajax/chat.php',
type: 'post',
data: { method: 'throw', message: message, byuser:byuser },
success: function(data)
{
chat.entry.val('');
}
});
}
}
from chat.php:
<?php
require '../core/init.php';
if (isset($_POST['method']) === true && empty($_POST['method']) === false)
{
$chat = new Chat();
$method = trim($_POST['method']);
if($method === 'fetch' && $_SESSION['ses_amInQueue']==0)
{
$shouldStop=0;
$messageIDs = $chat->checkForLatestMessage($_SESSION['ses_myChat'], $_SESSION['ses_meInChat']);
while($messageIDs=='')
{
usleep(30000);
clearstatcache();
$messageIDs = $chat->checkForLatestMessage($_SESSION['ses_myChat'], $_SESSION['ses_meInChat']);
}
if($messageIDs!='')
{
$messageString=$chat->getNewMessages($_SESSION['ses_myChat'], $messageIDs);
$chat->deleteMessages($messageIDs);
echo $messageString;
}
}
else if($method === 'throw' && isset($_POST['message']) === true)
{
$message = trim($_POST['message']);
$byuser = trim($_POST['byuser']);
if (empty($message) === false)
{
$chat->throwMessage($byuser, $message, $_SESSION['ses_otherInChat'], $_SESSION['ses_myChat']);
}
}
I can't use "throw" method while the "while" loop is running. I tried checking the method on the end of "while" loop to see if it's "throw" and including it in "while"'s conditions, but that didn't work for some reason.
How do I pull this out? Both work independently, or if I remove "while" loop (but it is then no longer long-polling).
When first opening the mobile app homepage it returns an error
"TypeError: Jqueryxxxxxx is not a function" although it shows the API
callback results
"jQuery111309512500500950475_1459208158307({"code":1,"msg":"Ok","details":{"data"..."
according to Firebug.
I have to open different app pages then return to homepage to see Featured Merchants parsed.
JS Code
case "page-home":
callAjax('getFeaturedMerchant','');
break;
case "getFeaturedMerchant":
displayFeaturedRestaurant( data.details.data ,'list-featured');
break;
case "getFeaturedMerchant":
createElement('list-featured','');
break;
API PHP Code
public function actiongetFeaturedMerchant()
{
$DbExt=new DbExt;
$DbExt->qry("SET SQL_BIG_SELECTS=1");
$start=0;
$limit=200;
$and='';
if (isset($this->data['restaurant_name'])){
$and=" AND restaurant_name LIKE '".$this->data['restaurant_name']."%'";
}
$stmt="SELECT a.*,
(
select option_value
from
{{option}}
WHERE
merchant_id=a.merchant_id
and
option_name='merchant_photo'
) as merchant_logo
FROM
{{view_merchant}} a
WHERE is_featured='2'
AND is_ready ='2'
AND status in ('active')
$and
ORDER BY sort_featured ASC
LIMIT $start,$limit
";
if (isset($_GET['debug'])){
dump($stmt);
}
if ($res=$DbExt->rst($stmt)){
$data='';
foreach ($res as $val) {
$data[]=array(
'merchant_id'=>$val['merchant_id'],
'restaurant_name'=>$val['restaurant_name'],
'logo'=>AddonMobileApp::getMerchantLogo($val['merchant_id']),
);
}
$this->details=array(
'data'=>$data
);
$this->code=1;$this->msg="Ok";
$this->output();
} else $this->msg=$this->t("No Featured Restaurant found");
$this->output();
}
I'm stuck and confused what's causing this error and how to resolve it.
EDIT: Added the full callAjax Function
function callAjax(action,params)
{
/*add language use parameters*/
params+="&lang_id="+getStorage("default_lang");
dump(ajax_url+"/"+action+"?"+params);
ajax_request = $.ajax({
url: ajax_url+"/"+action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function() {
if(ajax_request != null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
} else {
},
complete: function(data) {
ajax_request=null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code==1){
switch (action)
{
case "getFeaturedMerchant":
displayFeaturedRestaurant( data.details.data ,'list-featured');
//$(".result-msg").text(data.details.total+" Restaurant found");
$(".result-msg").text(data.details.total+" "+ getTrans("Featured Restaurants found",'restaurant_found') );
break
)
else {
/*failed condition*/
switch(action)
{
case "getFeaturedMerchant":
createElement('list-featured','');
//$(".result-msg").text(data.msg);
break;
}
},
error: function (request,error) {
hideAllModal();
if ( action=="getLanguageSettings" || action=="registerMobile"){
} else {
onsenAlert( getTrans("Network error has occurred please try again!",'network_error') );
}
}
}};
Calling URL is:
http://domain.com/mobileapp/api/getFeaturedMerchant?
This is actually an issue with the way jQuery handles the abort method when using JSONP, which I have encountered before.
Basically, JSONP works by adding a script tag to the DOM, and adding a callback it will fire when it executes.
Unlike AJAX, the request generated by a script tag cannot be cancelled, so when you call abort like below, it only sort-of works.
ajax_request.abort();
jQuery will unset the global callback it registered, jQuery111309512500500950475_1459208158307 in your case, but it cannot stop the script from trying to run it when it loads. Thus, when it tries to call the now-undefined function, you get the error.
Personally, I think jQuery should set, or have an option to set, these global handlers to an empty function or something instead, but it doesn't. In your case, if possible, I would recommend avoiding making the request if you only plan to abort it before sending it.
Edit:
Two issues I see:
Your code bracing is wrong leading to some unintended execution paths.
You are trying to call .abort() on a JSONP request which is not supported. Doing so will cause the callback function to be removed BEFORE the JSONP script loads that tries to call that callback function. The .abort() will stop the processing of the request, but leave you with the type of script error you see reported.
Here are the notes on the code bracing:
It appears like your code bracing is wrong so you are executing the success callback too soon. When I put your callAjax through a code formatter, it looks like this (see the spot marked "problem area"
function callAjax(action, params) {
/*add language use parameters*/
params += "&lang_id=" + getStorage("default_lang");
dump(ajax_url + "/" + action + "?" + params);
ajax_request = $.ajax({
url: ajax_url + "/" + action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function () {
if (ajax_request != null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
} else {}, // <========== problem here
complete: function (data) {
ajax_request = null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code == 1) {
switch (action) {
case "getFeaturedMerchant":
displayFeaturedRestaurant(data.details.data, 'list-featured');
//$(".result-msg").text(data.details.total+" Restaurant found");
$(".result-msg").text(data.details.total + " " + getTrans("Featured Restaurants found", 'restaurant_found'));
break
) // <========== problem starts here
else {
/*failed condition*/
switch (action) {
case "getFeaturedMerchant":
createElement('list-featured', '');
//$(".result-msg").text(data.msg);
break;
}
},
error: function (request, error) {
hideAllModal();
if (action == "getLanguageSettings" || action == "registerMobile") {} else {
onsenAlert(getTrans("Network error has occurred please try again!", 'network_error'));
}
}
}
};
Add a missing brace in the problem area and you get this. But this is still not really correct. The two switch statements in the success handler are not correct syntax so they need to be fixed too. I think your issue is that you had some counteracting syntax errors that allowed the code to somehow run, but not execute in the proper way.
function callAjax(action, params) {
/*add language use parameters*/
params += "&lang_id=" + getStorage("default_lang");
dump(ajax_url + "/" + action + "?" + params);
ajax_request = $.ajax({
url: ajax_url + "/" + action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function () {
if (ajax_request != null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
}
}, // <======== Added this brace to close off the function
complete: function (data) {
ajax_request = null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code == 1) {
switch (action) {
case "getFeaturedMerchant":
displayFeaturedRestaurant(data.details.data, 'list-featured');
//$(".result-msg").text(data.details.total+" Restaurant found");
$(".result-msg").text(data.details.total + " " + getTrans("Featured Restaurants found", 'restaurant_found'));
break
) // <============= This is out of place and so are the next few lines
else {
/*failed condition*/
switch (action) {
case "getFeaturedMerchant":
createElement('list-featured', '');
//$(".result-msg").text(data.msg);
break;
}
},
error: function (request, error) {
hideAllModal();
if (action == "getLanguageSettings" || action == "registerMobile") {} else {
onsenAlert(getTrans("Network error has occurred please try again!", 'network_error'));
}
}
}
}
});
}
One possible way to approach fixing this is to fix the missing brace in the beforeSend: handler, then remove most of the success handler code to this stub and then add back in the proper code in the success handler under a careful eye:
function callAjax(action, params) {
/*add language use parameters*/
params += "&lang_id=" + getStorage("default_lang");
dump(ajax_url + "/" + action + "?" + params);
ajax_request = $.ajax({
url: ajax_url + "/" + action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function () {
if (ajax_request !== null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
}
}, // <======== Added this brace to close off the function
complete: function (data) {
ajax_request = null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code == 1) {
// <=========== Removed faulty code in here
}
}
});
}
Original Answer
That particular error and network response looks like your client wants some data from the server. The client (for some reason) decides that it needs to use JSONP to get the response from the server so the server is sending back JSONP, but the client code that sent the request did not properly prepare for the JSONP request by defining the appropriate callback function that the JSONP script can call.
You will either have to switch to a regular Ajax call that is not JSONP or we will have to see the details of your callAjax() implementation to see why the JSONP response is not working.
Here my ajax request and response,I have around 85 HTML pages with same ajax request.When i work with these files sometimes im getting following error
AJAX
$(document).ready(function(){
localStorage.setItem('currentPageNo', 9);
ResetSwiper();
CheckPageReadCompleted();
extrapopuptrigger("1");
});
function ResetSwiper() {
toggle_text = localStorage.getItem("currentBibleVersion");
myView = $(".scrollpane").data("mobileIscrollview");
if(toggle_text == "ESV") {
$(".searchContent").hide();
$(".esvContent").show();
setTimeout(function() {
var text_search = null;
$(".esvContent").html('Loading...');
text_search = $(".searchTitle").html();
xhr = $.ajax({
type: "GET",
url: "http://www.esvapi.org/v2/rest/verse?key=IP&passage="+text_search+"&include-footnotes=false",
data:"",
contentType: "text/html",
dataType: "text",
cache: false,
async: true,
crossDomain: true,
success: function(resp) {
$(".esvContent").html(resp);
setTimeout(function() {
if(myView != null || myView != 'undefined') {
myView.refresh();
}
},100);
},
error: function(err) {
var is_uiwebview = /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);
if(is_uiwebview) {
natviveAlert("StandFIRM","Unable to connect internet.Please try again!");
} else {
window.JSInterface.showAlertDialog("StandFIRM","Unable to connect internet.Please try again!");
}
}
},100);
});
} else{
$(".esvContent").hide();
$(".searchContent").show();
myView.refresh();
}
}
How can i solve this issue?Can any one please help me to solve
undefined should not have quotes
if(myView != undefined) {
myView.refresh();
}
Edit:
As #filoxo suggested you can use quotes for undefined but you should add typeof before comparison.
if(typeof myView != 'undefined') {
myView.refresh();
}
Check this link