0

This is a very trivial question, more of a curiosity..

How do you guys return data on a Jquery Ajax call? "Success" or "Fail", 0 or 1, something else?

Is there a better way to do it? What is the best practice?

public function ajaxCheckTask(){

    $task = Task::findOrFail(Input::get('id'));

    if($task->user_id == Auth::user()->id){
        $task->mark();
        return 'success'; 
    }

    return 'fail';

}
sigmaxf
  • 7,998
  • 15
  • 65
  • 125

2 Answers2

0

AJAX means **Asynchronous** JavaScript and XML. so you cannot return the success or failure since the request will be Asynchronous of what you are doing, but you can do an action on success or failure. I have given a code sample in javascript (SOURCE : w3schools. in case if you want to know more)

JAVASCRIPT

xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        // Do the success action
    }
    else{
        // Do the failure action
    }
}
xmlhttp.open("GET OR POST","URL TO CALL");
xmlhttp.send("DATA TO SEND");

JQUERY

$.ajax({
    url: URL, // URL to post the data
    method: 'post',// suitable http verb
    data: '', // values to be passed with the request 
    success: function(response) {
        // Do the success action
    },
    failure : function(response){
        // Do the failure action
    }
});
Cerlin
  • 6,622
  • 1
  • 20
  • 28
  • Please provide a useful answer with detail code. If you use any other jQuery AJAX method, such as $.get, $.getJSON, etc., you have to change it to $.ajax (since you can only pass configuration parameters to $.ajax) and provide variable status async: false; – Abin Abraham Oct 17 '14 at 07:24
  • i have addressed what the OP really asked for which is "whether you can return success or failure on ajax call". the answer for which is NO. if you are talking about Synchronous requests then it is called as SJAX not AJAX. The code which i have written is to make the OP understand the answer better. – Cerlin Oct 17 '14 at 07:32
0

This is how you call a success message that came from the backend.

$.ajax({
    url: URL,
    method: 'post',
    dataType: 'json',
    data: {"var":"val"}
    success: function(response) {
        alert(response);
    },
    failure : function(response){
        alert(response);
    }

});
aldesabido
  • 1,268
  • 2
  • 17
  • 38