简体   繁体   中英

unable to pass array from jquery to php

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.

AJAX is going to send the data to an external file, and you will not be able to see the output. That is why there is nothing visible happening when you submit the form. Maybe if you had the PHP script email you the data then you can check if it is passing it properly.

Fist of all, your code is syntactically and semantically incorrect. I marked the incorrect places with "<----"

function Bet(eventId,pick,odds,stake,profit,betType){
 return ({
    eventId:eventId,
    pick:pick,
    odds:odds,
    stake:stake,
    profit:profit,
    betType:betType
  });
} <------

 var bets = {};
$(".bet-selection").each(function() {
  /**
  some logic here
  **/
 }

 bets.push(Bet(eventId,pick,odds,stake,profit,betType)); <--- I guess this should be inside the loop, right?
});

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:

$.ajax({
 url:    'testsubmit.php',
 cache:          false,
 type:   'post',
 data:   { bets : JSON.stringify(bets)}
});

On PHP side, use json_decode function to decode JSON string to a PHP array of objects.

<?php

$bets = json_decode($_POST['bets']);
var_dump($bets);

Nice day.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM