JavaScript AJAX & Rails Controller (back-and-forth) - javascript

I'm sending information back-and-forth between a Rails controller and a JS file.
I'm sending the form to the controller through JS (works)
$("#help-email-submit").ajaxSubmit({url: '/help/send_help_email', type: 'post' });
I'm able to catch the event in the controller (works)
def send_help_email
....
end
In the same JS file that sent the above request, how do I capture the JSON response (below)? (doesn't work)
def send_help_email
...
cst_str = #current_support_ticket.to_s
respond_to do |format|
format.json { render :json => cst_str }
end
end
In the JS file
var xmlhttp = new XMLHttpRequest();
alert(xmlhttp.responseText);
UPDATE
I noticed a JS error that is preventing the success: function from executing:
Error
TypeError: 'undefined' is not a function (evaluating '$("#help-email- form").ajaxSubmit({url: '/help/send_help_email', type: 'post', complete: handlerResponse })')
This is the line that is triggering the error
$("#help-email-form").ajaxSubmit({url: '/help/send_help_email', type: 'post', complete: handlerResponse })
This is complete block
var handlerResponse = function(data) {
alert(data);
};
$('#help-email-submit').live('click', function(e) {
$('#sender-email-wrapper').fadeOut('fast', function() {
$("#help-email-sent").fadeIn('slow');
});
$("#help-email-form").ajaxSubmit({url: '/help/send_help_email', type: 'post', complete: handlerResponse })
e.preventDefault();
});

According to ajaxSubmit documentation, it accepts the same options that the jQuery.ajax method. So, to get the response, you can pass the complete callback to the call:
var handleResponse = function(data) {
// Use response here
};
$("#help-email-submit").ajaxSubmit({url: '/help/send_help_email', type: 'post', complete: handleResponse });
Depending on the version of jQuery that you are using, you can also pass the callback through the complete method on the return value from jQuery.ajax:
$("#help-email-submit").ajaxSubmit({url: '/help/send_help_email', type: 'post'}).complete(function(data) {
// Use response here
});

Related

Why Ajax is triggering 500 internal error in django?

Does anyone know why I am getting 500 internal error when I try to call an Ajax function? I tried to send the response from view.py to Ajax function in 2 ways: JsonResponse (see else from view.py) and also with HttpResponse (see if from View.py).
My Hmtl form does have a csrf_token, so I added the header in ajax function, but still got 500 internal erorr. The data is saved into database but the response is not sent to ajax function.
View.py
## Ajax
#login_required
def SubmitModal(request):
if request.method == 'POST':
text = request.POST['Text']
date = request.POST['DatePicker']
time = request.POST['TimePicker']
T = SText()
T.User = request.user
T.Text = text
T.STime = date + ' ' + time
T.save()
return HttpResponse(json.dumps({'success': True}), content_type="application/json")
else:
return JsonResponse({'success': False})
file that contains ajax
$(document).ready(function () {
// Show the modal window when a button is clicked
$('#open-modal').click(function () {
$('#modal').modal('show');
});
// Close the modal window when a button is clicked
$('.close-modal').click(function () {
$('#modal').modal('hide');
});
// Handle the form submission
$('#modal-form').submit(function (event) {
event.preventDefault(); // Prevent the form from being submitted
var formData = $(this).serialize(); // Get the form data
// Submit the form data to the server using an AJAX request
$.ajax({
type: 'POST',
url: '/submit/',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: formData,
dataType: "json",
success: function (response) {
if (response.success) {
$('#success-message').show();
} else {
$('#error-message').show();
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
$(".textarea-input")[0].value = '';
$(".date-input")[0].value = '';
$(".time-input")[0].value = '';
});
});
If you're reproducing this in a non-production environment, you can set DEBUG=True in the settings file. Then when you make the call from your browser, the response will include details about what the issue is. You can also set the ADMINS variable to send exception tracebacks to the specified emails when they're encountered. More details here.
You can view the data being sent and received in the developer tools of the browser you are using.

Passing data from View to Controller using Ajax results in 404 error on the controller method

I'm trying to pass data from View to Controller Action method. Using Ajax to pass the data to the controller but the controller doesn't receive the data and it is always null resulting in 404 error.
Can someone review this and point out what needs to be fixed?
Ajax call in View -
function openErrorDetails(errors) {
$.ajax({
type: 'POST',
url: "/Home/ErrorDetails",
dataType: 'json',
data: JSON.stringify({ errors }),
success: function (data) {
var win = window.open();
win.document.write(data);
}
});
}
Calling the Ajax funtion using a anchor tag OnClick event to open a new window with the errors details -
var exception = "onClick='openErrorDetails(" + JSON.stringify(data) + ")'> View details";
Controller -
[HttpPost]
public ActionResult ErrorDetails(string errors)
{
if (errors != null)
{
dynamic errorMessages = JsonConvert.DeserializeObject(errors);
return View("ErrorDetails", errorMessages);
}
else
{
return new HttpNotFoundResult();
}
}
this solved it
data: { errors: JSON.stringify({ errors }) },

When redirecting from page my data is lost

I have a method in my javascript with which I send data with ajax of my form to an action in my ruby controller
$scope.pay_spei = function () {
$('#pay_spei').attr("disabled", true);
var concepts = JSON.stringify($scope.transaction_spei.getConcepts());
$.ajax({
url: '/payment_spei/charge',
type: "POST",
data: {
payment_spei: concepts
},
success: function (data) {
console.log("SUCCESS!");
},
error: function (data) {
console.log("ERROR");
}
}).success(function () {
window.location.href = "/payment_spei/charge";
});
};
In my console:
Processing by PaymentSpeiController#charge as */*
Parameters: {"payment_spei"=>"[{\"name\":\"bbbbb\",\"quantity\":12,\"unit_price\":10000,\"$$hashKey\":\"object:3\"}]"}
{"payment_spei"=>"[{\"name\":\"bbbbb\",\"quantity\":12,\"unit_price\":10000,\"$$hashKey\":\"object:3\"}]", "controller"=>"payment_spei", "action"=>"charge"}
in the action of my controller called charge these data disappear:
def charge
concepts = JSON.parse(params[:payment_spei])
end
throws me this error
TypeError in PaymentSpeiController#charge
no implicit conversion of nil into String
this error does not appear when I remove the redirect in javascript
window.location.href = "/payment_spei/charge"
I need to redirect from page, how could I solve this error?

Not able to pass parameters through url in Ajax request using Rails

I'm trying to pass a parameter through a url in an Ajax request that's triggered by a confirmation dialogue. I'd like to fetch the value of that parameter in my Rails controller given a successful request but I haven't been able to do it.
I've tried so far the following code:
Here my Ajax request where I've been adding the param in the URL plus other params in data
function continueSave() {
var name = $('#leader_name').val();
var persisted_time = $('#leader_time').val();
$.ajax({
type: "POST",
url: "/leaderboards/1/?test=1",
data: { leader: { name: name, time: time } },
success: success
});
}
Here the dialogue-related JS
function nameAlert() {
return confirm("Name already exists. Would you like to continue?");
};
(function() {
if (nameAlert()) {
continueSave();
}
else {
//something else here
}
})();
Although the request successfully reaches the controller there's params[:test] is nil in the controller.
I've also tried to pass the test param in data, but it is not working either.
Would appreciate some help.
The relevant controller action (leaders_controller.rb)
def create
#leader = Leader.new(leader_params)
#leader.leaderboard_id = #leaderboard.id
#name_repeated = !#leaderboard.leaders.find_by(name: #leader.name).nil?
#check = params[:test]
if params[:test].nil? && #name_repeated == true
render :template => 'leaders/repeated_name.js.erb'
else
#leader.save
#rank = #leader.rank_in(#leaderboard)
respond_to do |format|
if #leader.save
format.html { redirect_to root_path }
format.js { }
else
end
end
end
end
Note:
1.- 'leaders/repeated_name.js.erb' contains the code for the Ajax request
2.- In routes Leader resource is nested within Leaderboard resource
Sorry guys I found the mistake. It was a dumb one.
I have shallow nested routes so that leaders is nested in leaderboards, therefore I was using the incorrect path for the request. It should be:
$.ajax({
type: "POST",
url: "/leaderboards/1/leaders?test=1",
data: { leader: { name: name, time: time } },
success: success
});
I should have caught that before sorry for wasting your time.
I'll post here - my comments are getting too long.
Try adding { type: 1} to your data and changing type to GET. Rails params contain both GET and POST data - you don't even have to change your controller.
function continueSave() {
var name = $('#leader_name').val();
var persisted_time = $('#leader_time').val();
$.ajax({
type: "GET",
url: "/leaderboards/1/",
data: { leader: { name: name, time: time }, test: 1 },
success: success
});
}

Sending a JSON object to Django backend through AJAX call

I have the following code (jQuery) to create a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
item.Code : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now this is my AJAX function:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ //I need my items object, how do I send it to backend server (django)??
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Now, my doubt is how do I send the 'item[]' object that I created to the backend? I do need to send both the item[] object and the variable 'calltype' which signals what made the AJAX call, as I have the same Django View (its the Controller equivalent for Django) in the backend being called by different AJAX functions.
How will my AJAX function look like?
Hey guys just got my answer right.
I used the following ajax function to get it right:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: items,
calltype: 'save',
'csrfmiddlewaretoken': csrf_token},
dataType: 'json',
// handle a successful response
success : function(jsondata) {
console.log(jsondata); // log the returned json to the console
alert(jsondata['name']);
},
// handle a non-successful response
error : function() {
console.log("Error"); // provide a bit more info about the error to the console
}
});
}());
So, this is sort of a self answer!!! :) Thanks a lot SO!!

Categories

Resources