Aayush Dahal
Aayush Dahal

Reputation: 1182

Unable to Send array as a parameter of form

I have created a hidden form and trying to add some other input field on ajax success and then later trying to submit this form. However, appending array into field is not going right.

success : function(resp) {
   $('#checkout').append('<input type="text" name="subtotal" value="'+resp.data.subTotal+'" />');
   $('#checkout').append('<input type="text" name="tax" value="'+resp.data.tax+'" />');
   $('#checkout').append('<input type="text" name="times" value="'+resp.data.times+'" />');
}

Doing so, input field times becomes like

<input type="text" name="times" value="[{"start_date":"2019-06-10","end_date":"2019-06-10","start_time":"08:00:00","end_time":"09:00:00"},{"start_date":"2019-06-11","end_date":"2019-06-11","start_time":"08:00:00","end_time":"09:00:00"},{"start_date":"2019-06-12","end_date":"2019-06-12","start_time":"08:00:00","end_time":"09:00:00"}]"

response looks like

{"status":"200","data":{"times":[{"start_date":"2019-06-10","end_date":"2019-06-10","start_time":"08:00:00","end_time":"09:00:00"},{"start_date":"2019-06-11","end_date":"2019-06-11","start_time":"08:00:00","end_time":"09:00:00"},{"start_date":"2019-06-12","end_date":"2019-06-12","start_time":"08:00:00","end_time":"09:00:00"}],"subTotal":300,"tax":24}}

And when I submit this form, it is not sending times value.

print_r($_POST)

Array
(
  [_token] => x8THCiWyxRXnb9T3mKI3ae8XzfKwHicW1SbwBGXS
  [subtotal] => 300
  [tax] => 24
  [times] => [{
)

I want to sent those times values to the server either this or that way.

Upvotes: 1

Views: 55

Answers (3)

Muthu R
Muthu R

Reputation: 806

you have to put the json string within single quote fiddle

$('#checkout').append('<input type="text" id="times" name="times" value=\'' + JSON.stringify(resp.data.times) + '\' />');

Upvotes: 1

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

inside your success response stringify JSON data :

 success : function(resp) {
                   let times=JSON.stringify(resp.data.times);

                   $('#checkout').append('<input type="text" name="times" value="'+times+'" />');

}

and decode at server side :

 $posted_data = json_decode($_POST['times'], true);

Upvotes: 2

vlumi
vlumi

Reputation: 1319

The values of input elements can only be strings, so you'll need to serialize your object first, e.g. into JSON:

$('#checkout')
    .append('<input type="text" name="times" value="'
        + JSON.stringify(resp.data.times)
        + '" />');

Upvotes: 1

Related Questions