How to use dynamic data name using jQuery.post?

I have 2 basic form used to convert data (type 1 ↔ type 2).

I want to fulfill my .post request using only 1 form.

I have a problem with the [data] parameter for jquery.post

Here is my code:

$('form').submit(function(){
    var a = $(this).parent().find("input").attr('name');
    var b = $(this).parent().find("input").val();
    var url = $(this).attr('action')
    $.post(url, { a:b },function(data) {
        $(data).find('string').each(function(){
            $('.result').html($(this).text());
        });
    });
    return false;
});     

The problem lies within {a:b}. binterpreted as my var b, but ano, so my message options are similar to [a:1]instead [param:1].

Is there a way to have a dynamic a?

+1
source share
2 answers

Try the following:

var data = {};
data[a] = b;
$.post(url, data, function(data) {

So like this:

$('form').on('submit', function (e) {
    e.preventDefault();

    var data = {};
    var el = $(this);
    var input = el.parent().find('input');

    var a = input.attr('name');
    var b = input.val();
    var url = el.attr('action');

    data[a] = b;

    $.post(url, data, function(data) {
        $(data).find('string').each(function(){
        $('.result').html($(this).text());
    });
});
+7
source

Yes, use something else to report data:

$.post(url, a+"="+b,function(data) {
    $(data).find('string').each(function(){
        $('.result').html($(this).text());
    });
});
+3
source

All Articles