简体   繁体   中英

JQuery Ajax returning success with nonexistent url parameter

So I have this code in one of my Laravel's views: (there is no such url as "nonexistenturl", I just made it up)

<script type="text/javascript">
$(document).ready(function(){

  $('#btnAdd').click(function(){
    addToCart();
  });

  function addToCart(){
    $.ajax({
      method: "GET",
      url: "nonexistenturl",
      data: { msg: 'hi' },
      success: function(data){
        alert('success');
      }
    })
   }

});
</script>

And the alert message is showing, I don't understand why. Thanks for the help!

Edit 0: Now I tried the same code in another View and I get an error as it must be, but I don't know why it works in the other view yet.

Edit 1:

For some reason if I run the javascript code I posted from one specific view, the following code is being executed:

public function show($id)
{
  $recipe = \App\Recipe::find($id);

  return view('recipes.show')->with('recipe', $recipe);
}

The Laravel's route for this is:

Route::get('recipe/{id}', 'RecipesController@show');

So it's as if the ajax request was using another url, the one from the current view...

Edit 2

I feel so stupid now. As charlietfl suggested it was using the url "recipe/nonexistent". So all I have to do is use: url: "{{url('route')}}"

Thanks for your help everyone :)

This probably mean that Laravel is returning some type of web page, even if there is no data on it, it returning something would be considered a success. A good way to debug this would be to alert the data, and it if returns an object then alert data.responseText.

alert(data.responseText); 

It would also help to navigate the any fake urls you are making to see what Laravel returns on them. EDIT

Try specifying json as the return type, I believe it defaults to text.

$.ajax({
  method: "GET",
  url: "nonexistenturl",
  dataType: 'json',
  data: { msg: 'hi' },
  success: function(data){
    alert('success');
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM