Send multidimentional array from JQuery AJAX to PHP - javascript

i want to send a multidimensional array to PHP from JQuery AJAX, but it is receiving in PHP like this
Array
(
[recordid] => 38
[locations] => [object Object],[object Object]
)
i must be doing some stupid mistake. here is the code.
it gets records from a table and send to PHP
$(document).on('click','.savenow',function(){
recordid = $(this).data('id');
locations = [];
$('.selectrec').each(function () {
parent = $(this).parent().parent();
name = parent.find('td').eq(5);
address = parent.find('td').eq(6);
lat = parent.find('td').eq(1);
lng = parent.find('td').eq(2);
row = [name,address,lat,lng];
locations.push(row);
});
locations = locations.toString();
$.ajax({
type: "POST",
url:'/record/saveSearchedLocations',
data: { recordid: recordid,locations:locations },
dataType: 'json',
success: function (data) {
console.log(data);
},
error:function(data){
alert("something went wrong, please try again.");
}
});
});
and this is the PHP function where i am receiving the data:
function saveSearchedLocations(){
print_r($_POST);
}

Use JSON.stringify() instead of toString() like so:
Change your AJAX call to this:
$(document).on('click','.savenow',function(){
recordid = $(this).data('id');
locations = [];
$('.selectrec').each(function () {
parent = $(this).parent().parent();
name = parent.find('td').eq(5);
address = parent.find('td').eq(6);
lat = parent.find('td').eq(1);
lng = parent.find('td').eq(2);
row = [name,address,lat,lng];
locations.push(row);
});
ajaxData = { recordid : recordid,locations : locations }
$.ajax({
type: "POST",
url:'/record/saveSearchedLocations',
data: JSON.stringify(ajaxData),
dataType: 'json',
success: function (data) {
console.log(data);
},
error:function(data){
alert("something went wrong, please try again.");
}
});
});
JSON.stringify() converts your array to an actual json string as opposed to Array.prototype.toString() which joins your array (one level) using a comma as separator.

Take this answer as a reference:
I think you need to use JSON.stringify(selectedData) in order to use it on the serverside.
jQuery:
var obj = { 'risk_cat': risk_cat, 'risk_type': risk_type };
selectedData.push(obj);
$.post('serive.php', { DTO: JSON.stringify(selectedData) },
function(data){ /* handle response, */ });
service.php:
header('Content-type: application/json');
header('Cache-Control: no-cache, must-revalidate');
$foo = json_decode($_POST['DTO']);
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); //example data
echo json_encode($arr);
This should get you started. In your ajax reponse, alert(data.a) would be alerting "1"

sendAjax = function() {
var data = {
foo: 123,
bar: 456,
rows: [{
column1: 'hello',
column2: 'hola',
column3: 'bonjour',
}, {
column1: 'goodbye',
column2: 'hasta luego',
column3: 'au revoir',
}, ],
test1: {
test2: {
test3: 'baz'
}
}
};
$.ajax({
type: 'post',
cache: false,
url: './ajax/',
data: data
});
}
When the button is clicked, the following structured data shows up in PHP's $_POST variable:
Array
(
[foo] => 123[bar] => 456[rows] => Array(
[0] => Array(
[column1] => hello[column2] => hola[column3] => bonjour
)
[1] => Array(
[column1] => goodbye[column2] => hasta luego[column3] => au revoir
)
)
[test1] => Array(
[test2] => Array(
[test3] => baz
)
)
)
This will only work with jQuery 1.4.0+. Otherwise jQuery simply calls .toString() on the nested array at key "rows" and nested object at key "test1", and they get passed to PHP with the useless values "[object Object
here is the link u can check here
https://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/

Put your data in a form and send form data with serializeArray()

Related

Get tag, custom taxonomy and attachment data from get_pages function

I currently have some code which retrieves all pages submitted by the currently logged in author using the get_pages function. I am then passing the result to Javascript via Ajax. Everything works as expected, and I'm retrieving the pages that I should be.
My issue is, the object does not have any data for the tags, other custom taxonomies and attachments on this page.
Is there a way to attach this data to the returned object?
functions.php:
function get_ajax_pages()
{
// Query Arguments
$args = array(
'authors' => $author,
'post_type' => 'page',
'post_status' => array('publish', 'pending'),
'hierarchical' => 0
);
// The Query
$ajaxpages = get_pages($args);
echo json_encode($ajaxpages);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_pages', 'get_ajax_pages');
add_action('wp_ajax_nopriv_get_ajax_pages', 'get_ajax_pages');
Javascript:
var adminAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
// the list of pages by the current author
var pageList = [];
// get an array of the current author's pages
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { action: 'get_ajax_pages' },
success: function (response) {
pageList = response;
}
});
At this point, each entry will return something like:
ID: 100
comment_count: "0"
comment_status: "open"
filter: "raw"
guid: "https://example.com/?page_id=100"
menu_order: 0
ping_status: "closed"
pinged: ""
post_author: "1"
post_content: "This is the post content"
post_content_filtered: ""
post_date: "2021-06-18 10:00:00"
post_date_gmt: "0000-00-00 00:00:00"
post_excerpt: "This is the excerpt"
post_mime_type: ""
post_modified: "2021-06-18 10:00:00"
post_modified_gmt: "0000-00-00 00:00:00"
post_name: ""
post_parent: 19
post_password: ""
post_status: "pending"
post_title: "Example page"
post_type: "page"
to_ping: ""
I would like it to also include data along the lines of:
tags: "example, test"
myCustomTaxonomy: "extra information, more data"
attachments: "https://example.com/wp-content/uploads/2021/06/myImage.png"
Is this possible?
In case it's useful, this is the solution I came up with. It certainly may not be efficient but it appears to suit my purposes at least.
What I ended up doing was populating a select list with each of the pages found in the first AJAX call. Selecting a page in this list then calls the second function which gets the various extra metadata for that page.
functions.php:
function get_ajax_pages()
{
// Query Arguments
$args = array(
'authors' => $author,
'post_type' => 'page',
'post_status' => array('publish', 'pending'),
'hierarchical' => 0
);
// The Query
$ajaxPages = get_pages($args);
echo json_encode($ajaxPages);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_pages', 'get_ajax_pages');
add_action('wp_ajax_nopriv_get_ajax_pages', 'get_ajax_pages');
function get_ajax_meta()
{
$editId = $_POST['editId'];
$meta = [];
$editTags = get_the_tags($editId);
$editCustomTaxonomy1 = get_the_terms($editId, 'CustomTaxonomy1');
$editCustomTaxonomy2 = get_the_terms($editId, 'CustomTaxonomy2');
$media = get_attached_media('', $editId);
array_push($meta, (object)[
'tags' => $editTags,
'customTaxonomy1' => $customTaxonomy1,
'customTaxonomy1' => $customTaxonomy2,
'media' => $media
]);
echo json_encode($meta);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_meta', 'get_ajax_meta');
add_action('wp_ajax_nopriv_get_ajax_meta', 'get_ajax_meta');
Javascript:
var adminAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
// the list of pages by the current author
var pageList = [];
// get an array of the current author's pages
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { action: 'get_ajax_pages' },
success: function (response) {
pageList = response;
// populate the dropdown with the pages
if (pageList.length > 0) {
for (var i = 0; i < pageList.length; i++) {
$("select[name=edit-page]").append("<option value='" + pageList[i].ID + "'>" + pageList[i].post_title + "</option>");
}
}
}
});
$("body").on("change", "select[name=edit-page]", function () {
editId = $(this).val();
// get the meta information of the selected page (tags, custom taxonomies, attached files)
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { "editId": editId, action: "get_ajax_meta" },
success: function (response) {
pageMeta = response;
// get the tags
console.log(pageMeta[0].tags[i].name)
// get custom taxonomy 1 data
console.log(pageMeta[0].customTaxonomy1[i].name)
// get custom taxonomy 2 data
console.log(pageMeta[0].customTaxonomy2[i].name)
// get attached file data
if (Object.keys(pageMeta[0].media).length > 0) {
for (var i = 0; i < Object.keys(pageMeta[0].media).length; i++) {
console.log(pageMeta[0].media[Object.keys(pageMeta[i].media)[0]]);
}
}
}
});
});

Send an JS array through Ajax

I've this type of array in JS:
[{
websitetype: "onepager"
}, {
layout: "provided"
}, {
layout_provided: "wireframes"
}, {
languages: "single"
}, {
client_name: "dasda"
}, {
client_email: "asdasd#asdasd.fr"
}, {
client_conditions: "on"
}, {
client_newsletter: "on"
}]
How can I send it through Ajax ?
What I tried is:
$.ajax({
type: 'POST',
url: 'assets/send.php',
data: {datas},
success: function(response) { },
});
This is what I would like to get in PHP:
[datas] => Array
(
[websitetype] => onepager
[layout] => provided
[layout_provided] => wireframes
[languages] => single
[client_name] => dasda
[client_email] => asdasd#asdasd.fr
[client_conditions] => on
[client_newsletter] => on
)
What I'm missing here please ?
Thanks.
The first thing you should do is reduce that array into an object matching the format you want
const dataObject = Object.fromEntries(datas.flatMap(o => Object.entries(o)))
This looks like the following
{
"websitetype": "onepager",
"layout": "provided",
"layout_provided": "wireframes",
"languages": "single",
"client_name": "dasda",
"client_email": "asdasd#asdasd.fr",
"client_conditions": "on",
"client_newsletter": "on"
}
You then have two options for posting it to PHP
Send it as raw JSON
$.ajax({
method: "POST",
url: "assets/send.php",
contentType: "application/json",
data: JSON.stringify(dataObject),
processData: false
})
Then read and parse the JSON in PHP
$datas = json_decode(file_get_contents("php://input"), true);
// example
echo $datas["websitetype"]; // "onepager"
Alternatively, let jQuery format the data as an associative PHP array
$.ajax({
method: "POST",
url: "assets/send.php",
data: {
datas: dataObject
}
})
This will post an application/x-www-form-urlencoded request body of
datas%5Bwebsitetype%5D=onepager&datas%5Blayout%5D=provided&datas%5Blayout_provided%5D=wireframes&datas%5Blanguages%5D=single&datas%5Bclient_name%5D=dasda&datas%5Bclient_email%5D=asdasd%40asdasd.fr&datas%5Bclient_conditions%5D=on&datas%5Bclient_newsletter%5D=on
PHP can read this as an array via $_POST
print_r($_POST['datas']);
Results in
Array
(
[websitetype] => onepager
[layout] => provided
[layout_provided] => wireframes
[languages] => single
[client_name] => dasda
[client_email] => asdasd#asdasd.fr
[client_conditions] => on
[client_newsletter] => on
)
Encode your data string into JSON.
const datas = [{
websitetype: "onepager"
}, {
layout: "provided"
}, {
layout_provided: "wireframes"
}, {
languages: "single"
}, {
client_name: "dasda"
}, {
client_email: "asdasd#asdasd.fr"
}, {
client_conditions: "on"
}, {
client_newsletter: "on"
}]
const jsonString = JSON.stringify(datas)
$.ajax({
type: 'POST',
url: 'assets/send.php',
data: { datas: jsonString },
success: function(response) { },
});
In your PHP:
$data = json_decode(stripslashes($_POST['datas']));
// here i would like use foreach:
foreach($datas as $data){
echo $data;
}

PHP & JavaScript - Variables

I just basically have a View with an Associative Array with Accidents Information.
The User will be able to click in the Country. When that happen I want to show them the information about accidents related with that country.
That information comes from PHP and the Click event is captured in JQuery...
How Can I insert the var country inside the index of the
associative array that came from PHP with an Index for each country?
.on('click', function(i, row) {
var country = row.label;
accident_chart.setData([{
a: <?php echo "".$charts['accidents_status'][**NEED var country value here**]['accidents']; ?>,
y: 'Accidents',
},
{
a: <?php echo $charts['accidents_status']['Qatar']['lost_time_accidents']; ?>,
y: 'Lost Time',
}
]);
});
You can't do that. Use AJAX instead to get the accident_chart data.
.on('click', function(i, row) {
var country = row.label;
$.ajax({
type: "GET",
url: "/get_accident_chart", // Just replace it with your PHP controller function that can access your $charts variable
data: {country: row.label},
dataType: "json",
success: function(data) {
accident_chart.setData(data);
},
error: function(data) {
return data;
}
});
});
In your PHP
get_accident_chart(){
$country = $_GET['country'];
$accident_chart = array(
array(
'a' => $charts['accidents_status'][$country]['accidents'],
'y' => 'Accidents'
),
array(
'a' => $charts['accidents_status']['Qatar']['lost_time_accidents'],
'y' => 'Lost Time'
)
);
echo json_encode($accident_chart);
}

cannot receive json from server through php

i cannot get the json from php on sever
the javascript code is:
$.ajax({
type: "POST",
url: "doingSQL.php",
data: label,
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
the job of doingSQL.php is selecting bookName from SQL database and convert the data to json. it look like this:
/* the server connecting code is omitted */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$label = $_POST["label"];
}
$sql = "SELECT * FROM book WHERE ower = '". $label."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Arr = array("id" => $row["book_id"],
"bookName" => $row["bookName"]);
$bookDetail[] = array( "book".$i => $Arr);
}}
}
mysqli_close($conn);
$json = array("mybook" => $bookDetail);
echo json_encode($json);// return json
but the result i got in the html console is "[ ]" or array[0].
the json is valid json format, it is look like:
{
"mybook":[
{
"book0":{
"id":"0",
"bookName":"bookA"
}
},
{
"book1":{
"id":"1",
"bookName":"bookB"
}
}
]
}
however, if the code is outside the SQL connection in php. the json returning will success.
it is look like:
/* the server connecting code is omitted */
mysqli_close($conn);
// if outside the SQL connection
$ArrA = array("id" => "0", "bookName" => "bookA");
$ArrB = array("id" => "1", "bookName" => "bookB");
$bookDetail[] = array( "book0" => $ArrA);
$bookDetail[] = array( "book0" => $ArrB);
$json = array("mybook" => $bookDetail);
echo json_encode($json);// return json success
any idea?
Just pass your ajax data as :
data: {label:label}
The data property of the ajax settings can be type of PlainObject or String or Array. For more reference see this http://api.jquery.com/jquery.ajax.
So your javascript code would be like this :
$.ajax({
type: "POST",
url: "doingSQL.php",
data: {label: label},
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
You need to pass the label value in a variable. Now since on the PHP page you are using $_POST['label'], so pass the variable like this :
data: {label: label},
So your complete ajax code would look like :
$.ajax({
type: "POST",
url: "doingSQL.php",
data: {label: label}, // changed here
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});

How do I call a JSON object?

I am having a problem calling a specific object. For example, I want to call mydata.title
I have the ff inside my php (this is just part of the code)
while($row = $DB->result->fetch_assoc()){
$Fthis[] = array(
"title" => $row["title"],
"subtitle" => $row["subtitle"],
"dates" => $row["dates"],
"Author" => $row["Author"],
"content" => $row["content"],
"himgsrc" => $row["himgsrc"]
);
array_push($marxarray, $Fthis);
}
echo json_encode($marxarray);
And then I have this AJAX in my js.
$.ajax({
url: 'editer.php',
type: 'POST',
data: { id: blogid },
success: function (data) {
var mydata= JSON.parse(data);
console.log(mydata);
alert(mydata.title);
}
});
Why does the alert return undefined ??
If I look at the log, I can see that the array has been passed correctly so no problem with the php (i think).
here's how it looks like anyway.
I checked your image, you have to use array index for that
mydata[0][0].title
success: function (data) {
var mydata= JSON.parse(data); // mydata is JSON array
}

Categories

Resources