Merge serialized form with array - php

I have a form and I am sending it with ajax to server.
Like this:
$.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize(),
dataType : 'json',
success: function(data){
}
});
And I receive in server something like
Array
(
[forms_element_1] => 'some value 1',
[forms_element_2] => 'some value 2',
[forms_element_3] => 'some value 3'
)
Now i need to add to this form global variable that is array itself.
var statuses = [5,7,3];
I need to receive from POST in server side something like
Array
(
[forms_element_1] => 'some value 1',
[forms_element_2] => 'some value 2',
[forms_element_3] => 'some value 3',
[statuses] => Array
(
[0] => 5,
[1] => 7,
[2] => 3
)
)
How can I achieve that in jQuery?

Turn it into a param string with $.param, then append it to the serialized form (which is also a param string).
data: form.serialize() + "&" + $.param({statuses:[5, 7, 3]}),

Related

PHP handling multi-dimensional object//array from AJAX Jquery post

I have a large multi-dimensional object of arrays in JS that I am trying to pass to PHP using Ajax. The keys of some of the array values are written arrays test[key], and in PHP I want them to be read as such test => array([key] => 123). Note, I am working in Wordpress.
Working example
JS:
var args = {
'action' : 'save',
'test[key1]' : ['123', 'abc']
}
var request = $.ajax({
url: settings.get('ajaxurl'),
data: args,
type: 'post',
success: function(response) { // }
});
PHP print_r on output:
[action] => save
[test] => Array
(
[key1] => Array
(
[0] => 123
[1] => 234
)
)
However, I want to send all of the test[key1] (and a lot more data) at the second level of the object. I have a lot of data and need them grouped accordingly.
Not working example
JS:
// simple changing the args
var args = {
'action' : 'save',
'data' : {
'test[key1]' : ['123', 'abc']
}
}
PHP print_r on output:
[action] => save
[data] => Array
(
[test[key1] => Array
(
[0] => 123
[1] => 234
)
)
This seems to be really difficult to explain - but it looks like PHP isn't parsing the array keys properly when it's not on the top level of the array. Am I doing something wrong // is there a way around this? I can provide more insight if needed, I attempted to make this as clear as possible.
When printing the keys of the data array, it prints them without the final ]. So it shows test[key1 instead of what I am expecting. Maybe they get stripped somewhere?
I think you need to stringify the data
var request = $.ajax({
url: settings.get('ajaxurl'),
data: JSON.stringify(args),
type: 'post',
success: function(response) { // }});
Then use json_decode to make it useful in PHP.
Edit:
This might get you where you want to go...
var args = {
'action' : 'save',
test : {
key1 : [
'123',
'abc' ]
} }
Since JavaScript does not allow for associative arrays.
Please try this args, this will give multi-dimensional array result.
var args = {
'action' : 'save',
'data' : {
'test': {
'key1' : ['123', 'abc']
}
}
}

get select options from php in x editable

I am using x editable for inline editing.
JQUERY
$('#status').editable({
value: 2,
source: [
{value: 1, text: 'Active'},
{value: 2, text: 'Blocked'},
{value: 3, text: 'Deleted'}
]
});
This one is running fine. But the problem is, I want to get source options from php. For that I have an array.
PHP
$php_array = Array ( [MOBILE_TOPUP] => MOBILE_TOPUP
[PICKUP] =>PICKUP
[DELIVERY] => DELIVERY
[BANK_DEPOSIT] => BANK_DEPOSIT )
I tried with by passing below variable in source but it's not working:
var json_array = <?=json_encode($php_array)?>;
How can I achieve this? Do I need to change array structure in PHP? Thanks for any help!
Yes, you have to change array structure as below :
$php_array = Array (
array('value' => 1, 'text' => 'Active'),
array('value' => 2, 'text' => 'Blocked'),
array('value' => 3, 'text' => 'Deleted'),
);
var json_array = '<?=json_encode($php_array)?>';
You shouldn't use PHP inside JS, better to make an ajax call. This feature is built into x-editable if you use the source option with a string like so:
$('#status').editable({
value: 2,
source: 'mypage.php'
});

JQuery, Ajax, Json, PHP multidimensional associative array

I am trying to loop through a multidimensional associative array retrieved via jquery/ajax from a php file.
The php array looks like this:
$pink = array ( "newarray" => array
( "varietyOne" => array
("name" => "Poublout", "year" => 2002),
"varietyTwo" => array
("name" => "Gerarde", "year" => 2003),
"varietyThree" => array
("name" => "Encore", "year" => 1956),
"varietyFour" => array
("name" => "Toujours", "year" => 1957),
"varietyFive" => array
("name" => "J'aime", "year" => 1958),
"varietySix" => array
("name" => "Alisee", "year" => 2001)
),
"varNumber" => array
("varietyOne",
"varietyTwo",
"varietyThree",
"varietyFour",
"varietyFive",
"varietySix"
)
);
print json_encode($pink);
The js looks like this:
$(document).ready(function () {
$('.clicker').click(function () {
$.ajax({
type: 'GET',
url: 'another.php',
dataType: 'json',
success: function (brandon) {
for (var i = 0; i < brandon.newarray.length; i++) {
var catName = brandon.varNumber[i];
for (var wineName in brandon.newarray[i][catName]) {
console.log(branond.newarray[i][catName][wineName]);
}
}
}
});
});
});
And here is the json rather than the php:
{"newarray":
{"varietyOne":{"name":"Poublout","year":2002},
"varietyTwo":{"name":"Gerarde","year":2003},
"varietyThree":{"name":"Encore","year":1956},
"varietyFour":{"name":"Toujours","year":1957},
"varietyFive":{"name":"J'aime","year":1958},
"varietySix":{"name":"Alisee","year":2001}},
"varNumber":
["varietyOne","varietyTwo","varietyThree","varietyFour","varietyFive","varietySix"]}
I've tried several different loops, changing my array values, but I can't make anything work. I can call an individual key=value pair in the array, but I can't get it to loop through all values.
Thank you.
And the results of console.log(brandon)
Object { newarray={...}, varNumber=[6]}
newarray
Object { varietyOne={...}, varietyTwo={...}, varietyThree={...}, more...}
varietyFive
Object { name="J'aime", year=1958}
varietyFour
Object { name="Toujours", year=1957}
varietyOne
Object { name="Poublout", year=2002}
varietySix
Object { name="Alisee", year=2001}
varietyThree
Object { name="Encore", year=1956}
varietyTwo
Object { name="Gerarde", year=2003}
varNumber
["varietyOne", "varietyTwo", "varietyThree", 3 more...]
0 "varietyOne"
1 "varietyTwo"
2 "varietyThree"
3 "varietyFour"
4 "varietyFive"
5 "varietySix"
So, the loop now outputs to console, but I want the text to be displayed on my site. Normally I use a $('#somediv').append(brandon.(whateverelse); and the information will appear. In this case it does not.
You shouldn't need the varNumber array.
All you need is:
for (var index in brandon.newarray) {
console.log(index);
console.log(brandon.newarray[index]);
console.log(brandon.newarray[index]['name']); // or brandon.newarray[index].name
console.log(brandon.newarray[index]['year']); // or brandon.newarray[index].year
}
In this case, index will be varietyOne, varietyTwo, etc.

Unable to parse JSON generated by PHP in Javascript

I have a php script which returns a JSON string.
<?php
$arr = array(
'id' => '1',
'myarray' => array(
array('a' => 'a1', 'b' => 'b1', 'c' => 'c1', 'd' => 'd1'),
array('a' => 'a2', 'b' => 'b2', 'c' => 'c2', 'd' => 'd2')
)
);
echo json_encode($arr);
?>
The javascript code for parsing the JSON is
$.ajax({
dataType: "json",
url: "http://www.something.com/sendJson.php"
}).done(function(json) {
data = jQuery.parseJSON(json);
alert(data['id']);
});
But for the above code i'm getting this error
SyntaxError: JSON Parse error: Unexpected identifier "object"
What could be causing this error?
The problem is your ajax call. You have dataType: "json", which means your string is already parsed in the callback.
So:
$.ajax({
dataType: "json",
url: "http://www.something.com/sendJson.php"
}).done(function(json) {
alert(json['id']);
});

serialize and param return issue with PHP and JQuery

I have the following code:
var data_str = $('form').serialize();
alert(data_str);
$("#SerializeTXT").text(data_str).show();
$.ajax( {
type: 'POST',
url: 'test.php',
data: data_str,
success: function(data) {
$('#result').html(data);
}
});
Here is my test.php and the result:
<?php print_r($_POST);?>
in the #result i get
Array ( [itemIDhidden] => 2640 [SelectQt] => 1 [Bread] => Black Bread_0 [Cheese] => American_0 [Toppings] => Bacon_0 [Description] => TWSTE 3 45 T4 )
In the SerializeTXT I get
itemIDhidden=2640&SelectQt=1&Bread=Black+Bread_0&Cheese=American_0&Toppings=Sauteed+Mushrooms_0&Toppings=Fried+Onions_0&Toppings=Bacon_0&Description=TWSTE+3+45+T4
You can see that the post gets only the last element of the multiple selected element. In SerializeTXT div i get exactly what is selected from the form.
Any ideas and how can I obtain all those parameters in the php file?
Thank you in advance.
Change your select element's name from Toppings to Toppings[]
<select name="Toppings" ...
to
<select name="Toppings[]" ...
Then $_POST['Toppings'] will be an array.
var form = $('form');
var data_str = '';
form.find('input, select, textarea').each(function()
{
data_str += $(this).attr('name')+'='+$(this).val()+'&';
});
$.ajax( {
type: 'POST',
url: 'test.php',
data: data_str,
success: function(data) {
$('#result').html(data);
}
});
};
test.php
print_r($_POST); returns
Array ( [itemIDhidden] => 2643 [SelectQt] => 1 [Bread] => Multi-Grain Bun_0 [Cheese] => American_0,Swiss_0 [Toppings] => Fried Onions_0,Bacon_0,Raw Onion_0 [Description] => TEST TEST TEST [CancelItemForm] => Cancel [BasketItem] => Confirm ).
This array can be easily manipulated in the PHP file. I hope this helps to some of the people outside

Categories