Read cross domain JSON response

20,478

Solution 1

I tried many tutorials including the answers above but had no luck. So I implemented it something like below

Form

 <form action="" onsubmit="submit_data(this, '1'); return false;">
   // some form fields
 </form>

Submit function for form

 <script>
   function submit_data(f, app_id){
     var data_string = $(f).serialize();
     $.ajax({
              url: "http://www.example.com/"+app_id+"/contact_us.js?"+data_string,
              dataType: "jsonp",
              crossDomain: true,
            });
   }

  function show_errors(jsonOb)
    {
      $("span.error").remove();
      $.each(jsonOb, function(key,val){
      $("#contact_us_form_"+key).after("<span class=error>"+val+"</span>")
    });
  }


 </script>

In my controller

   def create
    @application = Application.find params[:application_code]
    @errors = ContactUsForm.validate_fields(params, @application)
    @application.save_contact_us_form(params[:contact_us_form]) if @errors.blank?

    respond_to do |format|
      format.js #{render :json => {:status => 'success'}.to_json}
    end
  end

And finally in create.js.erb

<% if @errors.blank? %>
  window.location = "<%= @application.redirect_url  %>"
<% else %>
  var errors = replaceAll('<%= escape_javascript(@errors.to_json)%>', "&quot;", "'")
  var errors_json = eval('(' + errors + ')')
  show_errors(errors_json);
  function replaceAll(txt, replace, with_this) {
    return txt.replace(new RegExp(replace, 'g'),with_this);
  }
<% end %>

This way I called submit_form on form submit and called show_errors javascript function from server it self. And it works.. But still I would like to have comments if this is a worst solution?

Solution 2

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.

Solution 3

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);
      }
  });
Share:
20,478
Pravin
Author by

Pravin

Updated on March 23, 2020

Comments

  • Pravin
    Pravin about 4 years
         <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

  • Pravin
    Pravin about 13 years
    I had tried almost everything, but have no luck yet. Updated the question with efforts taken
  • T.J. Crowder
    T.J. Crowder about 13 years
    @Pravin: You're still putting () after the handler function name (success: handleSuccess()). As I said in the answer above, that calls your handleSuccess function immediately (before the ajax call) and assigns its return value to the success option to ajax. To refer to a function without calling it, you leave the () off (e.g., 'success: handleSuccess').