Emre Emre - 9 months ago 42
Ajax Question

Rails - ajax response handling

I am sending data by using ajax call to 3rd party api to see if the card supports installment, then I get a response in the

action, I just do not know how to show response on the view.

ajax call;

type: "GET",
url: "/payments/new",
dataType: "json",
data: {card_digit},
success: function(data) {},
error: function(jqXHR) {}


def new
uri = URI.parse("https://...")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path, @headers)

req.body = @body.to_json
res = https.request(req)

puts "Response #{res.code} #{res.message}: #{res.body}"


Then here it returns res.body as json object, I would like to show this on the view I have tried to assign to a variable like @return then use it on the view but no chance, I tried with respond to block but could not manage to do it either.


Thank you for the answer!,
But now I get error
Encoding::UndefinedConversionError ("\xC4" from ASCII-8BIT to UTF-8)

res.body returns;


I wrote;

render json: { res_body: res.body }

in the success function

why would it happen?


I added

render json: { res_body: JSON.parse(res.body) }


If you use Ajax then you have to handle it in your JavaScript code to change your view.

Use this in your controller to pass the data to your Ajax call (replace the dummy hash):

render json: { test: "hello" }

In your success function of the ajax the JSON object I just rendered will be accessible in the data parameter of the function. Now I have to manipulate the view using javascript


To answer your edit I guess you have some characters which are more complicated to handle in your JSON like chinese, turkish, .... Maybe this might help you Encoding::UndefinedConversionError