Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX success function not being called

I am trying to get the success function from an AJAX call to fire. I know it is properly working because I am hitting my own API and I can see it is properly hitting the URL and the server is outputting a HTTP 200.

I figured it was because the server is outputting json, so I tried to account for that in the AJAX call, but still the success function will not work. Here is my code

ajax

$.ajax('http://localhost:3000/api/users/show/:id', {
  type: 'GET',
  dataType: 'json',
  contentType: "application/json",
  data: {
    id: 1
  },
  success: function(response) {
    return alert("Hey");
  }
});

api method

class UsersController < ApplicationController
    respond_to :json

    def show
        respond_with User.find(params[:id])
    end

end

server logs

Started GET "/api/users/show/:id?id=1" for 127.0.0.1 at 2013-08-02 20:36:42 -0700
Processing by MainController#index as JSON
  Parameters: {"id"=>"1", "path"=>"api/users/show/:id", "main"=>{}}
  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
  Rendered main/index.html.erb within layouts/application (0.6ms)
Completed 200 OK in 146ms (Views: 144.3ms | ActiveRecord: 0.5ms)
[2013-08-02 20:36:42] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
like image 854
user2495030 Avatar asked Aug 03 '13 03:08

user2495030


People also ask

When AJAX success is called?

AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.

How do I know if AJAX is working?

$. ajax({ url: "page. php", data: stuff, success: function(response){ console. log("success"); } });

Is AJAX successful deprecated?

Yes, it is deprecated in jQuery 1.8 onwards.


2 Answers

This happened with me also a long back, i solved this by changing the dataType to text, and manually converting that to json object through eval.

$.ajax('http://localhost:3000/api/users/show/:id', {
  type: 'GET',
  dataType: 'text',
  contentType: "application/json",
  data: {
    id: 1
  },
  success: function(response) {
    response = JSON.parse(response);
    return alert("Hey");
  }
});

May this work for you.

like image 129
Ashis Kumar Avatar answered Sep 24 '22 02:09

Ashis Kumar


I would add a complete function and check the text status. That should give the information you need to solve the problem.

complete: function(response, textStatus) {
    return alert("Hey: " + textStatus);
  }
like image 42
SemanticZen Avatar answered Sep 27 '22 02:09

SemanticZen