Each user post to php page [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello overflowers!
The problem i'm stuck on at the moment is following.
I have managed to add a "✓" to selected users.
I have added a "data-id" attribute to each listed user.
The thing I'm trying to figure out is how I have post the users data-id from jquery to my php page.
Jquery:
task_takers = [];
var i = 0;
$(".new-task-takers ul.select_takers li").each(function(){
$(this).click(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
}
console.log("Selected:", $(this).data("id"));
i += 1;
task_takers[i] = $(this).data("id");
console.log(task_takers);
console.log(i);
});
});
console.log(task_takers);
PHP:
$task_takers = isset($_POST['task_takers']) ? $_POST['task_takers'] : NULL;
var_dump($task_takers);
All I'm getting is a NULL
Edit:
I got it too work, but the thing is the array is getting flooded if you select the user and un-select and re-select.
Array:
[1: 2, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3]
As you can see it spams ID: 3

You have to send data to the php script in order to make it work.
Here is a little example of jQuery.ajax from the docs :
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I usually use it as following :
$("form").submit(function(){
$.ajax({
type: 'POST',
url: "/relative/path/to/php/script.php",
data: $("form").serialize(),
success: function(data) {
console.log(data)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
Hope it helps.
EDIT
Since your last edit :
You could solve this by using array_unique to remove duplicated items of the array from the PHP script.
For example :
php > $arr = array("1" => 2, "2" => 3, "3" => 3, "4" => 3, "5" => 3, "6" => 3);
php > print_r($arr);
Array
(
[1] => 2
[2] => 3
[3] => 3
[4] => 3
[5] => 3
[6] => 3
)
php > $uniq_arr = array_unique($arr);
php > print_r($uniq_arr);
Array
(
[1] => 2
[2] => 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']
}
}
}

send json to php (jquery) [duplicate]

This question already has answers here:
Issue reading HTTP request body from a JSON POST in PHP [duplicate]
(2 answers)
Closed 4 years ago.
I am trying to pass a Json obtained by a json.stringify process of an html table to a php file to insert it into a database.
First,wanted to check is the code below is ok : i get the right output of the json when doing an alert of 'myjson':
var myjson= JSON.stringify(mydata);
alert(myjson);
[{},{"product[]":"john","qty[]":"288","price[]":"199","total[]":"57312"},{"product[]":"sylvia","qty[]":"12","price[]":"13","total[]":"156"},{"product[]":"juan","qty[]":"11","price[]":"9","total[]":"99"},{"total_amount":"57567.00"}]
then i have this ajax to send it to php (test.php):
$.ajax({
url: "test.php",
type: "POST",
data: myjson,
dataType: "JSON",
success: function (data) {
alert(data);
}
});
And my php file to check if the output is fine:
$obj = json_decode($_POST["mydata"]);
echo $obj->var;
but i do not get anything in my alert once the php is supposedly processed?
what is wrong?
Firstly, you will need to post the data with a name, more specifically with the name "mydata".
Currently the PHP looking for a post called mydata ($_POST["mydata"]) which is not available and throws the following Notice Undefined index: mydata
To do that, you can change the data you're sending from:
data: myjson
to
data: {"mydata": myjson}
Second, the data sent to the back-end is an array of objects
Array
(
[0] => stdClass Object
(
)
[1] => stdClass Object
(
[product[]] => john
[qty[]] => 288
[price[]] => 199
[total[]] => 57312
)
[2] => stdClass Object
(
[product[]] => sylvia
[qty[]] => 12
[price[]] => 13
[total[]] => 156
)
[3] => stdClass Object
(
[product[]] => juan
[qty[]] => 11
[price[]] => 9
[total[]] => 99
)
[4] => stdClass Object
(
[total_amount] => 57567.00
)
)
You will need to access them by index or iterate through the array.
Access them by index: $obj[0]->var or $obj[1]->var
Last but not least, the properties contain square brackets {"product[]":"john","qty[]":"288","price[]":"199","total[]":"57312"} which is not recommended but will still work. Accessing the properties should be done like: $obj[1]->{'property[]'}
JavaScript:
<script type="text/javascript">
function sendAjax(){
var mydata = [{}, {"product[]":"john","qty[]":"288","price[]":"199","total[]":"57312"}, {"product[]":"sylvia","qty[]":"12","price[]":"13","total[]":"156"},{"product[]":"juan","qty[]":"11","price[]":"9","total[]":"99"},{"total_amount":"57567.00"}]
var myjson = JSON.stringify(mydata);
$.ajax({
url: "test.php",
type: "POST",
data: {"mydata": myjson},
dataType: "JSON",
success: function (data) {
alert(data);
}
});
}
</script>
PHP:
<?php
$obj = json_decode($_POST["mydata"]);
echo $obj[1]->{'product[]'};
?>
Update:
The AJAX is expecting a JSON response, otherwise it will fail. In the Back-End you will need to change the response to JSON.
<?php
$obj = json_decode($_POST["mydata"]);
header('Content-Type: application/json');
echo json_encode($obj[1]->{'product[]'});
?>

Merge serialized form with array

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]}),

POSTing multidimensional array to the server via PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
multi-dimensional array post from form
I would like to send some data from the client to the PHP server using jQuery $.post(). When it arrives at the server, I would like $_POST['myList'] to be equal to either of the following (what ever is easiest). What should I set the data object to within $.post()?
array (
0=>array('id'=>123,'d1'=>'aaa','d2'=>'xxx'),
1=>array('id'=>234,'d1'=>'bbb','d2'=>'yyy'),
2=>array('id'=>345,'d1'=>'ccc','d2'=>'zzz')
)
array (
123=>array('d1'=>'aaa','d2'=>'xxx'),
234=>array('d1'=>'bbb','d2'=>'yyy'),
345=>array('d1'=>'ccc','d2'=>'zzz')
)
EDIT: first one looked like a simple array of objects, but seems jQuery needs this to be a keyed object:
var send_this = {
0: { id: 123, d1: 'aaa', d2: 'xxx' },
1: { id: 234, d1: 'bbb', d2: 'yyy' },
2: { id: 345, d1: 'ccc', d2: 'zzz' }
};
Second looks just has different looking keys for object containing objects:
var send_this = {
'123': { d1: 'aaa', d2: 'xxx' },
'234': { d1: 'bbb', d2: 'yyy' },
'345': { d1: 'ccc', d2: 'zzz' }
};
Tested implementation in jQuery 1.7.1:
$.post( '/herp.php', send_this, function(d) {
console.info( d );
});
The PHP program receives data exactly as you want it in $_POST.
You should use a JSON strong to send the data: Here is an example:
var pushData = {
id: "blalal",
id: "blalal",
id: "blalal",
};
JSON.stringify(pushData)
and then you can just post it or whatever
$.ajax({
url : "http://blalallalalal="+JSON.stringify(pushData),
type : "POST",
dataType: "text",
success: function (data) {
},
error: function() {
// alert("fsdf");
}
});
then from php side just use
$data = get_object_vars(json_decode($dataJSON));
DONE
Option 1
var data = [
{ id: 123, d1: 'aaa', d2: 'xxx' },
{ id: 234, d1: 'bbb', d2: 'yyy' },
{ id: 345, d1: 'ccc', d2: 'zzz' }
];
Option 2
var data = {
'123': { d1: 'aaa', d2: 'xxx' },
'234': { d1: 'bbb', d2: 'yyy' },
'345': { d1: 'ccc', d2: 'zzz' }
};
then
$.post(url, {mylist: data});
If your using jQuerys $.post or $.get, you do not need to encode/decode, just pass a JS object as the data argument...
var data = {
"myList" : {
0 : {"id":1,...etc},
1 : {"id":2,...etc},
2 : {"id":3,...etc},
etc...
}
};
// post or get
$.post(
url2post,
data,
callbackFunc
);
You could send them as three arrays, one for each attribute.
myList_id[]=123&myList_d1[]=aaa&myList_d2[]=xxx&myList_id[]=234&...
In PHP, you will recieve them as $_POST['myList_id'], $_POST['myList_d1'] and $_POST['myList_d2'], which you could combine into your desired array.
Or if you include indices, you could go a step further:
myList[0][id]=123&myList[0][d1]=aaa&myList[0][d2]=xxx&myList[1][id]=234&...
which will give you the array directly: $_POST['myList']

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