Good afternoon,
We are doing an jquery ajax call with the .serialize() function. We are doing this because the form has multiple columns/rows that we would like to save with one call to ajax. The serialize function takes all the pertinent form data and serializes it. Here is what gets sent to the php ajax call.
$.ajax({
type: "POST",
url: "ajax/SaveClaimParts.php",
data: {
'ClaimID': $('.hdn-claim-id').val(),
'Parts': $('.parts-form').serialize()
},
dataType: "json",
success: function(data)
{
console.log("Happy");
},
error: function()
{
console.log("An error occurred while processing the save.");
}
});
This works great because when I see what gets sent to the server to be processed looks something like this.
claim_part_no=12349&claim_part_desc=TUBE&claim_part_no=85555&claim_part_desc=BRACKET
Please note the duplicated part_no and part_desc. This is not a mistake but rather the fact that there are 2 rows that we want to submit. Each row contains a part # and a part desc.
The question now is how do I break this string up in php so that it can be saved/inserted row-by-row.
Here is what I have tried:
$Parts = $_POST['Parts'];
$PartsArray = array();
parse_str($Parts, $PartsArray);
This works but it only has the last row in $PartsArray. Any help would be much appreciated.
Thank you. George Eivaz
Based on your provided string:
claim_part_no=12349&claim_part_desc=TUBE&claim_part_no=85555&claim_part_desc=BRACKET
EDIT: Since you have repeating keys, it makes more sense not to use an associative array for this. The following code is updated to reflect retaining your keys despite repetition in the javascript serialization.
You can parse this using strpos
and substr
, something like this:
$current_key = 0;
foreach ( explode( '&', $str ) as $substring )
{
$divisor = strpos( $substring, '=' );
$key = substr( $substring, 0, $divisor );
$val = substr( $substring, $divisor + 1, strlen( $substring ) );
$PartsArray[$current_key][$key] = $val;
if ( $key == 'claim_part_no' )
{
$current_key++;
}
}
Then if you var_dump( $partsArray );
you should get something like this:
array (size=2)
0 =>
array (size=2)
'claim_part_no' => string '12349' (length=5)
'claim_part_desc' => string 'TUBE' (length=4)
1 =>
array (size=2)
'claim_part_no' => string '85555' (length=5)
'claim_part_desc' => string 'BRACKET' (length=7)
This should work ok as long as your serialization does not include &
or =
as part of the return values, so don't use it to parse anything that is url encoded (&
will encode to &
and break this).