I have made admin panel where setup notification alerts using ajax. It is working fine, but after few minutes than it starts to freeze the browser. Any idea what I am doing wrong, as it is my first Ajax project.
Following are codes which I am using, I used setInterval in a function which is called by body onload event.
<html>
<body onload="process()">
<-- Some notification divs to be replaced by javascript -->
</body>
<html>
JavaScript
<script>
var xmlHttp = createXmlHttpRequestObject();
function process() {
setInterval('process()', 10000);
if (xmlHttp) {
try {
xmlHttp.open("GET", "response.json", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
} catch (e) {
console.log("Can't connect to server:\n" + e.toString())
};
}
}
function handleRequestStateChange() {
if (xmlHttp.readyState == 4) {
{
if (xmlHttp.status == 200) {
try {
handleServerResponse();
} catch (e) {}
} else {
console.log("There was a problem retrieving the data:\n" + xmlHttp.statusText);
}
}
}
}
function handleServerResponse() {
responseJson = JSON.parse(xmlHttp.responseText);
for (var i = 0; i < responseJson.newbooking.length; i++) {
// html += "<li><a href='admin_user.php?id=" + + "'><div class='desc'>" + responseJson.users[i].first_name + ", " +responseJson.users[i].last_name + " joined</div></a></li>";
bookinghtml += "<li><a href='makeinvoice.php?bookingid=" + responseJson.newbooking[i].booking_id + "'><span class='subject'><span class='from'>" + responseJson.newbooking[i].company_name + " </span><span class='time'> " + responseJson.newbooking[i].user_name + " </span></span>";
bookinghtml += "<span class='message'> from " + responseJson.newbooking[i].start_date + ", " + responseJson.newbooking[i].batches + " " + responseJson.newbooking[i].campaign + "</span></a></li>";
}
myDiv = document.getElementById("bookinginfo");
myDiv.innerHTML = bookinghtml;
}
Every time you make a request, you tell it to make a request every 10 seconds.
So onload, you make a request and start a timer.
10 seconds later you make another request and start another timer.
10 seconds later you make two requests, each of which starts another timer.
10 seconds later you make four requests, each of which starts another timer.
and so on.
It starts freezing, because it eventually is making trying to make requests faster then the computer can handle.
Use setTimeout, not setInterval.
(Also, you should pass a function, not a string: setTimeout(process, 10000));
Related
I have this javascript code that is meant to run inside the google chrome console. It constantly checks a json formatted response. If anywhere in the response BestPrice equals max_price then it will purchase it using some API. The problem I am having is about 10 seconds after running it I get 'ERR_INSUFFICIENT_RESOURCES'.
I suppose it is from too many requests? I need it to loop through as fast as possible, so if it can't be instant, is there a certain request limit?
Code:
function snipebot(page, max_page, max_price){
$.getJSON('http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&LegendExpanded=true&Category=2&PageNumber=' + page, function(data){
$.each(data, function(index, item){
if (item['BestPrice'] <= max_price){
$.get('http://www.roblox.com/Item.aspx?id=' + item['AssetId'], function(data){
var purchaseData = $($(data).find(".PurchaseButton")[0]).data();
if (purchaseData['expectedPrice'] <= item['BestPrice']){
$.post('/API/Item.ashx?rqtype=purchase&productID=' + purchaseData['productId'] + '&expectedCurrency=1&expectedPrice=' + purchaseData['expectedPrice'] + '&expectedSellerId=' + purchaseData['expectedSellerId'] + '&userAssetID=' + purchaseData['userassetId'], function(){
console.log('[' + item['BestPrice'] + '] #' + new Date().toTimeString())
});
} else {
console.log("Detected purchase.");
}
});
};
setTimeout(function(){
snipebot(page + 1 > max_page ? 1 : page + 1, max_page, max_price);
},100);
console.log("!checked");
});
});
};
snipebot(1, 4, 50);
When you call snipebot, it makes a request, and looking at the URL you're using, it gets an array back. Then for each item in the array, you are spawning another snipebot call. Each of those calls would in turn spawn more snipebot calls and so on. So, yeah, the ERR_INSUFFICIENT_RESOURCES error isn't really surprising.
Sorry if this topic already exists, but I couldn't find the solution. I have some calculations processed on server side. These calculations consists of several steps. I would like a response for each executed step. For instance, there are 5 steps in a task, and server must send me 5 responses:
Step 1 is executed
Step 2 is executed
Step 3 is executed
...etc
I read a lot of forums and blogs, but I can't solve this problem. In my case I think it is better to use long polling in comet. I wrote a simple example of my task (posted below); it doesn't work. This task has button which starts the counter (from 1 to 11 with sleep 1 sec), then Ajax sends a requests. The server must give the accumulated text ($q_msg), clear this variable, and continue to accumulate another counts. But instead of this, server accumulates everything without any responses and at the end response all in an answer. So, where is my fault? Please, assist me.
HTML:
<script type="text/javascript">
var request;
function createXMLRequest() {
request = new XMLHttpRequest();
return request;
}
//start counter
function comet_btnStart() {
document.getElementById('count1').innerHTML = "";
createXMLRequest();
var param = "btnStart=pusk";
request.open("GET", "counter.php?" + param, true);
request.onreadystatechange = comet_response;
request.send(null);
}
//get values
var q = "";
function comet() {
createXMLRequest();
var param = "q=" + q;
request.open("GET", "counter.php?" + param, true);
request.onreadystatechange = comet_response;
request.send(null);
}
function comet_response() {
if (request.readyState === 4)
{
if (request.status === 200)
{
if (request.responseText !== null)
{
var text = request.responseText;
if (text === "end") document.getElementById('count1').innerHTML += "<br/>Task is executed";
else
{
var result = text.split(",");
q = result[result.length-1];
document.getElementById('count1').innerHTML += "<br/>" + request.responseText;
setTimeout(comet, 2000);
}
}
else document.getElementById('count1').innerHTML += "<br/>No response";
}
else document.getElementById('count1').innerHTML += "<br/>Invalid connection";
}
}
</script>
</head>
<body>
<div>
Click button to start counter: <input type="button" value="Начать" name="btnStart" id="btnStart" onclick="comet_btnStart()" /><br/><br/>
Counts:<br/> <span id='count1' style='color: #246499; font-weight: bold'></span>
</div>
</body>
PHP:
<?php
if (isset($_GET['btnStart']))
{
$q_msg = "";
$q = 0;
logic::counter();
echo $q_msg;
$q_msg = "";
}
if (isset($_GET['q']))
{
$lastq = $_GET['q'];
global $q;
if ($lastq < $q)
{
echo $q_msg;
$q_msg = "";
}
else echo "end";
}
class logic
{
static function counter()
{
global $q;
while ($q <= 10)
{
sleep(1);
$q++;
global $q_msg;
if (strlen($q_msg) > 0) $q_msg .= ", " . $q;
else $q_msg = $q;
//just for debugging
echo $q_msg; //why server doesn't send data???
}
}
}
$msc=microtime(true);
//executing code
$msc=microtime(true)-$msc;
echo $msc.' seconds'; // in seconds
echo ($msc*1000).' milliseconds'; // in millseconds
i dont know if this is what you are looking for. But if i understsand correct this is what you are looking for. You can read more here How to get the execution time of a MySQL query from PHP?
Credit to Christian
I have an MVC4 Web API application where i have my Api Controller and Code-First EF5 database and some JavaScript functions for the functionality of my app including my Ajax Calls for my Web Api Service.I did the project on MVC because i was having trouble installing Cordova in VS2012, so i have decided to use Eclipse/Android Phonegap platform.Is there a way where i can call my web api service and be able to retrieve my database data designed EF5(MVC4) in my Android Phonegap application without having to start from the beginning the same thing again.I know phonegap is basically Html(JavaScript and Css) but i am having trouble calling my service using the same HTML markup that i used MVC4.I am a beginner please let me know if what i am doing is possible and if not please do show me the light of how i can go about this. T*his is my Html code*
<script type="text/javascript" charset="utf-8" src="phonegap-2.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="barcodescanner.js"></script>
<script type="text/javascript" language="javascript" src="http://api.afrigis.co.za/loadjsapi/?key=...&version=2.6">
</script>
<script type="text/javascript" language="javascript">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
//initialize watchID Variable
var watchID = null;
// device APIs are available
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = { timeout: 30000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
//declare a global map object
var agmap = null;
// declare zoom control of map
var zoomCtrl = null;
function initAGMap() {
agmap = new AGMap(document.getElementById("MapPanel"));
//TODO: must retrieve coords by device location not hard corded.
agmap.centreAndScale(new AGCoord(-25.7482681540537, 28.225935184269), 5); // zoom level 5 heres
// making zoom controls for map
var ctrlPos = new AGControlPosition(new AGPoint(10, 10), AGAnchor.TOP_LEFT);
zoomCtrl = new AGZoomControl(1);
agmap.addControl(zoomCtrl, ctrlPos);
}
function removeZoomCtrl()
{
zoomCtrl.remove();
}
//function search() {
// var lat = $('#latitude').val();
// var long = $('#longitude').val();
// $.ajax({
// url: "api/Attractions/?longitude=" + long + "&latitude=" + lat,
// type: "GET",
// success: function (data) {
// if (data == null) {
// $('#attractionName').html("No attractions to search");
// }
// else {
// $('#attractionName').html("You should visit " + data.Name);
// displayMap(data.Location.Geography.WellKnownText, data.Name);
// }
// }
// });
//}
//function GetCoordinate() {
//todo: get details from cordova, currently mocking up results
//return { latitude: -25.5, longitude: 28.5 };
}
function ShowCoordinate(coords) {
agmap.centreAndScale(new AGCoord(coords.latitude, coords.longitude), 5); // zoom level 5 here
var coord = new AGCoord(coords.latitude, coords.longitude);
var oMarker = new AGMarker(coord);
agmap.addOverlay(oMarker);
oMarker.show();
//todo: create a list of places found and display with marker on AfriGIS Map.
}
function ScanProduct()
{
//todo retrieve id from cordova as mockup
//This is mockup barcode
//return "1234";
//sample code using cordova barcodescanner plugin
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
//Callback function if barcodedont exist
function (error) {
alert("Scanning failed: " + error);
});
}
//Function to display Success or error in encoding.
function encode(type, data) {
window.plugins.barcodeScanner.encode(type, data, function(result) {
alert("encode success: " + result);
}, function(error) {
alert("encoding failed: " + error);
});}
function GetProductDetails(barcodeId,coords)
{
//Ajax Call to my web Api service
$.getJSON("api/products/?barcodeId=" + barcodeId + "&latitude=" + coords.latitude + "&longitude=" + coords.longitude)
.done(function (data) {
$('#result').append(data.message)
console.log(data)
var list = $("#result").append('<ul></ul>').find('ul');
$.each(data.results, function (i, item)
{
if (data.results == null) {
$('#result').append(data.message)
}
else {
list.append('<li>ShopName :' + item.retailerName + '</li>');
list.append('<li>Name : ' + item.productName + '</li>');
list.append('<li>Rand :' + item.price + '</li>');
list.append('<li>Distance in Km :' + item.Distance + '</li>');
//Another Solution
//var ul = $("<ul></ul>")
//ul.append("<li> Rand" + data.results.productName + "</li>");
//ul.append("<li> Rand" + data.results.Retailer.Name + "</li>");
//ul.append("<li> Rand" + data.results.price + "</li>");
//ul.append("<li> Rand" + data.results.Distance + "</li>");
//$("#result").append(ul);
}
});
$("#result").append(ul);
});
}
function ShowProductDetails()
{
//todo: display product details
//return productdetails.barcodeId + productdetails.retailerName + ': R' + productdetails.Price + productdetails.Distance;
}
//loading javascript api
$(function () {
initAGMap();
var coord = GetCoordinate();
ShowCoordinate(coord);
var barcodeId = ScanProduct();
var productdetails = GetProductDetails(barcodeId, coord);
ShowProductDetails(productdetails);
});
</script>
It looks like you're on the right track. The obvious error right now is that it's using a relative URL (api/products/?barcodeId=) to call the Web API. Because the HTML is no longer hosted on the same server as the Web API (even though you might be running them both on your local machine still), this won't work anymore. You need to call the service with an absolute URL (for example, http://localhost:8888/api/products/?barcodeId=).
Where is your Web API hosted right now and how are you running the Cordova code? If the Web API is up and running on your local machine and your Cordova app is running on an emulator on the same machine, you should be able to call the service by supplying its full localhost path.
If it still doesn't work, you'll need to somehow debug the code and see what the errors are.
I've got a JavaScript function that I want to report an alert message to the users if it successfully updates the database, or if it has an error.
In the main X.JSP file I have:
function startRequest(pChange)
{
//alert("startRequest");
createXmlHttpRequest();
//alert("sending message");
//var u1=document.f1.user.value;
//alert("Running startRequest for: " + pChange.id);
//xmlHttp.open("GET","updateEntry.jsp&pID=pChange.id&pStatus=pChange.status&pAddress=pChange.address&pDate=pChange.date&pNotes=pChange.note&pAssigned=pChange.assigned" ,true)
xmlHttp.open("GET","updateEntry.jsp?pID=" + pChange.id + "&pAddress=" +pChange.address + "&pStatus=" + pChange.status +"&pNote=" + pChange.notes +"&pAssigned=" +pChange.assigned ,true)
//alert(xmlHttp.responseText);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}
function handleStateChange()
{
//alert("handleStateChange");
var message = xmlHttp.responseText;
alert("Return Code:" + message);
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
}
}
else
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
}
I then run a method in updateEntry.jsp that does a number of things, but of interest is this section:
if(nId.equals("NMI")||nId.equals("MI")||nId.equals("NI")||nId.equals("SA")||nId.equals("S"))
{
org.hibernate.Query query2 = session2.createQuery("update Leads set Status = :nstatus where Id = :nid");
query2.setParameter("nid", nId);
query2.setParameter("nstatus", nstatus);
query2.executeUpdate();
out.println("Update successfully with: " + nstatus);
// Actual contact insertion will happen at this step
session2.flush();
session2.close();
}
else
{
out.println("Status must be: NMI, MI, NI, SA or S");
}
My understanding is that this should only create a single alert, if the function completes successfully. Instead it creates like 9 alerts all of which are blank. What am I doing wrong? I'm seeing both the "Return Code: " message and a blank " " message, (two different sections of code) but both output blank message variables.
If the readystate is not 4, it does not mean it is an error. Ajax has multiple states that inform the clientside about what is happening. Your code says that those connection states are all errors.
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
} <-- your else should most likely be up here
}
else <-- this is incorrect
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
Read the document at MDN - Ajax Getting Started
I wrote a Flickr search engine that makes a call to either a public feed or a FlickrApi depending on a selected drop down box.
examples of the JSONP function calls that are returned:
a) jsonFlickrApi({"photos":{"page":1, "pages":201, "perpage":100, "total":"20042", "photo":[{"id":"5101738723"...
b) jsonFlickrFeed({ "title": "Recent Uploads tagged red","link": "http://www.flickr.com/photos/tags/red/","description": "", ....
the strange thing is that in my local install (xampp) both work fine and i get images back BUT when i host the exact same code on the above domain then the jsonFlickrApi doesn't work. What i notice (by looking at Firebug) is that for the jsonFlickrApi the response Header says Connection close
Also, Firebug doesn't show me a Response tab when i submit a request to the jsonFlickrApi
here is the code:
function makeCall(uri)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", "jsonget.php?url="+uri, true);
xmlhttp.send();
}
function jsonFlickrApi(response)
{
var data= response.photos.photo ;
var output = "";
output += "<img src=http://farm" + data[4].farm + ".static.flickr.com/" + data[1].server + "/" + data[4].id + "_" + data[4].secret + ".jpg>";
document.getElementById("cell-0").innerHTML = output ;
}
//Public Feed
function jsonFlickrFeed(response)
{
var data= response.items[0].media.m ;
alert(data);
var output = "";
output += "<img src=" + data+ ">";
document.getElementById("cell-0").innerHTML = output ;
}
function callback()
{
//console.log("Ready State: " + xmlhttp.readyState + "\nStatus" + xmlhttp.status);
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var jsonResponse = xmlhttp.responseText;
jsonResponse = eval(jsonResponse);
}
}
examples of calls:
a)
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json×tamp=1339189838017
b)
http://api.flickr.com/services/feeds/photos_public.gne?tags=red&format=json×tamp=1339190039407
Question: why does my connection close? why is it working on localhost and not on the actual domain?
Looking at the HTTP response headers of
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json×tamp=1339189838017
I get a 302 with location
http://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json×tamp=1339189838017
So, what flicker wants to tell you is "use www.flicker.com instead of flicker.com!". With this URL I get content.