I have a form which submits an AJAX request to one of my controllers which uploads a file using PHP's curl. I want to show the user the status of that (PHP) upload, so I store the PHP upload progress in a session variable. Meanwhile, the submission of the form also starts a setInterval() which makes a different AJAX request to controller which checks the session variable. My problem is that the second AJAX call seems to only fire once (instead of throughout the upload process) and so instead of progressively updating the progress, it just returns 100 at the end. What am I doing wrong?
Here's my code:
(note: I'm using the jQuery form plugin to assist with the file upload. It also adds some additional callbacks)
<script>
var check_progress = function() {
$.ajax(
{
url : '/media/upload_progress',
success : function(data) {
console.log(data);
},
async : false
}
);
var options = {
beforeSend : function() {
$("#MediaSubmitForm").hide();
$("#MediaSubmitForm").after('<img class="hula-hippo" src="/img/hippo-hula.gif" />');
t = setInterval( check_progress, 500 );
},
success : function(data){
$(".hula-hippo").hide();
$("#MediaSubmitForm").after("<h3>Upload complete!</h3><p>Do <strong>you</strong> want to <a href='#'>create a project</a> of your own?</p>");
window.clearInterval(t);
console.log(data);
}
};
$("#MediaSubmitForm").ajaxForm(options);
</script>
Use setTimeout();. setInterval() executes the code after the time specified and setTimeout() executes the code every time it reaches the specific time.
These question explain well of their difference :)
setTimeout or setInterval?
'setInterval' vs 'setTimeout'
setInterval & setTimeout?
setInterval and setTimeout
JavaScript setInterval and setTimeout
And a search of this on SO will solve your problem :)
It sounds like this is a PHP locking issue. See the first comment in the answer to this question:
jQuery: Making simultaneous ajax requests, is it possible?
Related
i need a a script that will refresh the functions:
$ping, $ms
every 30 seconds, with a timer shown,
i basicly got this script:
window.onload=function(){
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds;
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();
}
but it refreshes the whole page, not the functions i want it to refresh, so, any help will be appriciated, thanks!
EDIT:
I forgot to mention that the script has to loop infinatly
This here reloads the whole page:
window.location.reload();
Now what you seem to want to do is reload portions of the page, those portions having been generated by php functions. Unfortunately php is server side so that means you cant get the client browser to run php. Your server runs the php to generate stuff that browsers can understand. In a web browser open a page you made using php and choose to view source and you'll see what I mean.
Here's what you'll need to do:
Make your two functions ping and ms accessable via ajax
Instead of window.location.reload() do a call to jQuery.ajax. on success write to your page
Here's what I think would be the ideal way of dealing with this... I haven't seen the php side of your problem but anyway:
make a file called ping.php and put all your ping function code in there. ditto for ms
in your original php file that called those functions, make a div at each point where you wanted a function call. Give them appropriate ids. Eg: "ping_contents" and "ms_contents"
You can populate these with some initial data if you want.
In your js put in something like this:
jQuery.ajax(
{
url : url_of_ping_function,
data : {anything you need},
type : 'POST', //or 'GET'
dataType: 'html',
success : function(data)
{
document.getElementById("ping_contents").innerHTML = data;
}
});
do another one for the other function
What you want is AJAX, Asynchronous JavaScript and XML
You can use jQuery for that.
I can put an example here, but there is a lot of information to be found on the internet. In the past I wrote my own AJAX code, but since I started using jQuery, it's all a lot easier. Look at the jQuery link I provided. There is some usefull information. This example code might be the easiest to explain.
$.ajax({
url: "test.php"
}).done(function() {
alert("done");
});
A some moment, for example on a click on a button, the file test.php is executed. When it's done, a alert box with the text "done" is shown. That's the basic.
The function below grabs a php page, then reloads it every 5 seconds. The only thing coming from that roomdata.php page is a string with a color name (blue, yellow, etc.). I wanted to be able to use that name in the function modifyLight(color), but it's not letting me. I don't know why, but no matter what I tried, it's not treating the variable data as a string, even if I clarify it as one.
Any help is appreciated, thanks!
$(function(){
function loadData()
{
var data = load('roomdata.php');
modifyLight(data);
setTimeout(loadData, 5000); // makes it reload every 5 sec
}
loadData(); // start the process...
});
You are using async ajad calls. You need to configure your request to be sync.
$.ajax(URL, {async : false});
In that way the execution of the next line will be done until the ajax request Is finished.
EDIT
Your function should be like this:
$(function(){
function loadData() {
$.post("roomdata.php", function(result) {
modifyLight(result);
setTiemout(function() { loadData(); }, 5000);
}
}
loadData(); // start the process...
});
The problem with the way you were doing it is that $.load(); only loads something with Ajax and put the content on $('#yourdiv'); It does not return anything. You need an ajax request with something in the "success" event. In the code I gave you, $.post makes an ajax request via post to roomdata.php and then, once the ajax is finnished, it executes the function function(result) { ... }
I am creating a dynamic todo-list on a webpage. On the page you have a form for registering todo's and a table showing all the registrated todo's. The idea is that you register something you want done in a form, hit the submit button, and then the todo-list-table is automatically updated with the latest registered todo. My script manages all of this except for automatically updating the latest registered todo.
Here's my code:
$(document).ready( function() {
$('#todo_registration input[type="submit"]').click(function(evt){
evt.preventDefault();
var todo = $('#todo_registration input[name="daily_todo"]').val();
$('#todo_registration input[name="daily_todo"]').val(null);
$.when( registerTodo(todo) )
.then (
updateTodoDisplay()
);
});
});
function updateTodoDisplay() {
$.post("./daily_todo_display.php", null, replaceTbodyHTML);
}
function replaceTbodyHTML(data) {
$('#todo_display_table tbody').html(data);
}
function registerTodo(todo) {
var parameters = {
daily_todo: todo,
registration_button: 'clicked'
};
$.post("./daily_todo_registration.php", parameters); //, printRegistrationStatus);
}
I have checked that the script successfully registrates the todo in the database. The php-script that gets the updated todo-list also works. My problem, I think, is that the function updateTodoDisplay() doesn't wait for the AJAX call in registerTodo() to successfully complete before it runs. But I thought my use of #.when() was supposed to make updateTodoDisplay() wait.
I know making the AJAX call synchronous would probably fix my problem, but in my opinion that is a bad solution. I only want this one and only function to wait for the AJAX call to complete. Thus I want the rest of the webpage to function while these calls are made.
Any one know a fix for my problem? Thnx.
What you need is possible, but it looks like you have an error in your code.
Change the
.then (
updateTodoDisplay()
);
to
.then (function(){ updateTodoDisplay(); } );
or even
.then (updateTodoDisplay);
The problem is that when you are registering the callback, in your current code you are passing the result of executing updateTodoDisplay() instead of passing it as a function. That is why you get it executed right away.
You should $.post your data, AND when server-side updating is done, respond from server-side too - sending text/json/xml back to the UI. You save one (the second) request with that, you keep ajax asynchronous, you keep your code shorter/more-maintainable, and you get rid of this issue. =)
$.post("url/todo.php", params, function (data) {
// callback
// do UI update here
// "json" but you can say "xml" too
}, "json");
All you need to do is to figure out your server-side response.
jQuery.post()
Have a nice time implementing! =)
I have developed application for analysis data ie. domain name. When user provide 10 domains the following javascript code working fine but when user start analysis for 100 domains, below code does not work. I used javascript to redirect to another page after 3 second of form submit because processing assign task takes at least 1 minute time.
function submitForm(){
document.form1.button2.click();
var t=setTimeout("redir()",3000);
}
function redir(){
window.location.href = '<?php echo base_url();?>menu/showmsg';
}
When it is small task it is working fine but if there is big file to process javascript does not work, it wait till task completed from PHP side.
Is there any option in AJAX or JQUERY or any finest code in JavaScript?
A simple way is to use an iframe in the target page that runs the php. The page will load, and the iframe will wait for the php page. You can use some javascript to check for a change or flag in the iframe to move on with the process.
You can sent all requests asynchronously using for example jQuery.ajax( url [, settings] ).
Here the documentation: http://api.jquery.com/jQuery.ajax/
$.ajax({
url: '<?php echo base_url();?>menu/showmsg',
error: function(){
return true;
},
success: function(msg){
// make what do you want
}
});
I have some script that takes a form and sends it to php using jquery ajaxSubmit.
Server side must copy image from one location to another.
using this code copy($img_dir_file,$mini_dir_file); is ok if u have few images.
But if u have let's say 20+ images php works slowly, and responds to ajax before finishing it's job. Thus Ajax changes content to blank page , cause result is not ready.
If you refresh page a bit later, everything is ok cause php finishes his work.
So please tell me what should I do with this problem ?
script is something like this
$('#save_edited_article').live('click',function(){
$('#edited_article_form').ajaxSubmit({
success: function(responseimage){
$('#main_content').html(responseimage) } }); });
You could use a Promise which will inform the browser when the job is complete.
Check out the jqXHR Object as part of Ajax on JQuery - you could then change your main content when the jqxhr object ( which works as a Promise) is complete :
jqxhr.done(function(){ $('#main_content').html(responseimage); });
Edit
An example using your code could be:
$("#edited_article_form").submit(function() {
var jqxhr = $.post(
"foo.php",
$("#edited_article_form").serialize()
);
jqxhr.fail(function(){ alert("fail") });
jqxhr.done(function(responseimage){ $('#main_content').html(responseimage) });
});
Disclaimer : This was written on the fly and may not compile. It is for example purposes only
Have the AJAX call check to see if it's complete, if it's not, keep polling every few seconds until it's ready.
Updated jQuery and ajaxSubmit plugin and everything works nice.