Randomtheories
Randomtheories

Reputation: 1290

Rails Server Callback to different domain

I want to do the following: The client (from a different domain, right now a JQuery-Script on my local computer) sends a Ajax-Post to the server, the server saves the result to the server and sends HTML/text back to the client who injects it into his HTML.

This is the Ajax-Call:

  var params = '{"comment": "Test", "creator": "Prof Frick", "name":     "Rainer", "url": "' + url + '"}';
  alert(params);
  $.ajax({
    type: "post",
    data: params,
    url: 'http://localhost:3000/pages/postjson/',
    success: function(data) {
      $('h1').html(data);
    }
  });
});

This is my route:

match '/pages/postjson/' => 'pages#postjson'

And this is the controller:

  def postjson
    parsed_json = ActiveSupport::JSON.decode(request.body.read) #
    @page = Page.where(:url => parsed_json["url"])
    new_obj = Page.new
    new_obj.name = parsed_json["name"]
    new_obj.creator = parsed_json["creator"]
    new_obj.url = parsed_json["url"]
    new_obj.comment = parsed_json["comment"]
    new_obj.save    
    render :json => @page[:name]
  end

I think my mistake is be quite basic and I really appreciate your help. My guess is that the mistake is either in

    @page = Page.where(:url => parsed_json["url"])

or in

    render :json => @page[:name]

because everything goes through, the json-data gets saved, the browser even alerts "Success", but the I want to post to just disappears.

Thanks for your advice. General coding tips also always appreciated!

Upvotes: 0

Views: 119

Answers (2)

Randomtheories
Randomtheories

Reputation: 1290

I finally solved the puzzle (for me):

After reading a lot I found this tutorial

I changed my controller to look similar to this:

respond_to do |format|
  format.js  { render :json => @page, :callback => params[:callback] }

And my JQuery-Function looks like this:

$(document).ready(function() {
  $.ajax({
    type: "GET",
    processData: false,
    contentType: "application/json",
    dataType: "jsonp",
    url: 'http://localhost:3000/pages/postjson.js?callback=?',
    success: function(data) {
      $('h1').html(data.name);
      alert("Name: "+ data['name']);
    }
  });
});

So happy that it is finally working :)

Upvotes: 1

Henrique Zambon
Henrique Zambon

Reputation: 1301

If you use render :json => something you will get a json object as response. What you need in this case is a render :js and a view that is called postjson.js.erb (assuming you're using ERB). In that view, you have to write the necessary JavaScript code to manipulate you HTML the way you want.

Upvotes: 0

Related Questions