I need to pass an array to from jquery to php for processing.
i create an array object like this
function Bet(eventId,pick,odds,stake,profit,betType){
return {
eventId:eventId,
pick:pick,
odds:odds,
stake:stake,
profit:profit,
betType:betType
}
in my submit handler i have this piece of code
var bets = {};
$(".bet-selection").each(function() {
/**
some logic here
**/
}
});
bets.push(Bet(eventId,pick,odds,stake,profit,betType));
});
$.ajax({
url: 'testsubmit.php',
cache: false,
type: 'post',
data: bets
});
Nothing happens when i submit the form. I was hoping the an array will be submitted to php and i can use print_r to view the structure. Please guys what am i doing wrong and where?
Thank you.
Fist of all, your code is syntactically and semantically incorrect. I marked the incorrect places with “<—-“
Now you cannot just post Javascript objects like this. The best option is encoding them as JSON (JavaScript Object Notation), which actually encodes them … as JS objects 🙂
Modern browsers include JSON parser/encoder, but older don’t. So include the following library to make sure older browsers won’t break: https://github.com/douglascrockford/JSON-js
Next, you’ll need to modify a bit of your code:
On PHP side, use json_decode function to decode JSON string to a PHP array of objects.
Nice day.