Asked  7 Months ago    Answers:  5   Viewed   48 times

I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:

$.ajax({
    type: 'POST',
    url: '/form/',
    data: {"name":"jonas"},
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.

Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?

 Answers

66

You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.

If you pass the data as a string, it won't be serialized:

$.ajax({
    type: 'POST',
    url: '/form/',
    data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});
Tuesday, June 1, 2021
 
antoniputra
answered 7 Months ago
97

Sounds like you're getting an HTTP 411 error.. This error can happen if you're sending a POST request without any data.

To fix this, add an empty object ({}) to the data property to your requests:

$.ajax({ 
    url: url, 
    type: 'POST', 
    data: {}, // <- set empty data 
    success: function(data, textStatus) { 
        // do something 
    } 
}); 
Thursday, September 23, 2021
 
maelgrove
answered 3 Months ago
28

my bet it's because of the $(this), try it this way....

$('#bin form').submit(function() {
    var $this = $(this);
    $.post($this.attr('action'), {
        success: function(data) {
            $this.hide().siblings('form').show()
        },
        data: $this.serialize()

    });
    return false;
});

demo no error

demo with the error

Thursday, October 14, 2021
 
Hadi J
answered 2 Months ago
75

Assuming there's only one select element...

jQuery('option[value=eggplant]').insertAfter('option:first-child')

I also assume that you actually have value attributes on your elements.

http://jsfiddle.net/wNmLF/


The code in the question changed. Now it would be...

jQuery('select.comestibles option[value=eggplant]').insertAfter('select.comestibles option:first-child')

For the most recent change...

jQuery('select.comestibles').each(function(){
    var opts = $(this).children();
    opts.filter('[value=eggplant]').insertAfter(opts.first())
}); 
Tuesday, November 16, 2021
 
Ivan Mushketyk
answered 3 Weeks ago
81

If you're using a more recent version of Rails, and wanted to do this in an unobtrusive fashion as possible, you'd use the :respond_to options in your controller, like so:

class MyController < ApplicationController

  def first_method
     respond_to do |format|
        format.html # this handles normal requests asking for html
        format.js # this handles requests asking for javascript to be sent instead
      end
  end

end

If you're responding to a click, you'd do something like firing the query like so on the page

$("a.element_you_click_to_trigger").click(function(e) {
  e.preventDefault(); // make sure clicking doesn't trigger unneeded event bubbling
  $.ajax({url: "/controller/first_method", type: "POST", dataType: "script"}); // send a request and tell the server that you want javascript back
}

Just like you have an index.html.erb file in your views folder for that controller, you'd have a similar first_method.js.erb file in relevant views folder along side your index.html.erb file:

views
  controller
    index.html.erb
    first_method.js.erb

This will return javascript that gets executed client side, but it gets build server side, so you can contain rails ERB fragments, so you can do something like this:

$('#loading_placeholder_element').html('<%= escape_javascript(render(:partial => "create")) %>');

// do some other stuff you fancy in the page

// then make the next call once the other stuff is over (you may need to add this as a call back on an animation):
$.ajax({url: "/controller/second_method", type: "POST", dataType: "script"});

You'd then repeat the same process again for each of the others longer methods that fsmf highlighted.

I found this Railscast on jQuery incredibly helpful when I was learning this a couple of months ago, and I'd really recommend it.

Hope this helps !

Friday, December 3, 2021
 
Iber
answered 4 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share