I want to copy json object to javascript array,
{
"profiledata1":{"id":0,"music":0,"image_x":130,"image_y":155,"mouth_x":0,"mouth_y":-28.125,"active":true,"default":false},
"profiledata2":{"id":1,"music":0,"image_x":130,"image_y":155,"mouth_x":0,"mouth_y":0,"active":true,"default":false},
"profiledata3":{"id":2,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"profiledata4":{"id":3,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"profiledata5":{"id":4,"music":0,"image_x":0,"image_y":0,"mouth_x":0,"mouth_y":0,"active":false,"default":false},
"upload":"http:\/\/localshost\/",
"format":"jpeg","status":1 }
This is my json object returned when i call some.php through ajax,
I want to copy profiledata1 to userdata_arr[0],profiledata2 to userdata_arr[1],profiledata3 to userdata_arr[2],profile4data to userdata_arr[3],profiledata5 to userdata_arr[5] in java script.
My java script is as follows,
$.ajax({
type: "POST",
url: "some.php",
data: {action:'load',
id:7}
}).done(function(o) {
var data = $.parseJSON(o);
if (!data || data === null) {
someError(true);
}else{
if(data.status==true){
userdata_arr[0] = data.profiledata1[0];
userdata_arr[1] = data.profiledata2[0];
userdata_arr[2] = data.profiledata3[0];
userdata_arr[3] = data.profiledata4[0];
userdata_arr[4] = data.profiledata5[0];
uploadDir = data.upload;
imgFormat = data.format;
somefunction();
}else{
someError(true);
}
}
});
when i execute this script i'm getting userdata_arr as undefined! Please help me to rectify this problem.
I'm also attaching the some.php here,
<?php
if ($_POST['action']=='load') {
$uid=$_POST['id'];
header("content-type:application/json");
// fetch contents from db with $uid;
$query = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($query)) {
$prof1 = $row['prof1'];
$prof2 = $row['prof2'];
$prof3 = $row['prof3'];
$prof4 = $row['prof4'];
$prof5 = $row['prof5'];
}
$jp1 = json_decode($prof1, 1);
$jp2 = json_decode($prof2, 1);
$jp3 = json_decode($prof3, 1);
$jp4 = json_decode($prof4, 1);
$jp5 = json_decode($prof5, 1);
echo json_encode($dta = array('profile1data' =>json_decode($prof1),'profile2data' =>json_decode($prof2),'profile3data' =>json_decode($prof3),'profile4data' =>json_decode($prof4),'profile5data' =>json_decode($prof5) ,'upload' =>'http://localhost/img/', 'format' =>'jpeg', 'status' =>1 )); ?>
Thanks in advance!
That's because you haven't declared your userdata_arr. To fix it, declare your array/object variable before using it. In your else code-block, do this:
else{
var userdata_arr = {}// declare your object
if(data.status==true){ //proceed to use your already-declared object, also notice the quote marks surrounding the object members/indexes
userdata_arr["0"] = data.profiledata1[0];
userdata_arr["1"] = data.profiledata2[0];
userdata_arr["2"] = data.profiledata3[0];
userdata_arr["3"] = data.profiledata4[0];
userdata_arr["4"] = data.profiledata5[0];
uploadDir = data.upload;
imgFormat = data.format;
somefunction();
}else{
someError(true);
}
}
Related
I am trying to display all records using jason in php.
but display all filed with null value.
I'm using postman for testing purpose.
I don't know what is the problem with that code. I getting null value only.
here is my code :
<?php
header('Content-Type: application/json');
$checkFields = "";
$REQUEST = $_SERVER['REQUEST_METHOD'];
if ($REQUEST == "POST")
{
include "DB/db.php";
$userlist = mysql_query("SELECT * FROM reg_services");
if(mysql_num_rows($userlist) > 0)
{
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
$json = array("success" => 1, "All_User_List" => $ph);
$jsonarray = json_encode($json);
}
}
else
{
$json = array("success" => 0, "message" => "Invalid Request Type(Use POST Method)");
$jsonarray = json_encode($json);
}
echo $jsonarray;
?>
please help me if you are know what is the error in code.
just replace this code with old one
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_array($userlist))
{
$ph[$p] = array();
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
You need to tell PHP about arrays
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p] = array(); // let PHP know it is an array
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
just replace this while loop condition with olde one.
while($userlistdata = mysql_fetch_array($userlist))
now it's work
I've seend much assistance for everything BUT transforming data when using the findBy query.
What I want is a json string of the resulset from this query ensuring that the objects are serialized so i can use this somewhere else:
$posts = $entityManager->getRepository(\Application\Entity\Post::class)
->findBy(['status'=>\Application\Entity\Post::STATUS_PUBLISHED],
['dateCreated'=>'DESC']);
Json::encode($posts,true) from Zend Framework Json but the data is not showing up when i do this.
The result will be a json encoded string with the entity objects that i can pass somewhere else
I will use for the decoding:
\Zend\Json\Decoder::decode($posts,\Zend\Json\Json::TYPE_OBJECT)
UNLESS I should be using \Zend\Json\Json::TYPE_ARRAY)
Here is the way I do it :
include : use Zend\Json\Json;
here is my example of function / action :
public function getListAction(){
$request = $this->getRequest();
if($request->isPost()){
// recuperer le produit choisi :
$element = $request->getPost("element");
$result = null;
$result = $this->getEntityManager()->getRepository('Application\Entity\Element')->findBy(array('etat' => 'valide' , 'pkElement' => $element));
$champs = array();
$i = 0;
foreach ($result as $value) {
$champs[$i] = array("id"=>$value->getPkElement() , "nom"=>$value->getNom());
$i++;
}
$data = array(
'result' => true,
'data' => $champs
);
return $this->getResponse()->setContent(Json::encode($data));
}
}
Then the call in the view.phtml :
$.post('/application/controller_name/getList', {element: $("select[name=element]").val()}, function(result) {
var options = $("select[name=element]");
var obj = JSON.parse(result);
var data = obj.data;
var selected = "";
options.empty();
for (var i = 0; i < data.length; i++) {
options.append($("<option />").val(data[i]['id']).text(data[i]['nom']));
}
});
Hope it helps.
I am using the MODX cms to output data from a third party, and I am stumped on how to return a nested array, currently I am only getting it to return the first array or NULL. Here is a sample of the code I am using:
$datastream = '[{"id":57,
"offer_info":{"offer_headline":"Main Offer Headline",
"published_title":"Displayed Main Title"},
// My issue is here with the nested array
"service_categories":[{"service_category_code":"D",
"headline":"My Headline for D",
"midline":"Middle copy",
"footline":"Footer copy for D"},
{"service_category_code":"T",
"headline":"My Headline for T",
"image":"image.svg",
"footline":"Footer copy for T"}]}]';
$output_json = json_decode($datastream);
$output_json = json_decode($datastream, true); // this returns null for everything
foreach($output_json as $component) {
$productid = $component->id; // this returns ok
$offer_headline = $component->offer_info->offer_headline; // this returns ok
$published_title = $component->offer_info->published_title; // this returns ok
$service_categories_category_code = $component->service_categories[0]->service_category_code; // this only returns first value
$service_categories_category_code = $component->service_categories->service_category_code; // this returns NULL
var_dump($service_categories_category_code);
I am able to take the values that return ok and place them in my code, but the nested array is only returning the first value, and I'm not sure if I am doing this correctly:
if ($service_categories_category_code = "D") {
$d_details_headline = $component->service_categories[0]->headline;
$d_details_midline = $component->service_categories[0]->midline;
$d_footline = $component->service_categories[0]->footline;
} elseif ($service_categories_category_code = "T") {
$t_details_headline = $component->service_categories[0]->headline;
$t_details_image = $component->service_categories[0]->image;
$t_details_footline = $component->service_categories[0]->footline;
};
Thank you very much in advance for any help
Hope this helps You :
<?php
$datastream = '[{"id":57,"offer_info":{"offer_headline":"Main Offer
Headline","published_title":"Displayed Main
Title"},"service_categories":[{"service_category_code":"D",
"headline":"My Headline for D","midline":"Middle
copy","footline":"Footer copy for D"},{"service_category_code":"T",
"headline":"My Headline for T",
"image":"image.svg",
"footline":"Footer copy for T"}]}]';
$output_json = json_decode($datastream);
//$output_json = json_decode($datastream, true); // this returns null for everything
$data = array();
foreach($output_json as $component) {
$productid = $component->id; // this returns ok
$offer_headline = $component->offer_info->offer_headline; // this returns ok
$published_title = $component->offer_info->published_title; // this returns ok
$data['productid'] = $component->id;
$data['offer_info']['offer_headline'] = $component->offer_info->offer_headline;
$data['offer_info']['published_title'] = $component->offer_info->published_title;
foreach ($component->service_categories as $comp) {
if ($comp->service_category_code == 'D') {
$data['D']['service_category_code'] = $comp->service_category_code;
$data['D']['headline'] = $comp->headline;
$data['D']['midline'] = $comp->midline;
$data['D']['footline'] = $comp->footline;
} elseif ($comp->service_category_code == 'T') {
$data['T']['service_category_code'] = $comp->service_category_code;
$data['T']['headline'] = $comp->headline;
$data['T']['image'] = $comp->headline;
$data['T']['footline'] = $comp->footline;
}
}
print_r($data);
}
I have a function that connects to Mysql DB that works great in a "normal" call, but fails to connect in response to ajax call.
The php code:
// return data to ShowDdl()
function getDDLdata($tablename) {
global $db;
$data = '';
$name = ($tablename == 'sapak' || $tablename == 'cupon' ? 'Name' : 'Hebrewname');
////****** $db IS NOT RECOGNIZED WHEN CALLING ShowDdl() FROM AJAX
////****** BUT WORKS GREAT IN NORMAL CALLS
$query = $db->select("SELECT `id` , `".$name."` AS name FROM `".$tablename."` ORDER BY `id` ASC");
for($i=0;$result = $db->get_row($query, 'MYSQL_ASSOC');$i++){
$data[$i] = $result;
}
return $data; // id, name
}
// echo ddl with current data from requested table
function ShowDdl($tablename, $sapakid = null) {
$possibletables = array (
'category', 'subcategory', 'brand', 'sapak', 'cupon'
);
$ddlname = '';
// find the correct name for the ddl
for ($i = 0; $i<count($possibletables); $i++) {
if ($possibletables[$i] == $tablename) {
// only cupon ddl should have different id and name
if ($tablename == 'cupon') {
$ddlname = 'sapak-'.$sapakid .'-cupon';
}
else {
$ddlname = 'product-' . $tablename;
}
continue;
}
}
echo '<select multiple id="'.$ddlname.'" name="'.$ddlname.'[]">';
$data = getDDLdata($tablename);
foreach ($data as $vn ) {
if ($vn['id'] != null) {
echo '
<option value="'.$vn['id'].'"> '.$vn['name'].' </option>
';
}
}
echo '</select>';
}
It works great when called from 'normal' php.
The ajax call:
$.ajax({
type: "GET",
url: 'moudels/product/generic_offer.php',
data: 'sid=' + sid + '&name=' + name,
success: function (data) {
$('<div id='+ sid + '> </div>').appendTo('#genericofferdiv');
// append the response to the new div
$("#"+sid).html(data);
}
});
I get this error:
Fatal error: Call to a member function select() on a non-object
I'm sure it it because the ajax call, maybe it can't load the global $db var correctly. Any ideas how I solve this?
Thank you very much
*Note: I know that I should use mysqli, but the whole project is build with this and I can't change it
When you call / include this file from within your php project, you probably defined somewhere the global variable $db and can access it in this file, too.
But if you call this from you website, all the php has run through and no global variable exist anymore...
-> So you have to include f.e. the config.php where you defined your $db variable again!
config.php:
$db = new mysqli(DB_HOST, DB_USER, DB_PW, DB_DB);
yourFile.php
require_once('./config.php');
I have a php file that i connect to it with ajax and callback value is JSON
when i get data from php it dosnt show and when alert data i see Object
Where is my problem ?
PHP:
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])){
$query = mysql_query("select * from tab");
for ($i=0;$i<mysql_num_rows($query);$i++){
while($row = mysql_fetch_assoc($query)){
$title['t'][i] = $row['title'];
$title['d'][i] = $row['description'];
}
}
echo(json_encode($title));
exit();
?>
JS:
$('#button').click(function(){
$.ajax({
url : "test2.php",
data : $("#tab"),
type : "GET",
success : function(b){
b = eval('('+ b +')');
console.log((b['t']));
alert(b);
}
});
});
How can i get all of data from this JSON and show me corect it ?
Here's a full working example with single row fetch and multi row fetch, without using mysql_ syntax and using prepared statements to prevent sql injections.
And yes, DON'T use mysql specific syntax, like I mentioned here: I cant get the form data to go into database. What am I doing wrong?
function example()
{
var select = true;
var url = '../scripts/ajax.php';
$.ajax(
{
// Post select to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'select' : select // the variable you're posting.
},
success : function(data)
{
// This happens AFTER the PHP has returned an JSON array,
// as explained below.
var result1, result2, message;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
result1 = data[i].result1;
result2 = data[i].result2;
message = data[i].message;
// Do something with result and result2, or message.
// For example:
$('#content').html(result1);
// Or just alert / log the data.
alert(result1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
}
Now we need to receive the posted variable in ajax.php:
$select = isset($_POST['select']) ? $_POST['select'] : false;
The ternary operator lets $select's value become false if It's not set.
Make sure you got access to your database here:
$db = $GLOBALS['db']; // An example of a PDO database connection
Now, check if $select is requested (true) and then perform some database requests, and return them with JSON:
if($select)
{
// Fetch data from the database.
// Return the data with a JSON array (see below).
}
else
{
$json[] = array
(
'message' => 'Not Requested'
);
}
echo json_encode($json);
flush();
How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows.
Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)):
function selectMultipleRows($db, $query)
{
$array = array();
$stmt = $db->prepare($query);
$stmt->execute();
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
{
foreach($result as $res)
{
foreach($res as $key=>$val)
{
$temp[$key] = utf8_encode($val);
}
array_push($array, $temp);
}
return $array;
}
return false;
}
Then you can do something like this:
if($select)
{
$array = array();
$i = 0;
$query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
foreach(selectMultipleRows($db, $query) as $row)
{
$array[$i]["result1"] = $row['result1'];
$array[$i]["result2"] = $row['result2'];
$i++;
}
if(!(empty($array))) // If something was fetched
{
while(list($key, $value) = each($array))
{
$json[] = array
(
'result1' => $value["result1"],
'result2' => $value["result2"],
'message' => 'success'
);
}
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
Or, if you want to KISS (Keep it simple stupid):
Init a basic function which select some values from the database and returns a single row:
function getSingleRow($db, $query)
{
$stmt = $db->prepare($query);
$stmt->execute();
// $stmt->execute(array(":id"=>$someValue)); another approach to execute.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
$array = (
'result1' => $result['result1'],
'result2' => $result['result2']
);
// An array is not needed for a single value.
return $array;
}
return false;
}
And then fetch the row (or the single value) and return it with JSON:
if($select)
{
// Assume that the previously defined query exists.
$results = getSingleRow($db, $query);
if($results !== false)
{
$json[] = array
(
'result1' => $results['result1'],
'result2' => $results['result2'],
'message' => 'success'
);
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
And if you want to get the value of $("#tab") then you have to do something like $("#tab").val() or $("#tab").text().
I hope that helps.
I suggest to use either:
b = jQuery.parseJSON(data)
see more here
or
$.getJSON
instead of eval()