0

I need to send a polling AJAX request to the server and send some data (which I think I'll just pass in the url) to the server. I'll have a number of different resque background jobs running, and I want to check if each job has finished. I found a gem to do that (resque-status), but I'm unsure how to send the data back-and-forth between the javascript and the controller.

The first thing is how would I construct this polling AJAX request to the server? What would the syntax be? The next thing I'm unsure about is how would I send the status of the job back to the ajax request, and then send the AJAX request back again if not all of the jobs are finished? I'm assuming JSON would probably help here.

I'd really appreciate code examples (preferably using Ruby on Rails and JQuery.

1 Answer 1

1

Use a library like jquery

js:

$(document).ready(function(){
    $.ajax({
        method: "POST",
        url: "ajax.php",
        dataType: "json", //jquery will convert the json into an object
        data: { //data sent to server
            foo: "foo",
            bar: "bar"
        },
        success: function(data){ //callback function
            if(data["type"] == "success"){
                alert(data["msg"]);
            }else{
                alert("malformed response");
            }
        }
    });
});

php:

<?php
$obj = new stdClass();
$obj->type = "success";
$obj->msg = "foo: " . $_POST["foo"] . ", bar: " . $_POST["bar"];
echo json_encode($obj); //echo the object as json
?>
Sign up to request clarification or add additional context in comments.

6 Comments

where is the json data in the PHP being sent back to the ajax function? how does it know which AJAX function to send the json data to? Btw, I'm using RoR. If you know it, I'd prefer an example in that language framework.
echo json_encode($obj); is sending it back. It knows what to send back based on the parameters it got in the request.
but how does it know to send it back to that same AJAX function? Would you know how to send it back from inside a RoR controller?
ajax is just an http request from javascript. The php doesn't know anything about the client-side script. webdesignerdepot.com/2008/11/how-ajax-works
right right. so since it's all one request, the ajax request automatically receives the JSON data in the data variable in the success callback? I don't need to parse the JSON at all?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.