Post value via ajax to php - php

I trying to post some value via ajax to php then php print send back js console.log, have problem:
build array( I'm doubt below I made is array??)
$('.eachcontainer').each(function(){
var arr = $(this).find('img').map(function(){
return $(this).attr('src');
});
console.log(arr);
// result:
// ["16.png", "17.png", "19.png", "18.png"]
// ["0.png"]
// ["0.png"]
// []
// []
$.ajax({
type: "POST", url: "update.php",
data: arr
}).done(function(msg){
console.log(msg);
});
});
php
print_r($_POST);
js come back console.log
Array
(
[undefined] =>
)
Array
(
)
Array
(
)
Array
(
[undefined] =>
)
Why this does not work? How can i fix it?
Also, I tried to change the syntax in my ajax function data: {arr: arr} but this didn't work either.
Error message:
TypeError: Type error jquery-1.10.1.min.js:6
Found error line in jquery-1.10.1.min.js:6:
t = x.isFunction(t) ? t() : null == t ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t)

you haven't constructed proper key&value pair using your data, if you want to pass a raw stream of data then set processData: false and capture with php://input
var arr = $(this).find('img').map(function(){
return $(this).attr('src');
});
$.ajax({
type: "POST", url: "update.php",
data: arr,
processData: false,
}).done(function(msg){
console.log(msg);
});
on the php side
$data = file_get_contents("php://input");

You first need to call arr.get() to get the jquery.map result back as a regular javascript array. Then you can pass it to the ajax data paramter as:
data: { "images" : arr.get() }
So the full ajax call would look like this:
$.ajax({
type: "POST", url: "update.php",
data: { "images" : arr.get() }
}).done(function(msg){
console.log(msg);
});
You can then read the array back in php as:
$images = $_POST['images'];

Related

jQuery get json_encode variable from PHP

My PHP file retrieves data from a PostgreSQL DB. I have to send them back to my jQuery function in two different arrays. One is passed by using:
echo json_encode($tb);
and works fine, in my js file i get data correctly by using:
$.ajax({
type: "POST",
url: './DB/lb.php',
data: {d_p: oa},
success: function (tb) {
console.log(tb);
})
console output is as expected.
The other is always a PHP array, but I have to replace chars:
str_replace(array('[', ']'), '', htmlspecialchars(json_encode($ltb), ENT_NOQUOTES));
but if I write:
$.ajax({
type: "POST",
url: './DB/lb.php',
data: {d_p: oa},
success: function (tb, ltb) {
console.log(tb);
console.log(ltb);
})
console.log(ltb) simply outputs
success
what I'm I getting wrong?
The second parameter of succes is the response staus. This is the reason because you get success when logging tlb.
You can only return one JSON at at time, so combine them:
echo json_encode(array("other stuff", "tb" => $tb, "tbl" => array("some" => "data")));
On JS side you can simple acces them by index or key:
tb[0]; // "other stuff"
tb.tb; // content of $tb variable
tb.tbl; // {some: "data"}
The final working code:
PHP:
$tb = array();
$ltb = array();
while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
{
array_push($ltb, $row["x"], $row["y"]);
array_push($tb, $row["z"],$row["t"]);
}
echo json_encode(array('tb'=>$tb,'ltb'=>$ltb));
JS
$.ajax({
type: "POST",
url: './DB/lb.php',
dataType: 'json', // this is what I forgot!!!
data: {d_p: oa}, // passes variable for PHP function
success: function (response) {
console.log(response.tb+" "+ response.ltb);
$.each(response.tb, function( i, item ) {
// iterate over tb array
}
$.each(response.ltb, function( i, item ) {
// iterate over ltb array
}
});

JQuery returning undefined from PHP JSON string

I am trying this JQuery code:
val = $(this).val();
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "?getCustomer=1&sequence="+val+"",
data: data,
success: function(data) {
alert(data["sequence"]);
}
});
but the alert is returning undefined
if i check the URL (?getCustomer=1&sequence=4) i get this returned:
[{"sequence":"53"}]
so the sequence value is definately the
this is what shows in the console:
[Object]0: Objectsequence: "112"__proto__: Objectlength: 1__proto__: Array[0]concat: concat()constructor: Array()copyWithin: copyWithin()entries: entries()every: every()fill: fill()filter: filter()find: find()findIndex: findIndex()forEach: forEach()indexOf: indexOf()join: join()keys: keys()lastIndexOf: lastIndexOf()length: 0map: map()pop: pop()push: push()reduce: reduce()reduceRight: reduceRight()reverse: reverse()shift: shift()slice: slice()some: some()sort: sort()splice: splice()toLocaleString: toLocaleString()toString: toString()unshift: unshift()Symbol(Symbol.iterator): values()Symbol(Symbol.unscopables): Object__proto__: Object
You misunderstood your json. Change
alert(data["sequence"]);
With
alert(data[0]["sequence"]);
or better
alert(data[0].sequence );
[{"sequence":"53"}] is an array, the first element of which is an object with a sequence member. You need to alert(data[0]['sequence']).

Not displaying array count

I have number of checkboxes on my page and I want to get those checkbox values in my database.
$('#assign_data').on("click",function()
{
var mandate_array = [];
var i= 0;
$('.assign_mandate:checked').each(function(){
mandate_array[i++] = $(this).val();
});
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+mandate_array+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
});
assign_mandate.php :
<?php
$mandate = explode(',',$_POST['mandate_array']);
// print_r($mandate); //it shows the data in array
count($mandate);exit; // it does not show the count in console
?>
When I print the array it show me the array data in console but when I try to echo the count of array it shows blank. Why ?
Thanks in advance
You have to echo the variable count value.
<?php
$mandate = explode(',',$_POST['mandate_array']);
// print_r($mandate); //it shows the data in array
echo count($mandate);exit; // it does not show the count in console
?>
Use JSON.stringify.
You would typically convert the array to a JSON string with JSON.stringify, then make an AJAX request to the server, receive the string parameter and json_decode it to get back an array in the PHP side.
$('#assign_data').on("click",function()
{
var mandate_array = [];
var i= 0;
$('.assign_mandate:checked').each(function(){
mandate_array[i++] = $(this).val();
});
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+JSON.stringify(mandate_array)+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
});
mandate_array is Array so you wont posted array data in query string, you should use JSON.stringfy() function to convert array/JSON object into string.
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+JSON.stringfy(mandate_array)+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
In PHP code
var_dump(json_decode($_POST['mandate_array']));
Use echo in front of the count()

jquery won't accept json_encode() data

I'm using the following piece of code to send data from a form to a php script that will do some calculations using a class:
$.ajax({
type: "POST",
url: "test2.php",
data: values,
success: function(returnedData) {
$("#result").html(returnedData);
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});
My PHP script creates an array which I encode with JSON and then echo
$jsonString = array(
'monthText' => $Month->getMonthText($month),
'gross' => $formatGross,
'net' => $formatNet
);
echo json_encode($jsonString);
So far so good. But I'm not very keen on displaying the raw JSON. I'd like to format the text before it's written to the document. I've tried $.parseJSON() and $.getJSON() but none of them work.
The jQuery docs says it needs a string but isn't json_encode() making my array to a string? Isn't echo making it a string? Why am I getting the error Uncaught SyntaxError: Unexpected token { in my jQuery-file? My theory is that it doesn't have single quotes around it.
I've tried using header('Content-type: application/json') in my PHP script and I've also tried dataType: json in my AJAX POST but nothing is working.
What am I doing wrong?
From the comments it sounds like you are using json_encode wrong. Store each piece of data into an array and then encode the array.
$data = array();
for($i=0;$i<$something;$++) {
$data[] = array(
'monthText' => $Month->getMonthText($month),
'gross' => $formatGross,
'net' => $formatNet
);
}
echo json_encode($data);
Then your Javascript would need to be
$.ajax({
type: "POST",
url: "test2.php",
dataType:"json",
data: values,
success: function(returnedData) {
//returnedData will now be an array Object
for( var i=0; i<returnedData.length; i++ ) {
$("#result").html(returnedData[i].monthText);
}
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});
for parsing, use jQuery.parseJSON(returnedData);
Add dataType in your ajax call like this.
$.ajax({
type: "POST",
dataType:"json",
url: "test2.php",
data: values,
success: function(returnedData) {
$("#result").html(returnedData);
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});

Using jquery sortable with ajax and php

I am trying to use jQuery sortable and then save the changes to the database, however before I even get to updating the database I have something strange going on that I can't fathom. If I log the serialised data to the console, I get all items in the 'list' but if I echo out the json encoded array from the php script I only get one item - confused.com.
The jquery at the moment is:
$('#sortable-list').sortable({
//handle : '.handle',
update : function () {
var order = $(this).sortable('serialize');
var table = $(this).parent().attr('id');
console.log(order);
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: "order=" + order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
}
});
The PHP at the moment is:
if (isset($_POST['sort']) && $_POST['sort'] == 1) {
if ($_POST['sort_table'] == 'nationalities') {
$output = array();
$list = parse_str($_POST['order'], $output);
echo json_encode($output);
}
}
The console log gives me:
nationality[]=17&nationality[]=1&nationality[]=47&nationality[]=23&nationality[]=3&nationality[]=4&nationality[]=5&nationality[]=6&nationality[]=7&nationality[]=8&nationality[]=12&nationality[]=10&nationality[]=11&nationality[]=13&nationality[]=14&nationality[]=15&nationality[]=16&nationality[]=18&nationality[]=19&nationality[]=20&nationality[]=21&nationality[]=22&nationality[]=24&nationality[]=25&nationality[]=26&nationality[]=27 etc
And the echo json gives me:
Object {nationality: Array[1]}
nationality: Array[1]
0: "17"
length: 1
So for some reason the full array isn't being passed through to the PHP file and I can't work out why.
Your problem is that you are trying to assign a serialized array, to a single query string parameter, which will yield an incorrect query string. Try passing the serialized list as returned by the plugin serialize method like so:
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
And then access the passed list in php with:
$list = $_POST['nationality'];

Categories