Interactive for + get function - javascript

I need a problem with a function to update some informations in my database (I'm using the websql). In my application, I'm showing a loading box for do the update, but, the for ends before the get function is complete and the loading box e closed.
I need that the next interaction of the for only happen when the get is finish.
Someone has a solution for this? :(
I'm using the appframework intel (jqmobi)
for (var i=0; i<len; i++){
var url = "http://172.25.129.30:8180/prax/rest/ocorrenciaJSONBean/consultarStatusOcorrencia/"+results.rows.item(i).id;
$.get(url,function(data){
tx.executeSql('UPDATE ocorrencias SET status="'+data.responseText+'" WHERE id = '+results.rows.item(i).id);
});
};
I have the following scenario:
An internal bank with a list of calls that a user opened on cell. What I want is to upgrade the status of the bank.
Today I do a query on internal bank and each id I perform a get on a webservice place to know the status of the call. I would like the next interaction is only occurred when the GET was finalized.
The problem here is that once the function ends, the screen refreshes and the message is "loading" disappears. This is occurring earlier than expected, since the end is before all GETs are finalized.

The get is not waiting to perform a call so you need to do a callback in your get function to perform the next one. You could do something like this:
var index = -1;
function perform_get(){
index++;
var url = "http://172.25.129.30:8180/prax/rest/ocorrenciaJSONBean/consultarStatusOcorrencia/"+results.rows.item(index).id;
$.get(url,function(data){
tx.executeSql('UPDATE ocorrencias SET status="'+data.responseText+'" WHERE id = '+results.rows.item(index).id);
})
.done(perform_get);
}
Now it is waiting to perform the next get call.
Hope this helps.

Related

Rest API Search Results is not the same as the results returned by the search page

I have A search rest API, when I run it through Share point Designer, i don't Get the Same Number if results as Returned by the Search page on the Share point site, I have tried Using different Source ids , also tried to use the default source id from results source but I always get the same results so i am not sure what I am doing wrong.
My Other Thought is, IS there a way to Get all the results From the Default search function Built in to Share-point?
var ct = new SP.ClientContext.get_current();
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(ct);
var queryStr = ctx.DataProvider.get_currentQueryState().k;
keywordQuery.set_queryText(queryStr);
keywordQuery.set_trimDuplicates(false);
keywordQuery.set_enableSorting(true);
keywordQuery.set_sourceId=("xxxxxx-xxxx-xxxx-xxx-xxxxxxx");
keywordQuery.set_rowLimit(500);
keywordQuery.set_trimDuplicates(false);
var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(ct);
var results = searchExecutor.executeQuery(keywordQuery);
ct.executeQueryAsync(onQuerySuccess, onQueryFail);
function onQuerySuccess()
{
results.m_value.ResultTables[1].ResultRows.forEach(function (row)
{
var Aname1 = row.name;
console.log(row);
if (!$isNull(Aname1))
{
var name= Aname1;
console.log(name);
}
});
}
function onQueryFail()
{
}
Usually, the results are paginated. What it means is that, instead of returning all the results at once, they are divided into parts and each part (page) is sent once.
For example, when you search in google.com, instead of returning all 1,50,00,000.... results, Google returns only 10 results or so. To get the next 10 results, you click the next button in the pagination menu at the bottom of the page.
This is done so that the API and network don't get overloaded. Imagine how large a response with 1,50,00,000 records would be.
This is what's happening with you. In the response you recieved, see if there's a record with a URL for the next page, Microsoft usually does things this way. If you call that URL, you'll get the next page. If that's not there, see if the URL you called has a parameter somewhere, where you can select the page.

Functional Javascript BaconJS, how can I push more values to an event stream?

I'm attempting to create a stack of AJAX responses in BaconJS. That processes them in a first in first out fashion, but each 'out' event should wait for user input.
This is where I'm at now: Live JSBin
var pages = Bacon.fromArray([1,2,3])
var next = $("#next").asEventStream('click').map(true);
pages.flatMapConcat(asyncFunction).zip(next).log("responses")
function asyncFunction(page) {
// Simulating something like an AJAX request
return Bacon.later(1000 + (Math.random() * 3000), "Page "+ page)
}
Currently this synchronously outputs an event from the pages EventStream each time that #next is clicked, which the behavior I want.
However, I am unable to figure out how to push more values to the pages EventStream. I have attempted to replace the pages EventStream with a Bus, and pushing values like this (which doesn't work).
var pages = new Bacon.Bus()
pages.push("value")
How do I push more values to an EventStream?
I know this is an OLD post, but bus would work. Just push the number (you had an array of numbers before) into it:
var pages = new Bacon.Bus();
// Bacon.fromArray([1,2,3])
var next = $("#next").asEventStream('click').map(true);
pages.flatMapConcat(asyncFunction).zip(next).log("responses")
function asyncFunction(page) {
// Simulating something like an AJAX request
return Bacon.later(1000 + (Math.random() * 3000), "Page "+ page)
}
pages.push(1);
pages.push(2);
pages.push(3);
I cloned your jsbin and changed it to use bus
As mentioned previously, you could stream the source of the page values using something like fromEvent or from fromBinder

Check when a Oracle 11gR2 scheduled job has completed and alert the user in Oracle APEX

Within Oracle APEX v4.2, I have an application by where a user presses a button which then goes off and submits a scheduled background job, allowing the user to continue working within the application. The job is kicked off using Oracle's DBMS_SCHEDULER.
My question is and want to keep it within the Oracle APEX space - assuming there is a table that stores when the job was initiated as well as when it eventually completes, how can I interact with this table, check whether the job has completed (i.e. somehow poll the table and stop when the "COMPLETE" status is found) and then, provide an 5 second alert that slides in and then slides out, notifying the user that the job has completed.
Can I use JavaScript (callback) via Dynamic Actions?
If you don't want to go down the plugin route, you can use the following code in an Application Process, called ProgressCheck in this instance:
DECLARE
CURSOR c_time_elapsed
IS
SELECT SUBSTR(elapsed_time,6,2)||'hrs '
||SUBSTR(elapsed_time,9,2)||'mins '
||SUBSTR(elapsed_time,12,2)||'secs' ELAPSED_TIME
FROM user_scheduler_running_jobs
WHERE job_name = 'XX_YOUR_JOB_NAME'
UNION ALL
SELECT '00:00'
FROM DUAL
WHERE NOT EXISTS (SELECT SUBSTR(elapsed_time,9) ELAPSED_TIME
FROM user_scheduler_running_jobs
WHERE job_name = 'XX_YOUR_JOB_NAME');
BEGIN
FOR r_time IN c_time_elapsed LOOP
htp.p('<p>Time elapsed: '||r_time.ELAPSED_TIME);
END LOOP;
htp.p('');
END;
In the Page header, include the following JavaScript:
<script type="text/javascript">
<!--
var myInterval;
function f_ProgressCheck(){
var get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=ProgressCheck',$v('pFlowStepId'));
gReturn = get.get();
get = null;
gReturn = (!gReturn)?'null':gReturn;
$s('P1_PROGRESS_RESULT',gReturn);
}
function f_myInterval(){
myInterval = setInterval ( "f_ProgressCheck()", 5000 );
}
//-->
</script>
This will call the Application Process every five seconds once your page has loaded and will put the results of the check into P1_PROGRESS_RESULT.
You can amend the Application Process to suit your requirements, perhaps returning something else or additionally checking for completion, like in the following code:
DECLARE
CURSOR c_job_count
IS
SELECT COUNT(*) TOTAL
FROM user_scheduler_job_log
WHERE job_name = 'XX_YOUR_JOB_NAME'
AND log_date >= (SYSDATE - 1/1440);
BEGIN
FOR r_job_count IN c_job_count LOOP
IF r_job_count.total = 1 THEN
htp.p('<p>Your data is ready to view.');
htp.p('<p>Click Go to view the report.');
htp.p('<input type="button" onclick="javascript:this.disabled=true;this.value=''Please wait...'';doSubmit(''REPORT'');" value="Go" class="RelevantAPEXClass" />');
ELSE
htp.p('<p>');
END IF;
END LOOP;
END;
You could also combine the PLSQL to deliver everything in one process.
You could also call the PLSQL (preferably) using a Dynamic Action.

AJAX progress bar on array iteration?

I am not too familiar with AJAX but I'm sure what I am trying to do is possible.
Basically I have a form with a text area, when the form is submitted the text area is made into an array with each new line being a value. Simple stuff, now my php then performs a database query on each array value. Also simple.
Now as the operation takes a while I want to make it into an AJAX call using jquery, and for every iteration on the array I want it to display the result back on my main page as well as displaying a progress bar.
So if my text area contains a list of 20,000 names and the query is to fetch the ages of these people, the ajax call would split the textarea into an array and iterate the array. For each iteration it should perform the query and send the result to my main page. So on my main page I will see a list that grows over time.
I hope I have explained this well enough, I just need advice on where to start/what to research. Any examples would be greatly appreciated.
Thanks!
As ajax is simply a request for data you cannot create a reliable loading bar easily.
However if you are doing loads of requests as you suggest in your question, "Which by the way is not the best idea".
You could do something like the code below. Again its pretty basic but will give your user a rough idea. I stuck it in a fidddle here for you http://jsfiddle.net/6dgAF/ its a basic example but should give you a jump off point.
function Status(data)
{
this.data = data;
this.size = this.data.length;
this.current = 0;
this.bar = $("#bar");
//Get width of each step of load
this.step = (this.bar.width() / this.size) ;
for(var i =0; i < this.size; i++){
this.getData(this.data[i]);
}
}
Status.prototype.getData = function(string){
//run your ajax here on each string and on success do this
//$.get( "ajax/test.html", function( string ) {
//this.current++;
//this.updateBar();
//});
this.current++;
this.updateBar();
}
Status.prototype.updateBar = function(){
//updates the bar with the current count * step width;
$("span",this.bar).width(this.step*this.current);
}
//Init object and put in dummy data
var status = new Status(new Array("string1","string2","string3","string4","string5","string6","string7","string8","string9","string10"));
An AJAX request is nothing else than requesting data from your server, just like any HTML page. The only difference is that you use Javascript, and don't feed the data to your browser as an HTML page, but use the data some way on your page.
One possible way to do the thing you want is the following:
Set an interval with the refresh rate, which calls a function getData
In getData you perform an AJAX request, which requests a piece of data from the server, which represents the current state. You might want to make sure the server only returns incremental updates, to avoid sending large amounts of data
Use the data on your front page, by displaying it in a friendly way to the user.
The main thing to keep in mind is that the server must save it's current state (the data which it has gathered with its queries), which it must return in the event of an AJAX request.
What you want is called XHR2 - personally I am using dojo
(dojo/request/xhr here)
However it should be possible with jQuery as well, search for jQuery XHR2 progress ...

CRM 2011 Queries with valid paging cookie should not be executed in this strategy

I get this error.
Error : 500: Internal Server Error: Queries with valid paging cookie
should not be executed in this strategy
when I invoke this code in a WebResource in CRM 2011
self.loadWorkItems = function () {
var user = self.user();
var bid = user.BusinessUnitId.Id();
var systemUserId = user.SystemUserId();
var results = new Array();
SDK.REST.retrieveMultipleRecords(
"QueueItem",
"$select=*&$skip=" + self.page() * self.pageSize() + "&$top=" + self.pageSize() + "&$orderby=CreatedOn asc&$filter=OwningBusinessUnit/Id eq guid'" + bid + "' and StateCode/Value eq 0",
function (r) {
results = results.concat(r);
},
function (error) {
self.lastError(error.message);
},
function (x) {
for (var i = 0; i < results.length; i++) {
var item = results[i];
var r = ko.mapping.fromJS(item, workItemMapping);
self.workQueue.push(r);
}
}
);
};
this is part of a knockoutjs viewmodel. I am trying to make a "More" button that goes and gets the next page of data from the server and throws it on the end of the list being displayed.
The page loads just fine and the first page comes back but when the next page is requested I get this error.
Any ideas on how to make the call without the error?
EDIT
I was mistaken It seems that some calls with $skip > 0 work. Going crazy here.
EDIT
I think what this error is trying to tell me is that the skip/top combo is more than the total record count and instead of giving me nothing (as I would expect), it's throwing an exception.
So the new question is how to avoid this stupidity? I guess now I have to count all the records and and make sure I don't page too much.
We deliberately catch all errors when performing query's since the SDK has a bug in the skip and take linq query's which is causing issues when skipping more then the result has items. As far as i know this isn't fixed by Microsoft yet
You fetch an non existing "page". Basically you are skipping more element than the result has.
So lets say that the underlying result in total have 10 records that match your filter and you say
query.skip(12) then you get this situation.

Categories

Resources