i am trying to display the data fetched from database in the loop and between loop i call the function and send ajax request its not working.Actually its displays the only if i used alert command. If i used alert then the browser display the div and then alert if i clicked ok then it displays the second div then again show alert.
Here is the js code
function like(divid,id,session) {
var orgnldiv=document.getElementById(divid);
var ndiv=document.createElement('DIV');
var idd=id+5000;
ndiv.id =idd;
ndiv.className="likeclass";
orgnldiv.appendChild(ndiv);
var dynamicdiv=document.getElementById(idd);
var span=document.createElement('span');
var spanid=idd+5000;
span.id=spanid;
span.className="spanclass";
dynamicdiv.appendChild(span);
var xmllhttp15;
if (window.XMLHttpRequest) {
xmlhttp15=new XMLHttpRequest();
} else {
xmlhttp15=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp15.onreadystatechange = function() {
if (xmlhttp15.readyState==4 && xmlhttp15.status==200) {
document.getElementById(spanid).innerHTML=xmlhttp15.responseText;
}
}
xmlhttp15.open("GET","spancount.php?postid="+id+"&userid="+session);
xmlhttp15.send();
// alert(spanid);
}
please suggest me what can be the reason of this problem my code is working well only if i use alert
The reason why your code works when you use alert is because whenever the alert function is called. The program flow is paused. In other words, your loop wont continue to make another Ajax call until you dismiss the alert.As a result, the request gets handled properly and the response data appears in the span div. that is why I had mentioned to make your calls synchronous instead.
So to answer the question you asked in the comment, Yes at times too many Ajax calls can be a problem. Let's say that the loops runs more than 15-20 times, that means 15-20 simultaneous requests. Now, think about the number of times the same request is being handled by the php script? Definitely a problem here!
Even with Jquery Ajax, the chances of the loop completing successfully is also 50-50 actually because it all boils down to the amount of requests being made , the bandwidth being used and how the request is being processed at the server.
One possible way to fix this problem is : Rather than constantly requesting small peices of data again and again from the server in the loop, Make one Ajax call and get the entire data as json. Then, parse the json and append data to the spans by using the particular span id to extract the relevant data from the json object.
You might have to do a little bit of tweaking in both the above javascript and spancount.php . But it will definitely Save you A LOT of bandwidth. You gotta consider the fact that more than one person could be using your site!!
Hope that cleared up things, all the best with your project :D
Related
Working on a platform, to enable auto-ticketing functionality. For which a REST API request is used for ticket creation. Unfortunately, there are 2 requests popping simultaneously, which results in creating duplicated tickets.
How to handle such case and send only one of these requests?
Tried adding the 2nd request in the response callback of the first, though this does not seem to work.
if (flag == 1){
logger.debug("Node-down alarm-Request raised - +sitn_id);
clearTimeout(mouseoverTimer);
mouseoverTimer = setTimeout(function(){
logger.debug("Inside Call back function - ");
//function call for ticket creation
incidentRequest(sitn_id,confUtil.config.mule_url);
}, 10);
You really should show more of the code that makes the request, though it seems as if you are doing some ajax inside your 'incidentRequest', so I will presume that (if that isn't what you are doing, then please, show your code....) - and since you tags say javascript and jquery - well, here goes...
To stop the 'double send' in an AJAX call, it is simple:
function incidentRequest(sitn_id,confUtil.config.mule_url){
// stop the double by clearing the cache
$.ajaxSetup({cache: false});
// continue on with the AJAX call
// presuming the url you want is confUtil.config.mule_url
// and the data you want to send is sitn_id
$.post(confUtil.config.mule_url, 'sitn_id=' + sitn_id, function (data) {
// do cool stuff
});
}
Hopefully that will help you get moving. If not, then we will need more code of what is going on around all this.
I have the code and it is not working on first click, but on the second click it is working.
$("#btnCopiar").on("click",function(){
var clipBoardObj = new ZeroClipboard($("#btnCopiar"), {
moviePath: "../thirdparty/ZeroClipboard.swf"
});;
// Create your data here to copy to the clipboard and assign to a variable name data
var data = "DATA IS COMING FROM SERVER OT TEXT INPUT";
clipBoardObj.on("copy", function (event) {
var clipboard = event.clipboardData;
clipboard.setData( "text/plain", data );
});
});
<button id="btnCopiar">Copiar</button>
Even if I have initialized the clipboard outside the click event, it is not working
I wonder if this has to with the synchronous way you have written the code.
Your line var data = ... implies that the variable data is receiving its information from a call to the server that only happens right at that moment. (I'm making some assumptions about code you have deleted in order to make the question more concise and understandable, though I could be wrong about that.) That data is going to take a little while to arrive. However, immediately after that line you are using the data variable in the clipBoardObj.on("copy", function(event) {... function. The first time you run that function, the data will not yet have arrived. However, some time will elapse before the user clicks the button a second time. When that happens, there may have been enough time for the first call to the server to have returned, and data will have some data. Note, however, that the second time you run that function, it will only be using the data from the first call to the server, which may or may not be acceptable.
I am working on a project for school and it's about jQuery, PHP, symfony and all that web stuff :). It is actually my first time using jQuery and even though I have already learned something, there are still many thing I dont know how to solve.
In this project, one of the things I am supposed to make is basically filtering some results. I have a database and when the site is loaded, all items from the database are displayed in a table. Then above the table, there is a text field. When I type in it, the items in the table are filtered as I type. But sometimes, when I write for example "HP", the jQuery first finishes the request for "HP" and displays the result and then it finished the request for "H" and so it overwrites the result of "HP" and this shouldnt happen. If I make the requests synchronous, it prevents me from writing in the text field when a request is being processed. How can I make it so that the requests are completed in the order they were called?
The jQuery code of this part of the project looks like this:
var oldTerm;
function filter() {
var term = $('#term').val();
//alert(term);
if(term != oldTerm) {
$.ajax({
url: url.replace('--', term).replace(/\/$/, '')
//musi bejt synchronni
}).done(function(data) {
$('#items_table tbody').html(data);
alert(term);
// udalost se musi registrovat po nacteni radku!
$('.edit_button').click(createForm);
});
oldTerm = term;
}
}
$(document).ready(function() {
oldTerm = null;
$('#term').keyup(filter);
});
I think your best shoot is to make a queue for the ajax call maybe use a lock too. You can also use this : Queue AJAX calls
I have a MySQL form with a drag 'n drop hot spot, and several image tags. The data field is simply a char(100) that stores a link to the uploaded image file. With each image tag I have a button to delete the image. It in turn calls a confirm dialog, and if confirmed calls a Javascript function to delete the image. The Javascript function calls a separate PHP file that executes the update to the MySQL table. What I would like to do is refresh the view once all this has been executed. I have searched all over Google, and this site and have tried numerous versions of everything claimed to work. But so far, I have found nothing. I don't want to use a meta tag because I found that that if you are attempting to upload an image invariably it would refresh before you can complete the upload.
As it is, everything works fine, except for the timing to execute a refresh. I'm assuming and logically it would seem that once the PHP update function has completed that that would be the time to execute a refresh. But so far, I haven't been able to get a Javascipt refresh function to work from an external PHP. It also seems that from the initial Javascipt function that it doesn't wait for the PHP to finish before calling a refresh from there. In other words, like these last few lines:
ajaxRequest.open("GET", "AjaxDeleteImage.php" + queryString, true);
ajaxRequest.send(null);
//window.location.reload(true);
Where you can see I commented out the reload. I tried it there, but it just killed everything. I would be happy to include more code if needed. Maybe my method is too convoluted and someone can give me a swift kick if needed.
AJAX calls are asynchronous so once the request goes out, the rest of the script carries on executing. This is generally a good thing otherwise your page will hang until the AJAX is done.
To carry out an action when the AJAX request is finished, you need to assign a callback function. This will be run when the AJAX is done. Or more accurately when the AJAX request state changes.
I lifted this from W3Schools:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//refresh page here or do other cool stuff
}
}
In your case you would change xmlhttp to ajaxRequest.
The onreadystatechange property expects a function and this function will be called whenever the state of the AJAX request changes. There are 5 different states, but the one you're interested in is 4 as this is the "I'm done!" state. The function above checks for this state and also checks the http status code returned from the server. If it is 200 life is good and you can then do what you need to do. The callback should be declared before calling .send().
You may also check for other status codes and react accordingly (say pop up an error if there is a 404 or 500 status code, or reset the page to a known good state so the user can try again).
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//refresh page here or do other cool stuff
}
elseif (xmlhttp.readyState==4 && xmlhttp.status==500)
{
//uh oh, something went wrong. Call Batman!
}
}
As an aside, libraries such as JQuery wrap up AJAX functionality into some very easy to use functions. A simple JQuery example:
$.get('myurl.php')
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
As you can see, you can perform your GET request and define all your handlers in one easy statement. If you only care about success, you can shorten it to just:
$.get('myurl.php', function(){
alert('success');
});
I want to retrieve the height and width of an image on a server by using an ajax post call to a php file which returns a double pipe delimited string 'width||height'
My javascript is correctly alerting that requested string from the php file so the info is now in my script but i cannot seem to access it outside the $.post function.
This works:
var getImagesize = function(sFilename)
{
$.post("getImagesize.php", { filename: sFilename, time: "2pm" },
function(data){
alert(data.split('||'));
});
}
But retrieving is a different matter:
// this line calls the function in a loop through images:
var aOrgdimensions = getImagesize($(this, x).attr('src')) ;
alert(aOrgdimension);
// the called function now looks like this:
var getImagesize = function(sFilename)
{
var aImagedims = new Array();
$.post("getImagesize.php", { filename: sFilename },
function(data){
aImagedims = data.split('||');
});
return "here it is" + aImagedims ;
}
Anyone able to tell me what i'm doing wrong?
You are misunderstanding the way that an AJAX call works. The first "A" in AJAX stands for asynchronous, which means that a request is made independent of the code thread you are running. That is the reason that callbacks are so big when it comes to AJAX, as you don't know when something is done until it is done. Your code, in the meantime, happily continues on.
In your code, you are trying to assign a variable, aOrgdimensions a value that you will not know until the request is done. There are two solutions to this:
Modify your logic to reconcile the concept of callbacks and perform your actions once the request is done with.
Less preferably, make your request synchronous. This means the code and page will "hang" at the point of the request and only proceed once it is over. This is done by adding async: false to the jQuery options.
Thanx for the Asynchronous explaination. I did not realize that, but at least now i know why my vars aren't available.
Edit: Figured it out. Used the callback function as suggested, and all is well. :D