retrieve data using json and jquery ajax call no work - javascript

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.

Related

Passing value to php from local storage using Ajax

I.m want to pass the values from js to php that is stored in local storage
js
let cartItems = localStorage.getItem("productsInCart");
var jsonString = JSON.stringify(cartItems);
$.ajax({
url:"read.php",
method: "post",
data: {data : jsonString},
success: function(res){
console.log(res);
}
})
php
<?php
print_r($_POST)
?>
on .php im getting just "array ()"
using #reyno's method with all the code in the same file called 'store_user_order.php'
<?php
if(isset($_POST["data"])) {
print_r($_POST["data"]);
} else {
?>
<button>SEND</button><br/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"> </script>
<script>
const cartItems = localStorage.getItem("productsInCart");
const jsonString = JSON.stringify(cartItems);
$("button").click(function() {
$.ajax({
url: 'store_user_order.php',
method: 'post',
data: {
data: jsonString
},
success: function(res) {
$('body').append(res);
},
error: function(err) {
$('body').append(err);
}
});
})
</script>
<?php } ?>
This should work if you have items in the localstorage
While testing, for checking values use method: "get", make sure that your test values aren't huge - you will see submitted values in the address bar.
For testing (php + MySQL) I always use this method:
success ? changes() : errors_list();`
I don't use js, so deal with syntax yourself, please.
on .php im getting just "array ()"
You received an empty $ _POST array - nothing was sent.
Because there was nothing to send, or there was an error sending

ajax - sending data as json to php server and receiving 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 },

$_POST empty after ajax post called

So the purpose of me using this ajax post is to use some JS variables in a wordpress loop, so I can call a custom loop depending on what the variables are in the ajax post.
Below is the ajax call.
$('.collection-more').click(function() {
$.ajax({
type: 'post',
url: 'http://tmet.dev/wp-content/themes/muban-trust/single-collection.php',
data: { "test" : "hello" },
success: function( data ) {
console.log( data );
}
});
})
Currently I'm sending hard-coded data.
In my single-collection.php page:
<?php
print_r($_POST);
if(isset($POST['filters[Artist]']))
{
$filters_obj = $_POST['filters[Artist]'];
$filters_array = json_decode($filters_obj, TRUE);
for($i = 0; $i < sizeof($filters_array); $i++)
{
echo '<p>h'.$obj->name.'</p>';
}
}
?>
I'm using the print_r just to debug the problem, currently it returns:
Array()
The problem is that I cannot access the Json object called "test" within the single-collection.php
How do I access it?
Thanks in advance!
EDIT: Screenshot of firebug
From ajax to php :
this is the conventional way
var payload = {
smth1: "name",
smth2: "age"
};
and then when calling ajax
$.ajax({
url: "somephp.php",
type: 'POST',
data: payload,
dataType: 'json',
crossDomain: true
})
From phpPost to javascript:
right way getting the post parameters:
$fields = $_POST['fields'];
$usernameGiven = $fields['smth1'];
$passwordGiven = $fields['smth2'];
and when returning smthn to javascript
$result = array(
"something" => "something",
"something2" => $something2
);
echo json_encode($result);
Use $_POST['test'] to access the test parameter. Your print_r() shows that it is filled in correctly.
Your PHP code is accessing $_POST['filters[Artist]'] but there is no such parameter in the Javascript. If you pass:
data: { 'filters[Artist]': somevalue }
you can access it in PHP as $_POST['filters']['Artist'].

What's wrong with this jQuery Ajax/PHP setup?

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
}
});
}

ajax to pass array value , how to fetch array on called page

I have array containg image path ,
GenerateReport[0] ="../images/Desert1.jpg"
GenerateReport[1] ="../images/Desert2.jpg"
GenerateReport[2] ="../images/Desert3.jpg"
GenerateReport[3] ="../images/Desert4.jpg"
GenerateReport[4] ="../images/Desert5.jpg"
I am trying to pass this array with following code,
$.ajax({
type: "POST",
url: "generatePdf.php",
data: {
genRep: "sample value"
},
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
sample value is passed successfully , but how can i pass array to ajax and use it on another page?? i tried passing array and using with below code but it is not working
$data1 = $_REQUEST['genRep'];
echo "tested".$data1[0];
Try like
genRep = [];
$.ajax({
type: "POST",
url: "generatePdf.php",
data: {
genRep: GenerateReport
},
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
It will send your array as genRep
try to use json object. in object you can store your images path
var data=[]; // array
var data[0] = 'something';
var data[1] = 'something1';
var data = { 'name': name, 'email' : email, 'contact' : contact, 'type' : type, 'msg' : msg }; // object
$.ajax({
url : 'contact.php',
type : 'POST',
data : {contact:JSON.stringify(data)}, // for json object
data : {contact: data}, // for array
success : function (msg)
{
alert(msg);
}
})
contact.php
$info = $_POST['contact'];
$info = json_decode($info,true); // for json object
echo $info.name; // for json object
echo $info[0]; // will print something...
$arr = array();
$arr[0] = "Mark Reed";
$arr[1] = "34";
$arr[2] = "Australia";
echo json_encode ($arr);
use this on the php page
and use the following to get the output
success:function(msg){
id_numbers = JSON.parse(msg);
alert(id_numbers)
}
Try:
$.ajax({
url: "generatePdf.php",
type: 'POST',
data: form_data,
dataType:"json",
success: function(data) {
alert(data[0]);
}
On the PHP side, you'll be wanting to print:
print json_encode($photos);
Made Some Change
print json_encode(array("photolist"=>$photos));
Then on the server, you'd access these with:
data.photolist[0]; //First photo
I have tested it, this will definitely work !
JS:
var GenerateReport = [];
GenerateReport[0] ="../images/Desert1.jpg";
GenerateReport[1] ="../images/Desert2.jpg";
GenerateReport[2] ="../images/Desert3.jpg";
GenerateReport[3] ="../images/Desert4.jpg";
GenerateReport[4] ="../images/Desert5.jpg";
$.ajax({
type: 'POST',
url: 'generatePdf.php',
data: 'image_array='+GenerateReport,
success: function(msg) {
alert(msg);
}
});
generatePdf.php :
<?php
$image_string = $_POST['image_array'];
$image_array = explode(",", $image_string);
print_r($image_array);
?>
Then you can loop over the $image_array to get the values.
try this
GenerateReport[0] ="../images/Desert1.jpg"
GenerateReport[1] ="../images/Desert2.jpg"
GenerateReport[2] ="../images/Desert3.jpg"
GenerateReport[3] ="../images/Desert4.jpg"
GenerateReport[4] ="../images/Desert5.jpg"
corrected code:
var imagedata = '';
$.each(GenerateReport,function(index,value))
{
if(imagedata=='')
{
imagedata = imagedata +'image'+index+'='+value;
}
else
{
imagedata = imagedata +'&image'+index+'='+value;
}
});
$.ajax({
type: "POST",
url: "generatePdf.php",
data: imagedata //pass string imagedata
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
imagedata should have sting like this:
image1=../images/Desert1.jpg&image2=../images/Desert2.jpg and so on
if(isset($_REQUEST['genRep']))
{
$data = $_REQUEST['genRep'];
print_r($data1);
echo "tested".$data1[0];
createPdf($data);
}
My code was correct , there was no value on index 0 , thats why it was not printing anything .My Mistake !!!

Categories

Resources