Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in handling reponse from remote true Rails

I am using Rails remote true for ajax calls, but I have error in handling the response form controller.

What I am doing is I have placed a form in partial which I render in the view for the first time, and I have also given it a id in html options for form_for. I have also applied some jQuery on that form like on save and cancel button and one script for date picker on one of its field.

As I handle the response from server using format.js for rendering js file, in which I have placed the code as follows

if @vairable.save
 format.js { render 'some-file' }
else
 format.js { render 'something'}
end  

If the variable saved successfully I close the form properly, but if validations occur I render the form again by writing JavaScript code in js.erb file. I have problem in handing this response. The errors are displaying properly but when the form renders again with errors, the jQuery events applied to its fields and button, do not work. The jQuery events don't take place.

This problem only occurs when the model validations occurs and the validation rails are displayed with the new render form.

like image 553
Sanyam Jain Avatar asked Nov 03 '22 22:11

Sanyam Jain


1 Answers

You should wrap your response in a respond_to block like this:

respond_to do |format| 
  if @variable.save
    format.js { render 'some-file' }
  else
    format.js { render 'something'}
  end  
end

Edit: Your jQuery tags should be changed to $(document).on(...). Eg.

#change this:
$("#your-target-id").click(function(){
  alert("This doesn't work after your have submitted via ajax")
});

#to this:
$(document).on("click", "#your-target-id", function() {
  alert("This should work after ajax submission, and when errors are displayed");
});
like image 141
jokklan Avatar answered Dec 10 '22 03:12

jokklan