Home > Mobile >  jQuery/Php Error Illegal string offset from unserialized post data
jQuery/Php Error Illegal string offset from unserialized post data

Time:05-26

I'm posting a jquery serialize data posting from modal/pop up div tag with name attribute such as formdata[1]field_x

<div  id="modal-payref-settings" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="modal-paycode-detailsLabel" aria-modal="true" role="dialog" style="padding-right: 17px; display: block;">
<div ><div >
<div >
<input type="text" name="formdata[1]payref_autonum" >
<input type="text" name="formdata[1]payref_prefix" >
<input type="text" name="formdata[1]payref_suffix" >
<input type="text" name="formdata[1]payref_pad"  value="4">
<input type="text" name="formdata[1]payref_next"  value="876">
<input type="text" name="formdata[1]payref_sample"  placeholder="Sample" aria-label="Sample" readonly="">
</div>
<!-- modal-body ends -->
</div>
</div>
</div>


$.ajax({
type: 'POST',
    url: 'model/trcode.php',
    data: {
        'a': 'SAVE_PAYREF',
    
      'formdata':$('#modal-payref-settings').find('[name^="formdata"]').serialize(),
    },
  //  dataType: "JSON",
    success: function (jsonStr) {
       alert(jsonStr);
    }
});

The Fetch/XHR capture the serialized posted data, which indicate the posting is correct. The same result return with print_r($_POST["formdata"] ); .

formdata[1]payref_autonum=Yes&formdata[1]payref_prefix=P2022&formdata[1]payref_suffix=&formdata[1]payref_pad=4&formdata[1]payref_next=876&formdata[1]payref_sample=

The data are getting un-serialized parse_str($_POST["formdata"], $formdata );. However $formdata return an empty array.

(
[formdata] => Array
(
    [1] => 
)
)

CodePudding user response:

You're trying to use a string as a full array

You can change the ajax code like

$.ajax({
type: 'POST',
    url: 'model/trcode.php',
    data: {
        'a': 'SAVE_PAYREF',
    
      'formdata':$('#modal-payref-settings').find('[name^="formdata"]').serialize(),
    },
  dataType: "JSON",
contentType: false,
            cache: false,
            processData:false,
    success: function (jsonStr) {
       console.log(jsonStr);
    }
});

And inside model/trcode.php page you can pass the

echo json_encode($_POST["formdata"]);

if use alert(jsonStr) instead of console.log(jsonStr) you will not get actual output sometimes because you are passing the object.

CodePudding user response:

The issue is your form fields name attribute is not an array,(which you are thinking is an array, but has a syntax error).To fix this do like below:

change names like this: formdata[1][payref_autonum] and so on for others.

  • Related