0

Im using YII and it sends the data as "table[attr1]=1&table[attr2]=2&table[attr3]=3" so to make a request using jquery I use:

 $.ajax({  
        url:"url",
        data:{
             'table[attr1]':1,
             'table[attr2]':2,
             'table[attr3]':3,
        },
        success:function(resp){
            //ok
        }
    });

but I need to make this data json dynamicaly, I tryed this but dosent work:

$("input").each(function(){ //build the data json       
    form.table[this.name]=this.value;  //the name is 'attr1' , the value is 1
});  



     $.ajax({  
        url:"url",
        data:form, //send the JSON here
        success:function(resp){
            //ok
        }
    });

This will send the data empty

Any ideas how to build this json?

2 Answers 2

1

You can do it like this

var form = {}; // create object
$('input').each(function(){
    form[this.name] = this.value; // add name/value
});

then form will hold an object like depending on name/value and assuming your element names are table[attr1] etc

{
  'table[attr1]': 1,
  'table[attr2]': 2,
  'table[attr3]': 3,
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you wirey, I didnt use this approach because I thought will turn the json into a useless array
0

There is no JSON involved here what you are sending is x-www-form-urlencoded, for your code to work you have to create the table property of the form object first.

var form = {table:{}};
$("input").each(function(){  
    form.table[this.name] = this.value;  //the name is 'attr1' , the value is 1
});
$.ajax({  
    url:"url",
    data:form, 
    success:function(resp){
        //ok
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.