Calling another function while long polling - javascript

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).

Related

Retrieving JSON data is not working as expected

Below I have a JSON array in my main PHP file. As you can see $firstname_error and $lastname_error are variables which I intend to pass to AJAX in order to have it displayed in two separate divs. At the moment nothing shows up and am unsure why. Any insight is greatly appreciated.
PHP & JSON
if (empty($_POST["City"])) {
$city_error = "A city required";
}
if (empty($_POST["E-mail"])) {
$email_error = "E-mail is required";
}
echo json_encode(array("city" => $city_error, "email" => $email_error));
AJAX
$(document).ready(function () {
$(".form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "destination.php",
data: $(this).serialize(),
dataType: 'json',
cache: false,
success: function (data) {
if (data.trim() != '') {
$('.error4').html(data.city);
$('.error5').html(data.email);
}
},
error: function () {
}
});
});
});
.error4 and .error5 currently displays nothing.
Since you have dataType: 'json', the data variable passed to your success function is going to be an object so you can't use trim().
To check if the value exists in the response you can use hasOwnProperty on data:
success: function (data) {
$('.error4').text(data.hasOwnProperty('city') ? data.city : '');
$('.error5').text(data.hasOwnProperty('email') ? data.email : '');
},
Hope this helps!
I believe your if condition is not true, So try changing your success function like this:
success: function (data) {
if (data.city.trim() != '') {
$('.error4').html(data.city);
}
if (data.email.trim() != '') {
$('.error5').html(data.email);
}
}
Ok, I figured it out. Use if(data !== null) instead of if (data.trim() != '')

AJAX call never reaching error statement

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.");
}
});
}
}
});

TypeError: jQueryxxxxxx is not a function

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.

Wait for ajax response using a yii2 form

I am implementing a form that request a process with ajax to sync 2 databases and I need to wait until the process finish.
In my form I have the flowing code to send the db credentials:
<div class="col-lg-offset-1 col-lg-11">
<?=
Html::a('Sync Databases', ['runsync'], [
'class' => 'btn btn-primary',
'id' => 'ajax_link_02',
'data-on-done' => 'linkFormDone',
'data-form-id' => 'syncdb_form',]
)
?>
and I also register the js with the ajax
function handleAjaxLink(e) {
e.preventDefault();
var
$link = $(e.target),
callUrl = $link.attr('href'),
formId = $link.data('formId'),
onDone = $link.data('onDone'),
onFail = $link.data('onFail'),
onAlways = $link.data('onAlways'),
ajaxRequest;
$("#show_msg").html("Loading.... please wait...");
ajaxRequest = $.ajax({
type: "post",
dataType: 'json',
url: callUrl,
data: (typeof formId === "string" ? $('#' + formId).serializeArray() : null)
});
// Assign done handler
if (typeof onDone === "string" && ajaxCallbacks.hasOwnProperty(onDone)) {
ajaxRequest.done(ajaxCallbacks[onDone]);
}
// Assign fail handler
if (typeof onFail === "string" && ajaxCallbacks.hasOwnProperty(onFail)) {
ajaxRequest.fail(ajaxCallbacks[onFail]);
}
// Assign always handler
if (typeof onAlways === "string" && ajaxCallbacks.hasOwnProperty(onAlways)) {
ajaxRequest.always(ajaxCallbacks[onAlways]);
}
}
var ajaxCallbacks = {
'linkFormDone': function (response) {
$('#show_msg').html(response.body);
}
}
The ajax call works fine and call the controller:
public function actionRunsync() {
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new \app\modules\admin\models\syncdb();
$response = $model->runSyncDb($_POST);
$res = array(
'body' => $response,
'success' => true,
);
return $res;
}
}
But is not waiting to the process
$model->runSyncDb($_POST)
to finish. If I comment the process and add a text it works fine but not if the process takes long.
What am I doing wrong?
I just added async false to the ajax request:
async: false,
so now the ajax is like this:
ajaxRequest = $.ajax({
type: "post",
async: false,
dataType: 'json',
url: callUrl,
data: (typeof formId === "string" ? $('#' + formId).serializeArray() : null)
});
Not sure the best way but works perfectly...

TypeError 'undefined' occurs sometimes during Ajax calls

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

Categories