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.
Related
I would like to know how to wait on an socket.on call. I know that one could use the callbacks as described here, but this is not applicable in my case (at least I think it is not). The following is what I have:
index.html
...
socket.on('update_img', function(data) {
// Do something
});
scanner.addListener('scan', function(content) {
socket.emit('answer', content);
});
and then on the server:
...
client.emit('update_img', some_data);
...
client.on('answer', function(data) {
// do something with the answer
});
what basically happens, I send something to the frontend which then generates an image. At the same time, the library in the browser (instascan, thus scanner.addListener) waits for reading a QR-code and sends its content back to the server. So what I now need is that client.on('answer', ...); waits for this answer.
Is there any way to achieve this?
Essentially with client.on(...) you're adding the callback to that event, meaning that whenever that "anwser" event ist emitted from the client, it will be called on the server.
So if you make sure that socket.emit("anwser") on the client, is only called after you sent the image from the server, the server just has to listen to the "anwser" event and may assume that everything happened as expected.
Therefore you dont actually have to "wait" explicitly.
EDIT: Misunderstood your flow. Will update my answer
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.
How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php
Basically just looking to see if a particular txt file exists on the server, and if so, do further processing; however, I don't think my recursion is correct, so can someone offer a few pointers - here's what I have:
function fileExists(filename) {
$.ajax({
type: 'HEAD',
url: 'http://www.example.com/system/'+filename+'.txt',
success: function() {
// Further processing if file exists
},
error: function() {
// File does not exists, run through function again-
return arguments.callee(filename);
}
});
}
It's pretty basic, there's some processing before hand that actually creates the file; however the issue is it's FTP-ed up to our domain, which means timing can vary by a few seconds, so basically I just want it to recheck until it sees that the file exists. I'll modify it a little afterwards to control the stack, possibly setting a timeout of half a second or something, but I'm not that great with javascript, so I need a few pointers to make this recursive. Any help is GREATLY appreciated.
the issue is when you try to call fileExists again via arguments.callee(fileName), the scope of the error method isn't what you think it is.
Just call fileExists.
The other you are going to have is that if your server is quick, you are going to be firing a ton of requests. You probably want to wait some time between requests. So make error contain
setTimeout(function(){
console.log('trying again....'); // this won't work in IE, I *think*
fileExists(filename);
}, 1000); // try again in a second
Finally, you should realize that the error callback only gets invoked if the server returns a 500. The 500 code usually means there was an error on your server. If a file doesn't exist, you should probably return json to indicate the file doesn't exist, and handle that case in your success callback.
error: function() {
fileExists(filename);
}
I'm trying to a return the value of a given URL periodically using jQuery and setInterval. My code looks like:
$("form").submit(function() {
setInterval(function(){
$('#upload_progress').load('/upload_progress');
}, 5000);
});
This works perfectly in Firefox, but in chrome, the load() function never runs. I've treid using the $.ajax function as well with the same result.
Any ideas why this is only affecting Chrome (v11.0)?
Any help would be much appreciated!
For one, you are actually submitting the form. I'm pretty sure this places the browser in a state of "hey, i'm waiting on a redirect from the server." If you really want to poll and update the page, you probably need to do
$("form").submit(function(e) {
e.preventDefault();
// ...
}
Just as a start. In this context, it works for me. Here, I even made you a pretty little JSFiddle of it working: http://jsfiddle.net/plukevdh/sRe4k/. If you need redirection once complete, you might add more data to the callback (json or something) so that you can check to see if {status: 0-100 [percent], completed: true|false} and if completed or status >= 100, just change the window.location.
Is your code wrapped in a document ready check?
$(document).ready(function(){
// your code
});
If not, that may be why.