getting JSON data from php page - javascript

My PHP web page is returning a JSON string. I wrote following function to get those data and display them on jQuery mobile listview.
function LoadJsonDataFunction()
{
$.getJSON("my_web_page.php", function(obj) {
$.each(obj, function(key, value){
$("ul").append("<li>"+value.fname+"</li>");
});
});
}
Here is my listview code:
<ul data-role=listview> </ul>
I have called to the function in the body tag
<body onload="LoadJsonDataFunction()">
but when I executing the program it displays "undefine" and no data.
then I change $.getJSON() request like this.then its working perfectly.
$.getJSON("some_page_returning_same_json_string.json",function(obj) { .....
let me know how can i fix this.
PS. Here is my php page output..
{
"employees":[
{
"fname": "sdsdsd",
"lname": "sdsd",
"phone": "sdsd",
"gender": "female",
"dob": "1990-03-11",
"address": "03",
"nic": "erer",
"email": "erererer",
"empid": "ererere",
"designation": "sdsds",
"qualifications": "dsds"
}
]
}
Here is my php code
<?php
header('Content-Type: application/json');
/*
Following code will list all the employees
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all employees from employees table
$result = mysql_query("SELECT * FROM emp_master") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// employees node
$response["employees"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$employee = array();
$employee["fname"] = $row["fname"];
$employee["lname"] = $row["lname"];
$employee["phone"] = $row["phone"];
$employee["gender"] = $row["gender"];
$employee["dob"] = $row["dob"];
$employee["address"] = $row["address"];
$employee["nic"] = $row["nic"];
$employee["email"] = $row["email"];
$employee["empid"] = $row["empid"];
$employee["designation"] = $row["designation"];
$employee["qualifications"] = $row["qualifications"];
//push single employee into final response array
array_push($response["employees"], $employee);
}
// success
// $response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no employees found
$response["success"] = 0;
$response["message"] = "No employees found";
// echo no users JSON
echo json_encode($response);
}
?>

Have you write correct header? If not write this as first line in your PHP:
header('Content-Type: application/json');

Change the line:
$.each(obj, function(key, value){
with
$.each(obj.employees, function(key, value){
The "employees" contains in "obj" and then it contains the array. "obj" does not contain the array you are looking.

This is the best exemple i used to begin JQM , you can check the link or use the code below
$('#ListPage').bind('pageinit', function(event) {
$.getJSON('some_php_or_json_file_link', function(data) {
$('#listView li').remove();
$.each(data.items, function(index, item) {
$('#listView').append('<li><span>' + item.json_label1 + '</span></li>');
});
$('#listView').listview('refresh');
});
});

Related

Convert a Ajax Json String to a JS Object for my Ajax Get Script

I ideally want the Ajax result to be converted from Jsonstring to OBJ Thank You in advance.
I know the AJAX GET script is working becuase when I alert the Ajax Post result I see the Contents in json string format as below.
alert(JSON.stringify(data));
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I want the AJAX GET result data converted to look like this in OBJ format like below.
{id:31,name:"Mary",username:"R8344",email:"wemail}];
PHP/SQL CODE with the Json encoded Array
<?php
include "../mytest/config.php";
$return_arr = array();
$sql = "SELECT * FROM users ORDER BY NAME";
$result = $conn->query($sql);
//Check database connection first
if ($conn->query($sql) === FALSE) {
echo 'database connection failed';
die();
} else {
while($row = $result->fetch_array()) {
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
$email = $row['email'];
$return_arr[] = array(
"id" => $id,
"username" => $username,
"name" => $name,
"email" => $email);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
?>
php echo _encode array above returns below Json string format
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I am looking for something like below.( top half of the script)
<script>
$(document).ready(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(result){
var data =(JSONstring convert to OBJ(result);
//-----The top half of script -------------
$.each(data, function( i, person ) {
if(i == 0) {
$('.card').find('.person_id').text(person.id);
$('.card').find('.person_name').text(person.name);
$('.card').find('.person_username').text(person.username);
$('.card').find('.person_email').text(person.email);
} else {
var personDetailCloned = $('.card').first().clone();
personDetailCloned.find('.person_id').text(person.id);
personDetailCloned.find('.person_name').text(person.name);
personDetailCloned.find('.person_username').text(person.username);
personDetailCloned.find('.person_email').text(person.email);
$('.card-container').append(personDetailCloned);
}
});
});
</script>
I will need help with the closing tags as above is just an example
The solution is:
success: function(result){
data =(result);
There was no need o convert the data to OBJ or anything ( blush). Then the code on the 2nd half of the Ajax script will receive the data and populate. Thanks to all contributors.

JQuery GET request won't get correct data from php echo

I am trying to fill a table using a jquery .get request, the url being a php file. The php gets data from a database, then it should return a json array back to the jquery, array which will fill the table. While the length of the array is returned as it should, the table cells are empty.
Here is my get.php function:
<?php
$mysqli=new mysqli("localhost:3306","root","","leagues");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$return_arr = array();
$query = "SELECT * FROM league";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row())
{
$return_arr[] = $row;
}
}
$mysqli->close();
header('Content-Type: application/json');
echo json_encode($return_arr);
?>
And here is my jquery get function
$.get('php/get.php',function(responseJson)
{
if(responseJson!=null)
{
$("#tableleague").find("tr:gt(0)").remove();
var table1 = $("#tableleague");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['teams']);
rowNew.children().eq(1).text(value['playedgames']);
rowNew.children().eq(2).text(value['wongames']);
rowNew.children().eq(3).text(value['tiegames']);
rowNew.children().eq(4).text(value['lostgames']);
rowNew.children().eq(5).text(value['scoredgoal']);
rowNew.children().eq(6).text(value['receivedgoal']);
rowNew.children().eq(7).text(value['points']);
rowNew.appendTo(table1);
});
}
});
Here is how my webpage looks, with the php file response shown.
Since the response is ok, what am I doing wrong that the cells aren't filled? Thank you.
If you look at your JSON data, you can see that there are no keys such as teams or playedgames. This is because you used fetch_row() in the PHP. Change that to fetch_assoc():
while ($row = $result->fetch_assoc())
This will give you $row with the field names as keys instead of using numerical keys that fetch_row() provides.
You can turn the php json into javascript object
obj = JSON.parse(json);
es:
var json='{"ex1":"test","ex2":[{"sub1":"test"},{"sub2":""s2test}],"ex3":true}';
var obj = JSON.parse(json);
after you can acces to data with :
obj.ex1 // test
obj.ex2[0].sub2 //s2test

Display JSON Array as html list

I want to display my JSON array which i got from the PHP server as list in HTML. The code I used loops through the array, but when i replace the array with the variable it does not work.
$(document).ready(function(){
$(document).bind('deviceready', function(){
//Phonegap ready
onDeviceReady();
});
var ownproducts = $('#ownproducts');
$.ajax({
url: 'MYURL',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var products = '<br>'+item.item;
var ul = $('<ul>').appendTo('body');
var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] };
$(json.items).each(function(index, item) {
ul.append($(document.createElement('li')).text(item));
});
ownproducts.append(products);
});
},
error: function(){
ownproducts.text('Error Message');
}
});
});
So i get a JSON file containing data from my database, item.item contains an array but when i replace this:
var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] };
for:
var json = { items: item.item };
or:
var json = { items: products };
it does not work (not displaying anything javascript related).
EDIT:
I try to get some items from my database through PHP
<?php
header('Content-type: application/json');
require 'config.php';
$con = mysqli_connect($url,$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$userid = $_GET['userID'];
mysqli_select_db($con, $database);
$sql = "SELECT shoppingListID AS id, shoppingListUserID AS userid, shoppingCheckBox AS checkbox, shoppingItem AS item, shoppingDate AS date
FROM shoppinglist
WHERE shoppingListUserID='$userid'
ORDER BY shoppingDate DESC";
$result = mysqli_query($con,$sql) or die ("Query error: " . mysqli_error());
$records = array();
while($row = mysqli_fetch_assoc($result)) {
$records[] = $row;
}
mysqli_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
the ShoppingItem field contains an array like ["Tomatos","Apples","Mangos","Bananas"] the SQL returns multiple shoppinglists from a single user, I want to display the shoppinglists on cards with the items of each list in an html list.
Anyone any suggestions? I appreciate the help.
Let me suppose that your JSON endpoint does in fact return the right data -- in this case visiting what you"ve labeled MYURL generates (I believe!) the text:
jsoncallback({"items":["Banana","Cherry","Apple","Strawberry","Pear","Pineapple"]})
Then we can move on to your logic, which consists in this callback function:
function (data, status) {
$.each(data, function (i, item) {
var products = "<br>" + item.item;
var ul = $("<ul>").appendTo("body");
var json = {
items: ["Banana", "Cherry", "Apple", "Strawberry", "Pear", "Pineapple"]
};
$(json.items).each(function (index, item) {
ul.append($(document.createElement("li")).text(item));
});
ownproducts.append(products);
});
}
What is the problem here? There are a lot. The first is that you should probably not be iterating over data, since that is not your array. Instead you should be iterating over data.items.
The second is that you should probably just be creating the HTML rather than creating a ton of DOM stuff. You can use vanilla JS's Array.prototype.map or Array.prototype.join functions rather than delegating this to JQuery: it is a part of the JS spec that this is sufficient:
function (data, status) {
var html = '<ul><li>' + data.items.join('</li><li>') + '</li></ul>';
$(html).appendTo('body');
}

Ajax Javascript Get JSON value

Hi I am developing an app in phonegap, where I am getting a particular value from server by connecting php file the value I need to pass is a string value 'pmnno'suppose whose value is '2' I need to get the value of '2' in column name 'personalnumber'.. So I am giving my code below
var jsonData;
$.ajax({
type: 'GET',
url: 'http://xxxx.com/app/get_pday1_number.php',
data: { pmnno: '2' },
dataType: 'html',
success: function (response) {
jsonData = response;
alert(jsonData);
}
});
php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pone"]))
{
$pone = $_GET['pone'];
// get a product from products table
$result = mysql_query("SELECT *FROM pdaynew WHERE pone = $pone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pone"] = $result["pone"];
$product["personaldayone"] = $result["personaldayone"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am getting a success mesage that means connection is succesful but ineed the value of '2' in column 'personalnumber' for that where I need to add that code..If anyone knows pls help me...
Instead of using * use personaldayone:
$result = mysql_query("SELECT personaldayone FROM pdaynew WHERE pone = $pone");

Php echo json_encode array into javascript array

I am trying to send a post to a php script which will collect all the account information from the database using this...
var e = document.getElementById("lstAccounts");
var accountID = e.options[e.selectedIndex].value;
alert("Account ID:"+accountID);
$.post("php/getAccount.php", {ID: accountID}, function(data)
{
var accountInfo = data;
});
This posts into this...
<?php
$id = $_POST['ID'];
include('database_api.php');
$db = new DatabaseControl;
$db->open_connection();
$result = $db->db_query("SELECT * FROM tblAccount WHERE ID=$id");
$account_info = array();
//Get Basic Information
while($row = mysqli_fetch_array($result))
{
$account_info['Name'] = $row['Name'];
$account_info['CRN'] = $row['CRN'];
$account_info['ID'] = $row['ID'];
$account_info['Type'] = $row['Type'];
$account_info['Revenue'] = $row['Revenue'];
$account_info['Industry'] = $row['Industry'];
$account_info['Description'] = $row['Description'];
$account_info['Employees'] = $row['NoOfEmployees'];
$account_info['Billing'] = $row['BillingAddress'];
$account_info['Shipping'] = $row['ShippingAddress'];
}
//Get Details
$result = $db->db_query("SELECT tblDetails.ID, tblDetails.Label, tblDetails.Value FROM tblAccountDetails
INNER JOIN tblDetails ON tblDetails.ID = tblAccountDetails.DetailID
WHERE AccountID=$id");
//Get Basic Information
while($row = mysqli_fetch_array($result))
{
$account_info['Detail'.$row['ID']]['Label'] = $row['Label'];
$account_info['Detail'.$row['ID']]['Value'] = $row['Value'];
}
//Get Contact Information
//Get Invoices
//Get Payments
//Get Notes
//Get To-Do
//Events
//Send back to javascript
echo json_encode($account_info);
?>
I need the echoed json_encode to enter a javascript on the return data. How do I get that data into an array?
$.post("php/getAccount.php", {ID: accountID}, function(data)
{
//In here how do I decode data into a javascript array
});
The data is set at "{"Name":"A business name","CRN":null,"ID":"17","Type":"User","Revenue":null,"Industry":"Software & Internet","Description":null,"Employees":null,"Billing":"An Address","Shipping":"An Address","Detail75":{"Label":"Phone","Value":"a phone number"},"Detail76":{"Label":"Email","Value":"an email address"}}" on return
pass in json_encode()'ed data from your php, like:
...
while($row = mysqli_fetch_array($result))
{
$account_info['Detail'.$row['ID']]['Label'] = $row['Label'];
$account_info['Detail'.$row['ID']]['Value'] = $row['Value'];
}
echo json_encode($account_info);
in js part:
$.post("php/getAccount.php", {ID: accountID}, function(data) {
//parse the json response
var response = jQuery.parseJSON(data);
console.log(response); //you can use $.each to iterate the data
});
First Set the datatype as JSON
$.post("php/getAccount.php", {ID: accountID}, function(data)
{
// Confirm Response
console.log(data);
$.each(data, function(i, e){
console.log(e);
});
}, 'json');

Categories

Resources