Where or where to refresh the view? - javascript

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');
});

Related

How to handle multiple requests being sent in JavaScript?

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.

CasperJS with Ajax request

I'm having a lot of trouble understanding how to test a simple form that makes an AJAX request and either loads a new page or displays an error, depending on the response.
The scope of 'this' is changing after the request. Once the form is submitted 'this' refers to the XHR result of the query, not to the page, so no title found of course. My code:
casper.test.begin('Tester.assertField(): unfilled inputs', 3, function(test) {
casper.start('http://www.myste.com/roku/', function() {
this.fill('form[id="id-lookup-form"]', {
'code': 'chuck#norris.com'
}, true);
test.assertField('code', 'chuck#norris.com', 'Tester.assertField() works as expected with inputs');
});
casper.wait(5000, function() {
test.assertField(this.title, 'myste.com', 'Title correct after form input');
});
casper.run(function() {
test.done();
});
});
I can increase the wait as long as I like and it will still fail. I know it is remedial, forgive me, but I've been all over trying to find a solution. This is similar: Update whole page on Ajax request and maybe I'm out to lunch, but since the page is making an AJAX request, I don't want to have to duplicate the request-- I want to let the page make the request and then see what happens. We do a lot of AJAX requests like this, I don't want to be intercepting/rewriting/parsing them all for every page I need to test. Casperjs, how to only proceed after receiving response from an ajax call seems to also suggest this method (though perhaps function getSomethingFromMyServerViaAjax() is not sending the request, i can't tell.)
Thanks very much, this is kicking me.

Page redirect from external php file (in ajax call)

I have this Salesforce "Web-to-Lead" form that I'm working with (on an IIS server), and I got it validating properly in an Ajax call (using the roscripts.com ajax validation as a starting point... this uses the Mootools library to carry out its Ajax functions), as well as sending all of the validated data using cURL, however I want the form to redirect to a new page after validation succeeds. The Ajax call runs every time the Submit button is clicked and either displays errors on the page or runs whatever is included in the "else" section of the validation code.
The Ajax function:
window.addEvent('domready', function() {
$('registerForm').addEvent('submit', function(e) {
new Event(e).stop();
var log = $('log_res').empty().addClass('ajax-loading');
this.send({
update: log,
onComplete: function() {
log.removeClass('ajax-loading');
//adding a header redirect here works, but redirects every time ajax call runs, regardless if validation succeeds or not
}
});
});
});
The "action" php file function:
<?php
if (rule){ //validation errors }
else { //where all of the logic happens after validation succeeds
//cURL function
//redirect attempts:
header( 'Location: http://www.place.com'); // doesn 't work
echo '<meta http-equiv="refresh" content="2" ; url="http://www.place.com">'; //resets the form, but doesn't redirect to www.place.com
};
?>
I'm totally stumped here, I can't get this darn thing to redirect, no matter how hard I try. Any help would be greatly appreciated!
From what I can tell of MooTools AJAX, the onComplete handler will fire any time AJAX is finished -- even when there are errors. That may be fine for removing your loading message, but you'll probably want to use onSuccess for a successful handler and onFailure for a failed request. While your script doesn't appear to be using MooTools directly, this is how MooTools AJAX works.
See the "Ajax!" section on http://mootools.net/ for an example.

sending ajax request but not getting right result.Js

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

Understand Ajax XMLHttpRequest in details

I am new to Ajax, and to make things worse, also a Javascript noob, and I have posted the bellow code of a chat script, to retrieve text from db, in real time, and the code is working, but I need to understand what certain requests are all about.
<script>
function retrieve(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest(); }
else if(window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
else {
alert('Please update your browser to start chatting');
}
Simply, I understand the above is (I created it) just a function with global variable declared to be assigned whether XMLHttpRequest/ActiveXObject Object is declared depending if browser is IE6,7 and others if not throw in alert...
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("canvas").innerHTML = xmlhttp.responseText;
}
}
Similarly, the above I assume takes the onreadystatechange property of the Ajax API and checks for it's state, readyState & status which, if only they match 4 and 200 means, Ajax is working as wanted
t = setTimeout("retrieve()", 2000);
I know the setTimeout() is a bit like setInterval() function, which runs the function inside it, every 2 seconds, to check for new messages.
xmlhttp.open("GET", "getajax.php", true);
xmlhttp.send();
Now, the problem is with the above, I can almost understand that the .open method is supposed to get data from getajax.php even though, I have no idea of what true means in this instance, but as far as the xmlhttp.send(); I have absolutely no clue,
So, All I need is for you to explain to me what I have missed during my illaboration, and
what the last queries mean, just in brief.
}
retrieve();
</script>
<div id="canvas"></div>
xmlhttp.open("GET", "getajax.php", true);
xmlhttp.send();
true is what tells the request to be performed A -synchronously, which is the A in AJAX. Then finally .send() actually send the request.
Asynchronous requests are non-blocking meaning that the rest of your code wont wait for them to finish and return before continuing. That is why you sent event handlers before starting the request via xmlhttp.onreadystatechange. That way once the request is complete you have already told your script what to do with the returned information.
Hope this helps.
Edit Additionally I recommend using some sort of framework or library for javascript like jQuery. While it is good to learn some of the javascript core, something like jQuery will make your life much easier.
Simply, I understand the above is (I created it) just a function with global variable declared to be assigned
xmlhttp isn't a global. It's a local variable in the global function retrieve.
Similarly, the above I assume takes the onreadystatechange property of the Ajax API and checks for it's state
onreadystatechange is a property that accepts a function. That function is run when the value of readyState changes. That function is usually used to check the status of the request.
I know the setTimeout() is a bit like setInterval() function, which runs the function inside it, every 2 seconds, to check for new messages.
setTimeout is like setInterval in a sense that it runs a function at a later time. Unlike setInterval, it only runs the code once. Also, that's not the proper way of running a timer. Here's a post that explains how to properly use timers.
the .open method is supposed to get data from getajax.php even though, I have no idea of what true means in this instance, but as far as the xmlhttp.send(); I have absolutely no clue
The open builds your request by accepting:
The type of request (GET/POST)
The url where you want the request sent
The third argument determines if the request is asynchronous or not.
If set to false, this makes the request synchronous. The browser will freeze and wait for the response.
If true, the request us asynchronous. The browser will not freeze in waiting.
The default value is true, so you can omit it.
send is the actual function that ultimately sends the request to the server.
For further reading, I suggest you read MDN's section regarding AJAX.

Categories

Resources