w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Ajax calls and JQuery: stop previuos ajax calls
My experience with aborting ajax-calls is that it can be pretty random when it works. A workaround that I've used once or twice is counters: var lastRequest=null; var started = 0, finished = 0; $('#button').click(function() { ++started; lastRequest = $.ajax({ type: "POST", url: "MyAction.do", success: function (response) { //Only do stuff on the last active request if(++finished == started) response= $('<div/>').append(response); } }); });

Categories : Ajax

Can Haskell optimize function calls the same way Clang / GCC does?
If your goal is to get this running as quickly as your C++ compiler, then you would want to use a data structure that the compiler can have its way with. module Main where import qualified Data.Vector as V b :: Int -> Int b x = x + 5 c x = b x + 1 d x = b x - 1 a x = c x + d x main = do putStrLn "Starting..." putStrLn $ show $ V.foldl' (+) 0 $ V.map a $ V.enumFromTo 1 100000000 putStrLn "Done." GHC is able to completely eliminate the loop and just inserts a constant into the resulting assembly. On my computer, this now has a runtime of < 0.002s, when using the same optimization flags as you originally specified. As a follow up based on the comments by @Yuras, the core produced by the vector based solution and the stream-fusion solution are functionally identical.

Categories : C++

SignalR Method Calls - Faster than Conventional AJAX Calls?
IMHO this would be a misuse of SignalR. Would it be faster? It really depends on several factors. The first of which is which transport ends up being used. If it's Web Sockets, then, yes, because a message will be sent over a connection that's guaranteed to already be established, but if it's SSE or LongPolling you're still doing a plain old HTTP POST every time to send messages. Second factor is that if the server is allowing Keep-Alive connections, then browsers will keep open TCP connections to the server for some period of time between requests anyway so there would be no overhead in terms of establishing a connection anyway. Also, let's not forget our powerful friend the GET verb and all the goodness it brings in terms of one of the most important features of the web: caching. If

Categories : Ajax

Optimize calls to a commonly called, expensive query
Do you have an index on the following fields? tblTasks(ModifiedTime) tblItems(ModifiedTime) ListItems(ModifiedTime) This should ensure pretty good performance. If you do, and there is still the problem of interacting locks, then you might consider having another table with this information. If you do updates/inserts directly on the tables, this would require triggers. If you wrap updates and inserts in stored procedures, then you can do the changes there. This would basically be turning the view into a table and updating that table whenever the data changes. That update should be very fast and have minimal interaction with other queries.

Categories : SQL

Does the compiler optimize non-polymorphic calls to virtual methods?
Does the compiler optimize/inline non-polymorphic calls to virtual methods? Yes, every decent compiler would do this. GCC and MSVC do it even on -O0//Od modes. LIVE DEMO #ifdef _MSC_VER #define NOINLINE __declspec(noinline) #else #define NOINLINE __attribute__ ((noinline)) #endif template<int> NOINLINE void ASM_MARKER() { static volatile int anti_opti = 11; (void)anti_opti; } void base(); void derived(); struct Base { virtual void foo() { base(); } }; struct Derived: Base { void foo() override { derived(); } }; int main() { ASM_MARKER<1000>(); Base b; b.foo(); ASM_MARKER<2000>(); Derived d; d.foo(); ASM_MARKER<3000>(); Base &r = d; r.foo(); ASM_MARKER<4

Categories : C++

Why doesn't C# compiler optimize away duplicate local variable default value initialization?
Why doesn't compiler omit generating IL for things like int foo = 0; for local variables since .locals init already cover that? Why should it? I have not actually verified this, but I would be surprised if the JIT compiler generated different native code if you removed the unnecessary initialization. What this means is that the only benefit adding this optimization to the C# compiler would have is to make the JIT compilation tiny bit faster (because it would have to process smaller amount of IL code). It seems the authors of the C# compiler though that making this optimization for such a tiny benefit is not worth it.

Categories : C#

Show ajax spinner, hide page render until ALL ajax calls complete?
One approach would be to display your loading animation as part of your initial page & page load. Then, wait for your outstanding ajax calls to reach zero and once that happens, hide the loading animation. Your document ready would look something like: $(document).ready(function() { $('#spinner').addClass('spin'); function stopSpinner() { $('#loading').addClass('hide'); $('#loading').one('webkitTransitionEnd', function() { $('#loading').hide(); }); } $(document).ajaxStop(function () { // $.active == 0 stopSpinner(); }); }); Your markup would have something like this as the last elements in the body: <div id="loading"> <div id="spinner"></div> </div> With styles like this: #lo

Categories : Ajax

only one ajax call from javascript loop instead of looping multiple ajax calls
JS-Call: $.post('update_page_positions.php', {'myArray': m}, function(data, statusText) { // This block is optional, fires when the ajax call is complete } ); AJAX-Handler: <?php include("connect.php"); $myArray = json_decode($_POST['myArray']); // do stuff with $myArray here. ?>

Categories : PHP

Sending an AJAX call before all other AJAX calls
UPDATED: Have one method on an interval that sets up the 'session'/local-storage var refreshing = false; var intervalID; $(document).ready(function(e){ var delay = 1234; intervalID = window.setInterval(setupInterval, delay); }); function setupInterval(){ refreshing = true; $.ajax(URL).done(function(r) { //do stuff setupStorage(r); refreshing = false; }); } function setupStorage(info){ //setup whatever here } OLD: Could you use some logic in your ready function to gate what you need to do? So basically call one ajax call -> if false, just schedule your latter methods, otherwise run the setup one and on completion schedule the latter method. Some pseudo-code: var refresh = false; $(document).ready(function(e){ $.ajax(URL).done( function(r) { if(r) {

Categories : Javascript

How to nest knit calls to fix duplicate chunk label errors?
I don't understand exactly the context use of your code. Why not to use simply knitr child document feature? Here a workaround ( hope that someone else come with a better solution specially you if you give more context) some_function <- function(chunk.name='chunk1'){ knit(text =sprintf(" ```{r %s} 1 ``` ",chunk.name)) } cat(knit(text =" ```{r } some_function('a1') ``` ```{r } some_function('a2') ``` "))

Categories : R

Angularjs ng-grid REST calls
Your missing your ng-model from the template var nameEditableTemplate = "<input type="text" ng-class="'colt' + col.index" ng-model="COL_FIELD" ng-input="COL_FIELD" ng-blur="updateEntity(col, row)"/>"; Hope this solves it

Categories : Angularjs

How do I avoid AngularJS in inline javascript calls?
You can encapsulate your own behavior using directives and setup bindings for events on elements to call a function if you want to wrap up a behavior (I believe I read that Ben Nadel an AngularJS blogger does... http://www.bennadel.com/blog/2446-Using-Controllers-In-Directives-In-AngularJS.htm). As is stated in the comment though I personally don't find it to be an issue, if I was on a larger team I could potentially see the desire to leave the binding up to a javascript developer and not have the HTML developer worry about those details and use directives only but seeing as how I write both parts I don't have any issue. Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register beh

Categories : Angularjs

How do Ajax calls fit in with a MVC structure
im using codeigniter, im using an dedicated controller for ajax and checking $_SERVER['HTTP_X_REQUESTED_WITH'] to determine if its an ajax request. you can use same approach, and you can keep all of your structure(use your models in ajax controller etc...)

Categories : Ajax

Ajax calls using Q and jQuery
OK, I think the heart of this problem is probably a CORS issue. The site I was serving the jQuery and Q libraries from (i.e. the page I loaded when I ran the Firebug session above), didn't have any Origin header. I have to dig into it to confirm this, but when I served jQuery and Q from the same site as the API I'm trying to access (via Ajax), things started working. It would have been nice if Firebug and/or jQuery had actually propagated the CORS error when the various promises failed. :-(

Categories : Jquery

Multiple Ajax Calls
This is possible. You can make a AJAX call as a callback from the first call. $.ajax({ url:"/echo/json/", data:xdata, type:"POST", success: function(data) { $.ajax({ // config success: function(data2) {}; // do your stuff }); } }); If you need multiple AJAX calls simultanously, you cann work with the deferred-object: jQuery Deferred - getting result of chained ajax calls

Categories : Jquery

Simultaneous ajax calls
First of all, I recomment wrapping your xmlHttpRequest generation/handling in a function, so you don't duplicate code that much. The problem you have there is that the data variable is global, so both ajax callbacks are using the same variable. You can fix it using the var keyword in both calls. xmlhttp2.onreadystatechange = function() { if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) { var data = JSON.parse(xmlhttp2.responseText); console.log('data2: ' + data); } }

Categories : Javascript

AJAX calls - where does logic go?
There's a few critical concepts you may be confused about. First. JSON is not a file, it's a format, more simply, a type of string. It's really good for collapsing arrays and storing address-value pairs, so a lot of data flies around in that format. Strictly speaking, they are JSON objects, but they're a lot like strings and arrays. It looks like this, if I remember correctly: { "name" : "john doe", "pet" : "dog", "hobby" : "parasailing" } Second, AJAX is a request to the server, made from the client (the browser) after the original page has loaded. That is, you type in 'youtube.com' and the youtube server receives the request and sends a big pile of HTML back to your browser. You watch your video, make a rating, and the browser doesn't reload the page but instead sends a separ

Categories : Javascript

AngularJS calls HTTP multiple times in controller
I don't think it is getting called twice, i just created a plunk for you to see this. var app = angular.module('projectsApp', []); app.controller('filtersController', ['$scope', '$http', function ($scope, $http) { $scope.status = 'Page loading'; var count = 0; $scope.init = function () { $scope.status = 'API called'; $http({ method: 'GET', url: '/json-tags-test', cache: true }).success(function (data, status, headers, config) { // this callback will be called asynchronously // when the response is available console.log('success'); count++; $scope.status = 'successful: '+ count; }).error(function (data, status, headers, config) { // calle

Categories : Json

How to limit frequency of calls to model functions in angularjs?
You can use $watch method on scope to react when todos changed. I cant say is this way better for performance. $scope.$watch('todos', function() { $scope.remaining = ... // remaining just int }, true); Also, if you use new angular, look to $watchCollection method.

Categories : Javascript

Check for any ongoing background API calls to finish in AngularJS
Perhaps something like: $scope.$watch('!is_searching && publishing', function(newVal){ if (newVal) { $scope.memberslist.members = $scope.memberslist.temp; $scope.publishing = false; } }) Set "is_searching" to true on the scope when the search starts, and set it to false when it is done. Set "publishing" on the scope when the search button is clicked. That should give you the desired behavior. Publish right away if no search is running, otherwise wait until search is complete.

Categories : Angularjs

In AngularJS, how can I see errors from templates, such as calls to undefined methods?
AngularJS expressions are not evaluated with eval(). http://docs.angularjs.org/guide/expression This is actually a huge advantage of Angular, as it leads to less buggy user experiences. Forgiving: expression evaluation is forgiving to undefined and null, unlike in JavaScript, where trying to evaluate undefined properties can generate ReferenceError or TypeError. As far as I know, there is no way to change this ^

Categories : Angularjs

Secure jsonp ajax calls
With ajax request you can send authentication headers beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + "username:password"); }, or insert authentication data with: $.ajax({ type: "GET", username: "user", password: "password", .... } but you have to handle authentication by yourself in your web-service. Or you could add with the var payLoadData some custom authentication data which you check with your web-service. You should also consider to make the connection under https if you don't want other people to intercept your authentication packets

Categories : Java

Making two simultaneous AJAX calls to PHP
Use setTimeout();. setInterval() executes the code after the time specified and setTimeout() executes the code every time it reaches the specific time. These question explain well of their difference :) setTimeout or setInterval? 'setInterval' vs 'setTimeout' setInterval & setTimeout? setInterval and setTimeout JavaScript setInterval and setTimeout And a search of this on SO will solve your problem :)

Categories : PHP

Waiting for multiple Ajax calls
Use $.when var array = []; $("#canvas .active[target]").each(function() { this$ = $(this); targetName = this$.attr('target'); target$ = $('div[name=' + targetName + ']'); if (target$.length == 0) { var ajax = $.post('loadData.php', { fileName : targetName + '.xml' },function(xml) { canvasData$ = $(xml).find("canvasData"); $('#canvas').prepend(canvasData$); }); array.push(ajax) } }); $.when.apply($, array).done(function(){ //do something })

Categories : Jquery

Concurrency with two files and two AJAX calls
I don't really get your point, but if you want to lock files for write or read use flock in php. http://php.net/manual/en/function.flock.php

Categories : PHP

browser performance after some ajax calls
Try using e.preventDefault(); before you submit or click to send a ajax request ..Just a try Also there are few links for reference Link 1 Link 2 Link 3

Categories : Ajax

Should I load all AJAX calls through an API subdomain?
The problem with plain JSON is that you cannot do cross domain AJAX requests, that includes subdomains. But for every problem is a solution. There is a technique called CORS, that means that you just need to add a special header to allow that cross domain calls. So if you just want to allow the domain example.com the header should look like this: Access-Control-Allow-Origin: http://example.com If you want to allow access from all domains use the asterisk instead: Access-Control-Allow-Origin: * And finally the php code, you must put this line php before any other output else you will get a warning and the ajax call will fail: header("Access-Control-Allow-Origin: http://example.com");

Categories : Ajax

Chaining a series of ajax calls
For sequential ajax calls what i have is calling another ajax inside the success of first ajax. Like this:- function ajax1(){ $.ajax({ url: "", data: dataString, type: "POST" , dataType: "text", cache: false, success: function(response_data){ ajax2(); // call second ajax on success } }); } function ajax2(){ $.ajax({ url: "", data: dataString, type: "POST" , dataType: "text", cache: false, success: function(response_data){ } }); }

Categories : Jquery

Trying to stop/continue ajax calls
Set the interval to a variable and clear it when you hide it: var timeout = null; var expanded = false; var ajax = null; $(".expandhide").click(function() { expanded = !expanded; //Reverse it if (expanded) { update(); //Call update again but right away } else { //Abort the ongoing ajax call (if any) if (ajax !== null) ajax.abort(); //Clear the timeout if (timeout !== null) clearTimeout(timeout); } }); //Set the global "ajax" variable to our request - don't use "var" here ajax = $.ajax( ... success: function(data) { // Do NOT use "var" here, as we're referencing the global variable timeout = setTimeout(update, 3000); } ... ); Alternatively, as a quick fix, just add a beforeSend anonymous functio

Categories : Jquery

multiple ajax calls using only javascript
It is, but you need a different "xmlhttp" handler for each request you make. Setup a new xmlhttp object and make a second request with the new object. My suggestion is to break out the part with you initializing the xmlhttp object, into a standalone function, and use it to create a few instances of those objects. However I must advise against such an approach. It is better to use a library for ajax requests.

Categories : Javascript

How to do multiple ajax calls and update the ui after each one
You'll get problems because you're trying to use i inside the callbacks, but by the time the callbacks are invoked i no longer has its original value. You also shouldn't use for ... in on array - only on objects. Instead of using any sort of for loop, I suggest the following, where each successive AJAX call is triggered on completion of the previous one: $.ajax(...).done(function(data) { var all = data.records; (function next() { var record = all.shift(); if (record) { $.post(...).done(next, function(res) { // process inner result // update UI, etc ... }); } })(); // invoke immediately }); Note that I've used "deferred" syntax instead of passing success: handlers in the

Categories : Jquery

multiple ajax calls jquery mvc
try this with jquery deferred: buildJQs: function () { var deferreds = [], deferred; $(".emailgraphs").each(function () { deferred = YAHOO.Report.Print("Email", $(this).attr("responsefield"), $(this).attr("id"), $(this).attr("metricid")); deferreds.push(deferred); }); $.when.apply(null, deferreds).done(function() { alert('all done'); }); }, Print: function (name, graphid, divid, metricid) { try { return $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: m_oReport.ds, //async: false, <- remove, this is a problem timeout: 300, data: JSON.stringify(m_oReport.printp(name, graphid, metricid)),

Categories : Jquery

Altering the URL on all ajax-calls from ExtJS
Ext.Ajax has a beforequest event that fires before any request happens: Ext.Ajax.on('beforerequest', function(conn, options, eOpts) { console.log('The options parameter contains the options'); console.log(' going to the request method'); });

Categories : Javascript

jQuery-How to call multiple ajax calls in one ajax call
Not possible in most cases Each ajax call involves the browser sending information to a server at a particular URL. If you reduced the browser code from two ajax calls to one ajax call, the server would receive less information, the browser would not receive some information it is getting now, and/or the server would perform fewer operations. If you control the server code, you might be able to change the server code to be able to do both operations in one step. Only then could you change the browser code.

Categories : Jquery

In AngularJS, how do I define a route which calls a specific method on a controller?
For AngularJS, remember it is client side, so the url resource doesn't have to directly related to the CRUD operation. I would recommend thinking of the url route as the view, not the operation. For example, I would use these: /items (show a list of the items) /items/edit/:itemId (show edit item form) I would not use these: /items/add (show add item form) /items/del/:itemId (Delete item) The reason I would not use the urls above client side is that what would you display for a /items/add resource? It would probably be the /items list right? Same goes for the /items/del/:itemId I would make two controllers. One that is an Items controller (i.e. a list of items) and an Item controller (i.e. a single item). Both should defer their functionality to a central service that manage

Categories : Javascript

In AngularJS, how to stop ongoing $http calls on query change
You should use version 1.1.5, which has the ability to cancel $http requests: https://github.com/angular/angular.js/blob/master/CHANGELOG.md // set up a dummy canceler var canceler = $q.defer(); // use it as a timeout canceler for the request $http({method: 'GET', url: '/some', timeout: canceler.promise}).success( function (data) { alert("this won't be displayed on cancel"); } ).error( function (data) { alert("this will be displayed on cancel"); } ) // now, cancel it (before it may come back with data) $rootScope.$apply(function() { canceler.resolve(); }); you can use the same canceler for all the requests, and resolve it just before starting the new set.

Categories : Http

Use response of 2 different AJAX calls (in their own functions) in a third function
Use the promises being returned by $.ajax. var p1 = jQuery.ajax({url:'http://tinyurl.com/api-create.php?url=http://xxxxxxxxxxx/', dataType:'script'}) var p2 = jQuery.ajax({url:'https://xxxxxx.com/names?user=random', dataType:'jsonp'}) $.when(p1, p2).then(function (response, data) { welcomemsg(response[0], data[0]); }); function welcomemsg(response, data){ jQuery.ajax({ url:'https://xxxxx.com/posts?walmessage=Hello ' + data.name + ' your post has been posted '+ response.id , dataType:'script', success:function(){ } }); }

Categories : Javascript

how to wait for all ajax calls to be done before testing with jasmine
To solve this problem, I used synchronous Ajax Requests, so that the code execution of the Jasmine Block only starts after all the documents are loaded. Here's my code at the beginning of the file (I assume that you want to store the files inside an array named fileLoaded. window.fileLoaded=[] DocUtils.loadDoc= function(path) { xhrDoc = new XMLHttpRequest(); xhrDoc.open('GET', path, false); //This line makes the call asynchronous (the false) xhrDoc.onreadystatechange = function(e) { if (this.readyState === 4) { if (this.status === 200) { window.fileLoaded[path]=this.response; } else { console.log('error loading doc'); if (callback != null) {

Categories : Javascript

One click generates multiple ajax calls
It is because you are registering the confirm callback handler inside the delete button click handler. So when you click on the delete button first time the handler is registered once - so the ajax request is sent once. When you click on the delete button second time one more confirm handler is registered, now we have two confirm handlers registered. it should be $('.delete').on('click', function(e) { e.preventDefault(); var $li = $(this).parents('li'), $url = $(this).attr('href'); $('#delete_confirm').modal('show'); }); $('#delete_confirm').find('button.btn-danger').click(function() { $.post($url, function(result) { $('#delete_confirm').modal('hide'); $li.remove(); }); });

Categories : Javascript

Remove class of parents after ajax calls
Maybe i don't understand your queston but with this : var divMiddleLayer = ("divBottomLayer").parent(); var divTopLayer = ("divMiddleLayer").parent(); divMiddleLayer.removeClass("rotate"); divTopLayer.removeClass("rotate");

Categories : CSS



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.