Ajax call inside a while loop - javascript

I want Ajax to get information while the information is valid. So if I do
$(document).ready(function () {
var url = '/my/url/';
var ses = true;
var i = 0;
while (ses) {
i++;
var temp;
$.get(url + "?get=" + i, function (data) {
if (data != '') {
temp = data;
sortArticles(data);
}
});
if(temp == '') ses = false;
}
});
If I do this without while (putting 0 instead of get var), I get the information I need, but if I put it like this, I enter an infinite loop and the page breaks. By the way, I tested and the if(data != '') statement works as intended.
I don't know why temp doesn't change the state of the ses variable. I tried putting an else statement inside $.get(..)
else ses = false;
but it doesn't do the trick neither.
Thanks for reading!

jQuery ajax (as most ajax implementations), which $.get() is a shorthand for, is asynchronouos be default. The callback function is only executed once the request is complete. The while continues indefinitely since without yielding control out to the JS engine the callback doesn't get a chance to do it's work - even if the request(s) are done.
In order to continuously send requests, try like this:
function requestMore(i) {
$.get('/my/url/?get=' + i, function (data) {
if (data != '') {
sortArticles(data);
requestMore(i + 1);
}
});
}
(document).ready(function () {
requestMore(1);
});

The way you wrote your code temp will never be ''.
The problem is temp is not a string. It's undefined.
Instead of:
if(temp == '') ses = false;
write:
if(typeof(temp) == 'undefined') ses = false;

$(document).ready(function () {
var url = '/my/url/';
var ses = true;
var i = 0;
while (ses) {
i++;
var temp='';
$.get(url + "?get=" + i, function (data) {
if (data != '') {
temp = data;
sortArticles(data);
}
});
if(temp == '') ses = false;
}
});
This will work.Initialize temp as a blank string as shown :)

Related

how to pass json parameters btween 2 files using module

i am trying to call function in other js file using require.all these the parameters
> Login = require("LoginRequest");
Create = require("CreateView");
var params = { username : username.value , password : password.value};
var type ="POST";
var URL = "https://localhost/post_auth.php";
var Result; </li>
and here the call funcion from LoginScreen.js
b2.addEventListener('click',function(e)
{
alert(params.username);
if (username.value != '' && password.value != '')
{
Result=Login.Request(params,type,URL);
}
else
{
// warning alert
alert("Username/Password are required");
}
if (Result.logged == true)
{
alert("Welcome " + Result.name + ", Please answer the following question");
Create();
}
else
{
alert(Result.message);
}
});
when i try to pass the parameters to LoginRequest.
function Request(params,type,url){
var Result;
var loginReq = Titanium.Network.createHTTPClient();
loginReq.open(type,url);
loginReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
//send parameters
loginReq.send(JSON.stringify(params));
loginReq.onload = function()
{
var json = this.responseText;
Result = JSON.parse(json);
alert (Result.logged);
alert (Result.name);
};
return Result;
};
exports.Request = Request;
the calling return undifiend object , where is my wrong here ?
That's because you are making an async call.
when you call loginReq.send() the call will be made and it will continue executing the rest of the code without waiting for the async call to be finished, that's why the function returns undefined.
To fix this you can make a sync call instead of an async call (this is a bad bad bad idea) or you could restructure your code, maybe LoginRequest could return the loginReq instance instead of the result

Why HttpRequest callbacks not working without alert

I have a issue in getting response in Kony application. this is the code
function getServerResponceOption(url){
alert(url);
var httpclient2 = new kony.net.HttpRequest();
var requestMethod = constants.HTTP_METHOD_GET;
var async = true;
httpclient2.open(requestMethod, url,async);
if(getAccessToken() != null && getAccessToken() != ""){
httpclient2.setRequestHeader("AuthToken",getAccessToken());
}
httpclient2.send();
httpclient2.onReadyStateChange = HandleResponce(httpclient2);
}
function HandleResponce(obj)
{
alert("Getting data "+obj.readyState+" Status "+obj.status+" Response "+obj.response );
if(obj.readyState == 4 )
{
if (obj.response != null && obj.response != "")
{
var jsonObj = obj.response;
handleResponseOption(0,jsonObj);
return;
}
else
{
}
}else{
var state = obj.status;
alert("Readystate "+obj.readyState+" Status = "+state);
}
if (obj.response != null && obj.response != "")
{
var jsonObj = obj.response;
handleResponseOption(1,jsonObj);
}
}
Here i got server response if i put the alert message in HandleResponce(obj) without the alert i didn't get any response. the ready state is 1 and status is 0. What is the problem occurred if i remove the alert message?
Note: URL and getAccessToken() is getting values.
You are calling function in line, When you use HandleResponce(httpclient2) function is immediately executed.
httpclient2.onReadyStateChange = HandleResponce(httpclient2);
Change your code as
httpclient2.onReadyStateChange = function(){ HandleResponce(httpclient2) };

Node file uploads and sychronicity

While I'm generally comfortable with rudimentary asynch patterns in node I have come across a situation where I need the return value from an asynch call in a generally synchronous situation.
Given the function:
modelHelper.saveFile = function(field) {
var url = cloudinary.uploader.upload(this.req.files[field.name].path, function(result) {
if(typeof result.url != "undefined" && result.url.length > 0)
{
console.log(" \n\n\n Inside the cloudinary call.");
console.log("\n\n URL = " + result.url);
return result.url;
}
return false;
});
console.log("\n\n\n Outside the load, URL =" + url);
if(!url) return "";
return url;
};
This function is called in the case of uploading a file to a server, and is called by a simple loop which loops over all of the elements of a page. For the majority of cases it's a simple mapping of variable to value, as such I really don't want to need to inject a next into this function.
Here's the caller:
modelHelper.parseField = function(field) {
var type = field.type;
switch(type) {
case "email":
case "url":
return strings.exists(this.param(field.name)) ?
this.param(field.name) : "";
break;
case "file":
return modelHelper.resolveFile.bind(this)(field);
break;
default:
return strings.exists(this.param(field.name)) ?
strings.makeSafe(this.param(field.name)) : "";
}
and this, in turn is called by:
modelHelper.populate = function(elements, record, next){
var len = elements.length;
parseField = modelHelper.parseField.bind(this);
while(len--)
if((elements[len]["type"] != "captcha"))
this[record][elements[len]['name']] = parseField(elements[len]);
next.bind(this)();
};
as such, I'm looking for a pattern that will block execution until the file operation in saveFile returns a variable; something like wrapping it in a setInterval type call was my first thought, but is there a better way?
Pass a callback to saveFile and call it with the url once the upload is complete
modelHelper.saveFile = function(field, callback) {
var url = cloudinary.uploader.upload(this.req.files[field.name].path, function(result) {
if(typeof result.url != "undefined" && result.url.length > 0) {
console.log(" \n\n\n Inside the cloudinary call.");
console.log("\n\n URL = " + result.url);
return callback(null, result.url);
}
return callback();
});
};

How to add a param to a URL that trigger jQuery to run a function on load

Is there a way to add a url param like: http://site.com?open=true
And on document ready, if jQuery sees the open param set to true execute a function?
Thanks
first lets make a good Query string searcher in JS
function querySt(qsName, url)
{
var theUrl;
if (url == null || url == undefined)
theUrl = window.location.search.substring(1); else theUrl = url;
var g = theUrl.split("&");
for (var i = 0; i < g.length; i++) {
var pair = g[i].split("=");
if (pair[0].toLowerCase() == qsName.toLowerCase())
{
return pair[1];
}
}
return null;
}
$(function (){
if (querySt("open")!='true') return;
});
taken from website http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
You can test location.href with a regex:
if (location.href.match(/open=true/)
// do something
You might want to work on the regex though, to make sure it works for you.

Get reference to 'triggerElement' in onSuccess function?

Is it possible to get a reference to the triggerElement that invoked the Ajax request in the onSuccess function?
<%=Ajax.ActionLink("x", a, r, New AjaxOptions With {.OnSuccess = _
"function(context) {alert('get triggerElement reference here?');}" })%>
The page is rendered to:
x
So let's have a look at Sys.Mvc.AsyncHyperlink.handleClick inside Scripts\MicrosoftMvcAjax.debug.js:
Sys.Mvc.AsyncHyperlink.handleClick = function Sys_Mvc_AsyncHyperlink$handleClick(anchor, evt, ajaxOptions) {
/// omitted doc comments
evt.preventDefault();
Sys.Mvc.MvcHelpers._asyncRequest(anchor.href, 'post', '', anchor, ajaxOptions);
}
So the ActionLink is rendered to an anchor ("a") tag, with an "onclick" event, which uses Sys.Mvc.AsyncHyperlink.handleClick with this as one of the parameters, mapped to anchor.
Then there's this Sys.Mvc.MvcHelpers._asyncRequest call with anchor as the fourth parameter. Let's have a look in Sys.Mvc.MvcHelpers._asyncRequest:
Sys.Mvc.MvcHelpers._asyncRequest = function Sys_Mvc_MvcHelpers$_asyncRequest(url, verb, body, triggerElement, ajaxOptions) {
/// omitted documentation
if (ajaxOptions.confirm) {
if (!confirm(ajaxOptions.confirm)) {
return;
}
}
if (ajaxOptions.url) {
url = ajaxOptions.url;
}
if (ajaxOptions.httpMethod) {
verb = ajaxOptions.httpMethod;
}
if (body.length > 0 && !body.endsWith('&')) {
body += '&';
}
body += 'X-Requested-With=XMLHttpRequest';
var requestBody = '';
if (verb.toUpperCase() === 'GET' || verb.toUpperCase() === 'DELETE') {
if (url.indexOf('?') > -1) {
if (!url.endsWith('&')) {
url += '&';
}
url += body;
}
else {
url += '?';
url += body;
}
}
else {
requestBody = body;
}
var request = new Sys.Net.WebRequest();
request.set_url(url);
request.set_httpVerb(verb);
request.set_body(requestBody);
if (verb.toUpperCase() === 'PUT') {
request.get_headers()['Content-Type'] = 'application/x-www-form-urlencoded;';
}
request.get_headers()['X-Requested-With'] = 'XMLHttpRequest';
var updateElement = null;
if (ajaxOptions.updateTargetId) {
updateElement = $get(ajaxOptions.updateTargetId);
}
var loadingElement = null;
if (ajaxOptions.loadingElementId) {
loadingElement = $get(ajaxOptions.loadingElementId);
}
var ajaxContext = new Sys.Mvc.AjaxContext(request, updateElement, loadingElement, ajaxOptions.insertionMode);
var continueRequest = true;
if (ajaxOptions.onBegin) {
continueRequest = ajaxOptions.onBegin(ajaxContext) !== false;
}
if (loadingElement) {
Sys.UI.DomElement.setVisible(ajaxContext.get_loadingElement(), true);
}
if (continueRequest) {
request.add_completed(Function.createDelegate(null, function(executor) {
Sys.Mvc.MvcHelpers._onComplete(request, ajaxOptions, ajaxContext);
}));
request.invoke();
}
}
So the original anchor is now triggerElement, but as you can see, this parameter is never used in the function's body.
So, if you want to have some kind of a "formal" (or documented) reference to triggerElement - no such thing.
But hey, it's JavaScript, so you can access almost anything as long as the browser did not move to another page, including the call stack. For instance:
<script type="text/javascript">
function a(p, q)
{
b();
}
function b() {
var x = arguments.caller[1];
alert(x); // boo!
}
a(789, "boo!");
</script>
So eventually you can hack it and access the original anchor. I suggest you do the following:
Write a function to be invoked in the
OnBegin.
Inside this function, access
the original triggerElement, and
add it as a property to the original
ajaxOptions (which can be accessed,
too)
Then, in the OnSuccess function,
access your hacked property of
ajaxOptions.

Categories

Resources