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
}
Related
I have a custom database that I want to insert items into from a WordPress front-end interface. When I submit the form, I can get the JSON values just fine, but for some reason, it doesn't seem to be inserting into the database. I do not get any error messages.
Here's what I'm doing (please note that I am testing the name variable, hence why it's not pulling from an input field):
I am using the auto_increment_id value from SHOW TABLE STATUS to create the commmittee_id value, and would prefer for that to be inserted as the primary key.
JavaScript
$(".addButton").click(function() {
var commitAddID = $(this).attr('id');
var name = "1name";
var date_created = $("#addCommCreated_input_"+commitAddID).val();
var status = $("#addCommStatus_input_"+commitAddID).val();
var disbanded = $("#addCommDisbanded_input_"+commitAddID).val();
var dataString = {
'action': 'addCommittee',
'committee_id': commitAddID,
'old_id': commitAddID,
'name': name,
'description': '',
'date_created': date_created,
'status': status,
'disbanded': disbanded
};
jQuery.ajax({
url: addCommittee.ajaxurl,
type: "POST",
data: dataString,
dataType: "json",
success: function (response) {
$("#name_"+commitAddID).html(name);
$("#created_"+commitAddID).html(date_created);
$("#status_"+commitAddID).html(status);
$("#disbanded_"+commitAddID).html(disbanded);
}
});
functions.php
// set up AJAX call for addCommittee
add_action('wp_ajax_addCommittee', 'addCommittee');
add_action('wp_ajax_nopriv_addCommittee', 'addCommittee');
function addCommittee() {
global $wpdb;
$committee_id = esc_sql($_POST['committee_id']);
$old_id = esc_sql($_POST['old_id']);
$name = esc_sql($_POST['name']);
$created = esc_sql($_POST['date_created']);
$status = esc_sql($_POST['status']);
$disbanded = esc_sql($_POST['disbanded']);
$desc= esc_sql($_POST['description']);
$wpdb->insert('wp_bubu_committees',
array(
'old_id' => '',
'name' => $name,
'description' => '',
'date_created' => $created,
'status' => $status,
'disbanded' => $disbanded
)
);
exit();
}
I have also localized the AJAX URL in functions.php. Any ideas?
Edit: Updated the code-- the action was set to the . I now am able to insert into the database, but it only allows me to insert one item. Attempting to insert additional items returns nothing, but the data does post to JSON.
Remove the data type json.
jQuery.ajax({
url: addCommittee.ajaxurl,
type: "POST",
data: dataString,
success: function (response) {
$("#name_"+commitAddID).html(name);
$("#created_"+commitAddID).html(date_created);
$("#status_"+commitAddID).html(status);
$("#disbanded_"+commitAddID).html(disbanded);
alert(response);
}
});
I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },
I'm triyng to retrieve JSON format data using $.ajax method of jquery from a php page, I get this error parseerror when the code runs, but if I see the response of the server with firebug it's Ok.
Here's my script code:
$.ajax({
url: "php/selectedObjectRequest.php",
type: "POST",
dataType: 'json',
data: {},
success: function(data) {
var prova = jQuery.parseJSON(data);
alert(prova.museum);
},
error: function(jqXHR,textStatus,errorThrown) {
alert(textStatus);
}
});
And that's my server side code:
$arrayToEncode = array(
'museum' => 'bellearti',
'atwork' => 'davide',
'beaconCode' => '78888',
'qrCode' => '2252222'
);
echo json_encode($arrayToEncode);
How I can solve?
solved:
My error was an echo to test before
echo json_encode($arrayToEncode);
pay attention.
The parameter data in your success handler will be preprocessed because you told jQuery that the dataType was JSON. You should be able to just use data.museum. To make sure, console.log(data); to see what it is.
the answer is:
change prova.museum to data.museum
$.ajax({
url: "php/selectedObjectRequest.php",
type: "POST",
dataType: 'json',
data: {},
success: function(data) {
alert(data.museum); // add data.museum instant of prova.museum
},
error: function(jqXHR,textStatus,errorThrown) {
alert(textStatus);
}
});
FIDDLE
Change the format
$arrayToEncode[] = array(
'museum' => 'bellearti',
'atwork' => 'davide',
'beaconCode' => '78888',
'qrCode' => '2252222');
echo json_encode($arrayToEncode, JSON_UNESCAPED_UNICODE);
So that you can call the return value like
for (var j = 0; j < data.length; j++) {
console.log(data[j].museum);
console.log(data[j].atwork);
console.log(data[j].beaconCode);
console.log(data[j].qrCode);
}
Try using this:
var parsed = JSON.parse(data);
This usually works for me.
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()
I'm building a search app which uses Ajax to retrieve results, but I'm having a bit of trouble in how exactly to implement this.
I have the following code in Javascript:
if (typeof tmpVariable == "object"){
// tmpVariable is based on the query, it's an associative array
// ie: tmpVariable["apple"] = "something" or tmpVariable["orange"] = "something else"
var sendVariables = {};
sendVariables = JSON.stringify(tmpVariable);
fetchData(sendVariables);
}
function fetchData(arg) {
$.ajaxSetup ({
cache: false
});
$.ajax ({
type: "GET",
url: "script.php",
data: arg,
});
}
And within script.php:
<?php
$data = json_decode(stripslashes($_GET['data']));
foreach($data as $d){
echo $d;
}
?>
What is it that I'm doing wrong?
Thanks.
Your PHP script is expecting a GET var called 'data'. With your code you're not sending that.
Try this:
if (typeof tmpVariable == "object"){
var data = {data : JSON.stringify(tmpVariable)}; // Added 'data' as object key
fetchData(data);
}
function fetchData(arg) {
$.ajax ({
type: "GET",
url: "script.php",
data: arg,
success: function(response){
alert(response);
$("body").html(response); // Write the response into the HTML body tag
}
});
}