1

I have created an API which my AJAX post send values to it. AJAX does post and my laravel API does process the values. My issues is with the callback returning the value back to my AJAX post. My AJAX doesn't return the results in the success section when I do console log. I would like the results from my api to can use data to make my condition. At the moment, the console log doesn't even return a value. But in my chrome inspector under preview it shows the response from my API but not in the success section.

AJAX

var fname = "Joe";
var lname = "Test";
var processUrl = "api.example.com/z1";
$.ajax({
    type: 'POST',
    url: processUrl,
    data: {"name": fname,"surname": lname},
    dataType: 'json',
    success: function(res){
      console.log(res);
      if(res.length >= 1){
        $('#display').val(res.name);
      }
   }                            
});

PHP

public function checkResults(Request $request){
  $name = $request->name." ".$request->surname;

  $result = array();
  $result['name'] = [$name];

  return response()->json($result,201);
}
EternalHour
  • 8,308
  • 6
  • 38
  • 57
saiyan101
  • 610
  • 4
  • 12
  • 28

3 Answers3

0

I believe this is happening because you are sending status code 201 (Created), but you need to send status code 200 (OK) to trigger the success callback.

public function checkResults(Request $request){
  $name = $request->name." ".$request->surname;

  $result = array();
  $result['name'] = [$name];

  return response()->json($result,200);
}

I couldn't find it specifically in the jQuery docs, but this SO question addresses it.

EternalHour
  • 8,308
  • 6
  • 38
  • 57
0

For first it will be good to return with 200 OK response code (instead of 201).

Note: If you want to just immediately get the answer for your question only, you can see the last part of this answer (usage of "done/fail" construct instead of "success/error").

Additional:

There is many patterns which are used by Client(Frontend)<->API<->Server(Backend) developers. Approximately all APIs built without any 500 server error codes. But there is exists also many differences between APIs structures.

  1. One of them is to send response like this (this is the only one example of response):

    return response()->json([
        'success' => true, // true or false
        'message' => "Message about success!",
    ], 200); // 200, 401, 403, 404, 409, etc
    
  2. The other approach is to always sending 200 OK, but message can be also about error:

    return response()->json([
        'success' => false, // true or false
        'code' => 404,
        'message' => "Resource not found!",
    ], 200);
    

This kind of methods will written under try{}catch() and will return only 200, but that messages can imitated also as an error (as in example).

  1. The other (appropriate approach for you) is to change your Frontend AJAX functionality like this:

    $.ajax({
        type: 'POST',
        url: processUrl,
        data: {
            {{--_token: "{{ csrf_token() }}",--}}
            name: fname,
            surname: lname
        },
        dataType: 'json'
    }).done(function(res) {
        console.log(res);
        if(res.length >= 1) {
            $('#display').val(res.name);
        }
    }).fail(function(jqXHR, textStatus, errorThrown) {
        console.log("Error: " + textStatus);
    });
    

AJAX .done() function replaces method .success() which was deprecated in jQuery 1.8. This is an alternative construct for the success callback function (like before: "success: function(){...}").

AJAX .fail() function replaces method .error() which was deprecated in jQuery 1.8. This is an alternative construct for the complete callback function (like before: "error: function(){...}").

Note: .error() callback is called on HTTP errors, but also if JSON parsing on the response fails. This is what's probably happening if response code is 200/201 but you still are thrown to error callback.

boolfalse
  • 1,892
  • 2
  • 13
  • 14
0

Due to the asynchronous nature of Ajax calls, do not put them in the normal execution flow of your program. See this post to get more insight.

A quick fix for your problem is to include the ajax call in a function and call that function anytime you want to interact with the server asynchronously.

var fname = "Joe";
var lname = "Test";
var processUrl = "api.example.com/z1";
ajaxCall();

function ajaxCall() {
    $.ajax({
        type: 'POST',
        url: processUrl,
        data: {"name": fname,"surname": lname},
        dataType: 'json',
        success: function(res){
            console.log(res);
            if(res.length >= 1){
                $('#display').val(res.name);
            }
        },
        error: function() {     
            console.log('error');
        }           
    });
}

In addition, include an error function in the ajax call settings to handle cases where the ajax request fails. See this answer for alternative styles of doing this.

Udo E.
  • 2,665
  • 2
  • 21
  • 33