1

I have a simple object

function MyClass()
{
    this.id = null;
    // ... Lot of stuff in it
}
MyClass.prototype.parse = function(text)
{
    // A parsing function that fills the object
}

If I try to send the object using $.post

$.post("target.php", { QUERY: "query_id", object: obj }, function(data){
    console.log(data);
}, 'json');

with obj being an instance of MyClass, I get an error : text is undefined

How do I make it understand that I only want the data being sent, not the methods like parse as it wouldn't make any sens ?

2 Answers 2

2

You can iterate over an object's properties by doing

for (var prop in obj)

Using that in combination with typeof to figure out if the property is a function, you can create a function to return all non-function properties as a new object. I whipped up this jsfiddle as an example.

http://jsfiddle.net/6w0wj8hj/

That means you can then do

$.post("target.php", { QUERY: "query_id", object: obj.getProperties() }, function(data){
    console.log(data);
}, 'json');
Sign up to request clarification or add additional context in comments.

1 Comment

Nice ! What I ended up doing is putting the getProperties method in a Postable class, and make other class inherit from it :)
1

When doing an Ajax call, you can only send string. It automatically converts the data to string but if it can't, like in your case, it throws an error. In this case, instead of sending obj, send obj.data (the string value).

2 Comments

As my obj contains a lot of fields, the automatic conversion is very nice. Is there any way to restrict it only to fields where it's possible ?
Im pretty sure this link will be really helpful to you: stackoverflow.com/questions/1068189/…

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.