CasperJS with Ajax request - javascript

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.

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.

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.

Where or where to refresh the view?

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

Run (JS) function if server responded something specific

On one of my pages I have "tracking.php" that makes a request to another server, and if tracking is sucessful in Firebug Net panel I see the response trackingFinished();
Is there an easy way (built-in function) to accomplish something like this:
If ("tracking.php" responded "trackingFinished();") { *redirect*... }
Javascript? PHP? Anything?
The thing is, this "tracking.php" also creates browser and flash cookies (and then responds with trackingfinished(); when they're created). I had a JS that did something like this:
If ("MyCookie" is created) { *redirect*... }
It worked, but if you had MyCookie in your browser from before, it just redirected before "track.php" had the time to create new cookies, so old cookies didn't get overwritten (which I'm trying to accomplish) before the redirection...
The solution I have in mind is to redirect after trackingFinished(); was responded...
I think the better form in javascript to make request from one page to another, without leaving the first is with the ajax method, and this one jQuery make it so easy, you only have to use the ajax function, and pass a little parameters:
$.post(url, {parameter1: parameter1value, param2: param2value})
And you can concatenate some actions:
$.post().done(function(){}).fail(function(){})
And isntead of the ajax, you can use the $.post that is more easy, and use the done and fail method to evaluate the succes of the information recived
As mentioned above, AJAX is the best way to communicate between pages like this. Here's an example of an AJAX request to your track.php page. It uses the success function to see if track.php returned 'trackingFinished();'. If it did then it redirects the page 'redirect.php':
$.ajax({
url: "track.php",
dataType: "text",
success: function(data){
if(data === 'trackingFinished();'){
document.location = 'redirect.php';
}
}
});
The example uses JQuery.

Getting jQuery autocomplete to run on change

I'm trying to get jQuery autocomplete to work, but I can never get the source callback to run.
$(function() {
$('#function_name').autocomplete({
source: function(request, response) {
$.getJSON('/autocomplete', {
search: request
}, function(data) {
response(data.comp);
});
}
});
});
This is the code I currently have, but the callback for source is never run. What needs to happen to make it run? How can I get it to run every time the text box is updated?
EDIT: I updated jQuery and it now makes the requests correctly. However, now the $.getJSON callback is not being called. so it never runs
function(data) {
response(data.comp);
}
Any reason why is might be doing this?
The reason seems to be that flask (which I'm running my site off of) doesn't return a response when requested by this ajax, but does if you just visit the page. I don't really know what's going on with that, but I guess the code is correct.

Categories

Resources