3

I've got an object like this:

var obj = {
    age:["23"],
    part:["0"],
    race:[],
    state:["AL"],
    gender:["1"],
    county:["9999"],
    consent:["9999"]
};

I pass this object to php for processing, but race[] is not passed to php along with everything else. How do I change race so it gets sent and has a value of ""?

EDIT: Any one of those (age, part, race, …) could be empty, so I need a way to check and then change.

I've used this code to loop thru the object/array: http://jsfiddle.net/jshado1/wLZMH/

7
  • 3
    Did you try obj.race = [""];? Commented Jan 9, 2012 at 21:47
  • 4
    How are you passing it to PHP? Also, is there any reason why all of your object values are 1-length arrays? Commented Jan 9, 2012 at 21:50
  • @fluffy: via jQuery AJAX. Race can have multiple values, ex race:["asian","black","white"] Commented Jan 9, 2012 at 21:55
  • 2
    It's normal for the jQuery parameter serialiser (and browsers in general) to omit unfilled fields - you should fix your PHP script to anticipate that. Commented Jan 9, 2012 at 21:57
  • I wrote my own serialiser because I needed more complex output. Commented Jan 9, 2012 at 22:17

2 Answers 2

2

Just do:

if(obj.race!==undefined && obj.race.length===0){
   obj.race = [""];
}

Or:

if(obj.race!==undefined && obj.race.length===0){
   obj.race.push("");
}

EDIT:

For all elements

for(var key in obj){
 if(obj[key]!==undefined && obj[key].length===0){
     obj[key] = [""];
 }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! btw when I wrote it, I had obj[key].length < 1 and it didn't work.
1

I'm not sure why you've marked it up in that way. If you're passing key–value pairs to PHP, then it should look as follows:

var obj = {
    age: "23",
    part: "0",
    race: {
        "Value 1",
        "Value 2"
    },
    state: "AL",
    gender: "1",
    county: "9999",
    consent: "9999"
};

That way, each value would be passed to PHP (as it's a string, despite being empty).

6 Comments

they are arrays because race could have multiple values.
You'd probably be better passing an object rather than an array then, as modified above.
Functionally, what's the difference between this and the array I have?
Arrays are for numerically indexed data, objects are for non-numeric keys. Plus, objects are more extendable.
No. "23" is a string, as it's surrounded by quotes (it probably should be an integer). The value for race is an object, as it's wrapped in curly braces ('{' and '}').
|

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.