Rails Active Model Serializers conflict with Ajax? - ruby-on-rails

When I use gem "active_model_serializers", my all Ajax can't work, my code like following:
$(document).on('change','#brand_id_dropdown', function () {
var request = "/beacons/find_beacon_uuid_given_brand_id?brand_id="
+ $('#brand_id_dropdown').val();
var aj = $.ajax({
url: request,
type: 'get',
data: $(this).serialize()
}).done(function (data) {
change_uuids(data);//modify the majors' dropdown
}).fail(function (data) {
console.log('AJAX request has FAILED');
});
});
I tried change to
data: { get_param: 'value' },
dataType: 'json'
still conflict, whenever I gem serializer and start rails server, all Ajax fail. how can I fix that?

I can't comment because I don't have enough rep. But you need to supply a little more information.
What's the failure message in the rails server logs? Check the rails server output and copy paste the errors into your question. Also, open your browser console and paste the "console" or "network" errors (in chrome: OPTION+CMD+I to show console). Lastly, throw a debugger; statement into your ajax call and play around with the variables.

Related

How to debug ajax response?

I am at lost with ways to debug my Ajax callback. I'm trying to print the response from the php file to see if the call is working but without success. While the call works, the response seem to return empty... Nothing shows in the console but the response in Network tab is 200 OK and I can see the data in the response header. However not able to print it back to the console. console.log(response) should print the table but meh. What are alternative ways to debug this? Any suggestion is welcome.
js
$.ajax({
type: 'POST',
dataType : 'json',
url: 'queries/getsocial.php',
data:nvalues,
success: function(response)
{
console.log(response);//does not print in the console
}
});
So here's the proof I get that it is working server side
After a much needed 10 hour break into the night, I solved the issue with a much clearer mind. I removed the dataType row and it worked for me.
As silly as it may sound, the table in the PHP page was not in JSON format, so when jQuery tries to parse it as such, it fails.
Hope it helps for you. If not, check out more suggestions here.
Before
$.ajax({
type: 'POST',
dataType : 'json',
url: 'queries/getsocial.php',
data:nvalues,
success: function(response)
{
console.log(response);//does not print in the console
}
});
After (Works now)
$.ajax({
type: 'POST',
url: 'queries/getsocial.php',
data:nvalues,
success: function(response)
{
console.log(response);//yes prints in the console
}
});
Can you add a photo of the console? When something like that happens to me, I usually print something console.log(“Response: “+ response). At least if you see the text at least you can be sure your function is getting executed.

Posting form between 2 rails applications including files

I am trying to post a form from one rails app to another hosted on different domains and including files.
I attempted:
$(document).on("click", ".application-form .submission input", function(e){
e.preventDefault();
var form = $(".application-form form");
var data = new FormData(form);
var url = "http://example.com/action";
$.ajax({
url: url,
type: 'POST',
success: function(){
alert('success');
},
error: function(){
alert('error');
},
data: data,
cache: false,
contentType: false,
processData: false
});
});
But the remote server doesn't receive any data, params merely contains the controller name and action.
I also have tried using remotipart and setting up my form with form_for(#application, url: "http://example.com/action", html: {multipart: true}, remote: true) and if I include a file, the server receives [object Object] instead of correct param names and values. If I do not include a file, then the params are sent and received correctly, but I need to include files with the upload.
What is going on to cause [object Object] to replace all my form data when I include a file? Using remotipart 1.2.1. And I've seen this and it does not apply.
There are a lot of issues with attempting what you are:
Cross Domain Requests (CORS)
Form
Uploading
CORS
Your first issue is you have to ensure you're able to pass the data between the two domains. CORS is a standard protocol, whereby you can only send requests to pre-approved domains
Basically, you need some way to whitelist the possible connecting domains, and with Rails, you'll be best to use the RACK-CORS gem
I would begin by ensuring this is set up on your "receiving" domain
Form
Secondly, you need to compile the correct form data when you submit
I would use the .serialize() function:
$(document).on("click", ".application-form .submission input", function(e){
e.preventDefault();
var form = $(".application-form form");
var data = form.serialize();
var url = "http://example.com/action";
$.ajax({
url: url,
type: 'POST',
success: function(){
alert('success');
},
error: function(){
alert('error');
},
data: data,
cache: false,
contentType: false,
processData: false
});
});
This will probably explain the lack of params being sent to your other domain
Upload
Uploading files creates a totally new issue, as it takes a lot to get the file-upload process to work through ajax
There are plugins such as JQuery-FileUpload-Rails allow you to upload files through ajax. From my understanding, this works by providing custom middleware to handle the file upload over ajax. I'm not totally sure how it works, but I know it does, as we've used t multiple times
In general, you cannot directly upload files from a form via AJAX. You have to 'fake' it using either a hidden iframe, Flash, or something similar (might be different in the newest browsers). The jQuery Form plugin does a good job of simplifying this, and there are lots of other plugins as well to help with this.

Ajax call on ruby on rails

I have a ajax call using ruby on rails. I'm getting a success but I don't know how to use the data result of the ajax call.
$.ajax({
url: "/search/get_listing?listing_id" + id,
dataType: 'JSON',
success: function(data) {
var listing = JSON.parse(data);
$("#modalPrice").html(data.city);
}
});
Controller:
#listings_data = Listings.find_by(id: params[:id])
render :json => #listings_data.to_json
Using data.city won't work. I'm expecting to get the values retrieve from the model by simply putting . on the variable
var listing = JSON.parse(data);
Still no luck. Help guys. Thanks!
JSON.parse is Ruby code, API of JSON gem. How can you guys use that in Javascript :)
jQuery can process JSON object data directly. Just use:
success: function(data) {
$("#modalPrice").html(data.city);
}
For example, you can render in the controller:
render :json => { :city => #listings_data }
On the JS:
success: function(data) {
var listing = data.city;
}
I'm having similar problems everytime I use AJAX in rails since the response seems to differ depending on how you return the value or how you are handling the success in JS. Try this:
success: function(data, status, xhr) {
var listing = JSON.parse(xhr.responseText);
$("#modalPrice").html(data.city);
}
I usually use Firebug (Firefox Plugin) to set a breakpoint in my success handlers to check the arguments where exactly the response is in. Sometimes it's in the first value, sometimes in some other and then it may be xhr.response or even xhr.responseText. It's confusing me every time.
To use Firebug for this, press F12 on your page, select the 'Script' pane and find the code you want to check. Click next to the row number of your code where you want your breakpoint. In this case, you could've chosen the var listing line. When the code is executed (after your click), the browser will stop there and you can check the passed arguments on the right side.

Using Ajax/jsonp to receive data from Web Api

I've built a simple web service using the Web Api and I want to consume it from a simple mVC view using jQuery. I'm developing on localhost and consuming the service from Azure, which is why I'm using jsonp.
When I run my jQuery I view in Fiddler and the request is successful and json sent back but the .Ajax function returns these errors:
NaN, parsererror, and callback was not called
<script>
$(function () {
var callback = function(data) {
alert(data);
};
$.ajax({
url: 'http://itjobsdirect.azurewebsites.net/api/values/getbytitle?title=developer',
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'callback',
success: function (data) {
$('#main').text(data);
},
error: function(jqXHR, textStatus, error) {
alert(jqXHR.status + jqXHR.message);
alert(textStatus);
alert(error);
}
});
});
</script>
I found this question: JsonP with Web Api is it still relevant?
Thanks for your help!
Yes, the link to that question you have there is still relevant.
ASP.NET Webapi doesn't ship with a default formatter that understands the dataType of 'jsonp' and so the solution here is to add a custom JsonpMediaTypeFormatter (as shown in the answer for the questions you have linked).

Try to post JSON.stringify object to aspnet mvc controller - bad request

I'm trying to post a JS Object stored in a hidden field:
$("#hdnArr").val(JSON.stringify(arr));
<pre>
$.ajax({
url: form.action,
type: 'POST',
data: $(form).serialize(),
success: function (result) {
//
},
error: function (xhr, textStatus, exceptionThrown) {
//
}
});
</pre>
Locally it is working fine, but in a production server (windows 2012 server with IIS 8), it is returng a Bad Request Error. With Firebug I checked that my hidden value is like this:
hdnArr=%5B%7B%22Type%22%3A%22%22%2C%22TypeB%22%3A%22%22%2C%22TypeC%22%3A%22%22%2C%22TypeD%22%3A%22%22%7D%5D
This problem is basically the % character. How can I enable my server to accept this char?
Ok, I could solve this problem just switching the Managed Pipeline from App Pool to Classic Mode.

Resources