Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read cross domain JSON response

     <script>
        $.ajaxSetup( {contentType: 'application/json'} );
        function submit_data(f){
          alert('submitting')
          var data_string = $(f).serialize();
          $.ajax({
                url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
                dataType: "jsonp",
                type : 'post',
                processData: false,
                crossDomain: true,
                contentType: "application/json",
                jsonp: false,
                jsonpcallback: result()
            });
        }

        function result(){
          alert('back in')
          alert(data)
        }
        function jsonp1300279694167(){
          alert('dhoom')
        }
      </script>

I have script above querying across domain and posting data within a form.
Everything seems to work fine. JSON response can be seen in the firebug console. I want to process the response and display status messages accordingly to the user. How should I achieve it?


UPDATE

I have tried as suggested by T.J. Crowder but have no luck yet. The modified code is as below

function submit_data(f){
  alert('submitting')
  var data_string = $(f).serialize();
  $.ajax({
            url: "http://localhost:3000/application/1/contact_us.json?"+data_string,
            dataType: "jsonp",
            crossDomain: true,
            success: handleSuccess()
        });
}



function handleSuccess(data) {
  alert("Call completed successfully");
  alert(data);
}

This does not accesses data and alerts undefined. If I try to pass it from success: handleSuccess() it errors and redirects with a http request.

I am getting response from a Ruby on Rails application. Here is the method I am hitting

def create
    errors = ContactUsForm.validate_fields(params)
    logger.info errors.inspect
    if errors.blank?
      respond_to do |format|
        format.json {render :json => {:status => 'success'}.to_json}
      end
    else
      respond_to do |format|
        format.json {render :json => {:status => 'failure', :errors => errors}.to_json}
      end
    end
  end

Is there any thing that I need to configure in my rails app

like image 512
Pravin Avatar asked Mar 16 '11 13:03

Pravin


2 Answers

You're close. You just use the success callback as usual (see the ajax docs), not a special one:

$.ajax({
    url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
    dataType: "jsonp",
    type : 'post',
    processData: false,
    crossDomain: true,
    contentType: "application/json",
    jsonp: false,
    success: function(data) {
        // Use data here
    }
});

Also, your code:

jsonpresponse: result()

...would call the result function and then use its return value for the jsonpresponse property of the ajax call. If you want to use a separate function, that's fine, but you don't include the (), so:

$.ajax({
    url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
    dataType: "jsonp",
    type : 'post',
    processData: false,
    crossDomain: true,
    contentType: "application/json",
    jsonp: false,
    success: result
});

function result(data) {
    // use `data` here
}

Also, I'm pretty sure you don't need/want the jsonp parameter if you use success, so:

$.ajax({
    url: "http://localhost:3000/application/1/contact_us.json?jsonpcallback=?"+data_string,
    dataType: "jsonp",
    type : 'post',
    processData: false,
    crossDomain: true,
    contentType: "application/json",
    success: result
});

function result(data) {
    // use `data` here
}

Finally: Are you sure you want to set contentType? That relates to the content being sent to the server, not the content being received from it. If you're really posting JSON-encoded data to the server, great, you're fine; but it looks like you're using jQuery's serialize function, which will not produce JSON (it produces a URL-encoded data string). So you probably want to remove contentType as well, both from the call and from the ajaxSetup call.

like image 82
T.J. Crowder Avatar answered Nov 04 '22 08:11

T.J. Crowder


I hope if you can try jQuery-JSONP
jQuery-JSONP How To

[Example]

$.getJSON('server-url/Handler.ashx/?Callback=DocumentReadStatus',
  {
      userID: vuserID,
      documentID: vdocumentID
  },
  function(result) {
      if (result.readStatus == '1') {
          alert("ACCEPTED");
      }
      else if (result.readStatus == '0') {
          alert("NOT ACCEPTED");
      }
      else {
          alert(result.readStatus);
      }
  });
like image 31
Ahmed Atia Avatar answered Nov 04 '22 07:11

Ahmed Atia