0

I have a super simple JQuery ajax request below:

$.ajax("../ajax/data/items.json",
{ success: setContent, type: "GET", dataType: "json" });

function setContent(data, status, jqxhr) {

alert("Hello!");
}

The json loads on the page with a 200 response. The success function is set to setContent(). But the success function never runs and I cannot figure out why.

Questions:

  1. Is my understanding of how the success function works incorrect? Why doesn't the function setContent() run for a 200 response on the Json?

  2. Are the arguments for setContent() filled out behind the scenes by JQuery? Obviously I am not setting it anywhere in the code, but the video does not show adding arguments any place.

I am following Lynda.com's tutorial:

http://www.lynda.com/jQuery-tutorials/AJAX-made-simple/183382/368483-4.html

specifically the video AJAX made Simple.

1
  • 1
    As always, when you aren't getting the success handler called, install an error handler and see what it tells you the error is. Commented Oct 26, 2015 at 22:04

1 Answer 1

1

The issue is most likely that you aren't getting back valid JSON. If you specify the data type as JSON and it returns something else, the success handler will not get called.

There is nothing wrong with the syntax:

enter image description here

As you can see, the console.log fires if you don't specify the dataType, as it doesn't care if it is JSON or not. If you do specify, nothing gets logged.

$.ajax(window.location.href,
{ success: setContent, type: "GET", dataType: "json" });

function setContent(data, status, jqxhr) {

console.log("It worked!");
}

You can copy that into dev tools on this site and see what happens when you remove the dataType parameter.

Sign up to request clarification or add additional context in comments.

1 Comment

This seems like a likely possibility. It's a guess, but a likely possibility. The way to tell for sure is (as I've suggested in a comment) is for the OP to install an error handler for the Ajax call and see what the actual error is. If it's a JSON error that will show in the error handler.

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.