How to extract parts of response of AJAX from PHP - javascript

Need some help here, i've been searching for related issues here but nothing seems to answer my problem. Ok so here how it goes
I have a simple search function that search through my database and I used an ajax to pass the data and get back the response and I manage to do that but my problem is that I can't seem to display the response the way I wanted to.
Here's my Ajax
$.ajax({
url: url, /// defined url
type: type, ///defined type
data: data, ///defined data
success: function(response){
//here I want to display something like
$('#display').html(the name of the employee);
}
});
Here's the ajax response
{
"employee": [{
"badgeno": "123 ",
"name": "John G. Doe",
"success": true
}]
}
{
"employee": [{
"badgeno": "456 ",
"name": "Jane G. Doe",
"success": true
}
I want to get the employee Name in there and display it in my page. How exactly am I gonna do that?
Thanks in advance. I'm still a newbie BTW
Here's the PHP
$getEmp = $this->Employee_model->search_emp($employee);
$count = count($getEmp);
if($getEmp){
for ($i=0; $i < $count; $i++) {
$data['employee'][$i] = array(
'badgeno' => $getEmp[$i]->BADGENO,
'name' => $getEmp[$i]->NAME,
'success' => true
);
echo json_encode($data);
}
print_r($data);
//$this->load->view('admin/home', $data);
}

Try:
employee_name= data.employee[0].name;
$('#display').html(employee_name);
Link to fiffle:
https://jsfiddle.net/fcz53htw/
If you have more then one name, first add them to array, only then print then json_encode of the array.
Now its wont wont work because you printing twice.
Try change your php to this:
$getEmp = $this->Employee_model->search_emp($employee);
$count = count($getEmp);
if($getEmp){
for ($i=0; $i < $count; $i++) {
$data['employee'][$i] = array(
'badgeno' => $getEmp[$i]->BADGENO,
'name' => $getEmp[$i]->NAME,
'success' => true
);
//echo json_encode($data);
}
echo json_encode($data);
//$this->load->view('admin/home', $data);
}

On php you are write the results twice delete the printr only use json_encode

Related

Structured data

Hello I am working on the data structure. I have following problems:
when I dump ($ data), I have all the info.
I am looking for how has integrated a php variable in json.
here is my piece of code. I have serious problem with concatenation. thank you in advance
<script type="application/ld+json">
{
"name":"<?php ($data[restaurant_name]);?>"
"author": {
"#type": "<?php.....?>",
"name": "<?php.....?>"
},
"datePublished": "<?php ($data[date]);?>",
"description": "<?php ($data[description]);?>",
}
</script>
Do not construct JSON objects like this, it's error-prone!
just using PHP construct an associative array, then use json_encode() function to create valid JSON object and pass whole to JS.
// variables
$name = 'Foo';
$type = 'bar';
$authorName = 'John';
// array
$data = [
'name' => $name,
'author' => [
'#type' => $type,
'name' => $authorName
]
];
// encode to JSON and display
echo json_encode($data);

Unable to retrieve JSON value from PHP and Javascript

I have the following JSON below that I want to parse and get the value of the TotalRows. However, in my PHP and JavaScript it returns an error or undefined when I try to access it and I am not sure why.
For JavaScript:
var data = <?php echo json_encode($customers); ?>;
console.log(data.TotalRows)
I even placed console.log(data) and it gave me the JSON I posted and then I did console.log(data[0].TotalRows) and it give me undefined.
My code for PHP is, where $customers returns the JSON below:
$customers = $customerDB->findCustomer(5, 1);
$arr = json_decode($customers, true);
echo $arr["TotalRows"];
[
{
"TotalRows":91,
"Rows":[
{
"CompanyName":"Ana Trujillo Emparedados y helados",
"ContactName":"Ana Trujillo",
"ContactTitle":"Owner",
"City":"M\u00e9xico D.F.",
"Country":"Mexico"
},
{
"CompanyName":"Antonio Moreno Taquer\u00eda",
"ContactName":"Antonio Moreno",
"ContactTitle":"Owner",
"City":"M\u00e9xico D.F.",
"Country":"Mexico"
},
{
"CompanyName":"Around the Horn",
"ContactName":"Thomas Hardy",
"ContactTitle":"Sales Representative",
"City":"London",
"Country":"UK"
},
{
"CompanyName":"Berglunds snabbk\u00f6p",
"ContactName":"Christina Berglund",
"ContactTitle":"Order Administrator",
"City":"Lule\u00e5",
"Country":"Sweden"
},
{
"CompanyName":"Blauer See Delikatessen",
"ContactName":"Hanna Moos",
"ContactTitle":"Sales Representative",
"City":"Mannheim",
"Country":"Germany"
}
]
}
]
Its an array of object, so you would get TotalRows by
console.log(data[0].TotalRows);
Actually, I figured it out. The following worked:
var data = <?php echo json_encode($customers); ?>;
var data = JSON.parse(data);
console.log(data[0].TotalRows);

Error in performing ajax post data and echoing those data on the console log

i was asked to perform ajax post data to the php script which will include the another script which perform sql connection to the database and get all data and convert data to json format. then the json data will be shown on the console. also i also was asked to modify the ajax to post the values such as name and the religion such as abdullah and muslim respectively.. I want to perform coding on the passwrapper to get and show data on the console.log..
in ajax.html
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: 'Abdullah',
lastReligion: 'Muslim',
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
in passwrapper.php
<?php
include 'student.php';
executePass();
receivePost();
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
echo '<script>console.log("Last='.$_POST["lastName"].' lastReligion='.$_POST["lastReligion"].'");</script>';
}
}
?>
in student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
?>
my question is how to show all data on the console log and also show the post data on the console.log.. please do not modify the student.php... only modify the passwrapper.php
This should output the data from both functions combined, as JSON which your ajax "success" function can log. Your existing code has an issue because one part of it tries to return JSON, and the other part tries to return a <script> block, which is not valid JSON, and also would likely not be executed by the browser anyway for security reasons.
I've also modified the two functions so they return their output to the caller as PHP variables, rather than directly echo-ing JSON strings to the browser. This makes them more re-usable, and also makes it much simpler to then combine the results into a single coherent JSON object to output to the browser.
The console.log(data); command in your existing ajax "success" function will take care of logging all the returned data to your browser console.
$studentArr = executePass();
$postArr = receivePost();
echo json_encode(array("students" => $studentArr, "postvars" => $postArr));
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
return array ("lastName" => $_POST["lastName"], "lastReligion" => $_POST["lastReligion"]);
}
}
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
return $json_array;
}
Now, I don't know the exact structure of your "students" data, so I can't give you an exact example of the output you'll receive, but if I were to assume that your students table had 3 simple fields - "id", "firstname", and "lastname", and there were 4 rows in the table, you would get a final JSON output something like this:
{
"students":
[
{
"id": 1,
"firstname": "firstname1",
"lastname": "lastname1"
},
{
"id": 2,
"firstname": "firstname2",
"lastname": "lastname2"
},
{
"id": 3,
"firstname": "firstname3",
"lastname": "lastname3"
},
{
"id": 4,
"firstname": "firstname4",
"lastname": "lastname4"
}
],
"postvars": {
"lastName": "Abdullah",
"lastReligion": "Muslim"
}
}
You have a JSON object with two properties. The "students" property contains an array of all the students in your table. The "postvars" property is another object containing properties matching the two POST variables you wanted to capture.

Create JavaScript Object from PHP to hold user list with user data fields

I am building a Project management app using JavaScript and PHP.
Many of my JavaScript files will need access to a user list from my backend database. To increase performance or server hits I would like to build the user list with user data attached 1 time in PHP and print it to the screen as a JavaScript Object which my other JavaScript files can then access to get users data.
Assuming I have 20 users.
I need to have access to these user fields in ALL my JavaScript app/objects:
User name
User ID
User ACL role
User gravatar image URL
I am uncertain if I should generate a JavaScript Object with my PHP of the userlist or if it needs to be generated as JSON?
Also which ever it be, object or JSON, can you please show how it should be formatted to include multiple user records in the list and then how I would access a users data from my other JavaScript files assuming I have the user's ID.
So if I have user ID 1, I can call a function or object from my other JavaScript files and they will have access to all data for that user with ID 1 by getting it from the JavaScript that my PHP would print into the header of page.
Any help please?
Ideally I think something like being able to call:
var user = cureentJsObject.getUser(userId);
user.gravatarUrl // https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG
user.username // JasonDavis
user.role // admin
Being able to do something like that inside of my other JavaScript object/apps based on the data in the header of screen for userlist would be really nice but I am not certain how to do it?
UPDATE
I think this PHP would generate what I want. Just have to figure out the best way to access it in all of my objects in other JS files in the page
<?php
// PHP array
$userList = array(
array(
'id' => '1gdfgdfkn123423423',
'username' => 'JasonDavis',
'role' => 'admin',
'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
),
array(
'id' => '2gdfgdfkn123423423',
'username' => 'John Doe',
'role' => 'user',
'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
),
array(
'id' => '3gdfgdfkn123423423',
'username' => 'Rick James',
'role' => 'user',
'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
),
);
?>
var users = <?php echo json_encode($userList) ?>;
JSON output:
var users = [{
"id": "1gdfgdfkn123423423",
"username": "JasonDavis",
"role": "admin",
"gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}, {
"id": "2gdfgdfkn123423423",
"username": "John Doe",
"role": "user",
"gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}, {
"id": "3gdfgdfkn123423423",
"username": "Rick James",
"role": "user",
"gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}];
UPDATE 2
I can now access the user from the above...
<script>
function findById(source, id) {
for (var i = 0; i < source.length; i++) {
if (source[i].id === id) {
return source[i];
}
}
throw "Couldn't find object with id: " + id;
}
var users = <?php echo json_encode($userList) ?>;
var id = '2gdfgdfkn123423423';
var user = findById(users, id);
alert(user.gravatar);
</script>
I would say using JSON.
You can make a multidimensional array in PHP which encodes to JSON.
After you parse the JSON in JS you can access it like an object. E.g.:
myUserData[1].name
If you will always need all your users data, you can write an array of users in your PHP template as a JS array of objects. You don't need JSON. Something like:
<?php
$users_JS = array_map(function($user) {
return "{name: '{$user->name}', gravatar: '{$user->gravatar}'}";
}, $users)
?>
<head>
<title>PHP to JS</title>
<script>
window.MyApp.users = [
<?php echo implode(',', $users_JS); ?>
];
</script>
</head>
Now you can access your user list in window.MyApp.users.
If you need user data on demand (you don't know what data your app will need), you can do a little API in PHP that returns a user on JSON format:
<?php
$user = getUserFromId($_GET['id']);
header('Content-type: application/json');
echo json_encode($user);
And in JS:
$.ajax({
type: 'GET',
url: '/getUser.php', // URL of previuose PHP
data: {id: 3}
}).done(function(user3) {
// Do awesome things with user3
});
Obviously, this code needs validation, 404 if user id doesn't exists, etc, etc...
HTH!
You can use json_encode passing your user object to it.
The better way is to create a string with concatenating with '.' operator and in javascript use JSON.parse to make it a JSON object

jQuery getJSON Undefined Error

Alright, so I've done a bit of searching and trying with no luck. I'm hoping that someone here can point me in the right direction. I have a JSON feed that I'm working with, which is supposed to output a variety of data. Currently, it just sends back and "UNDEFINED" response for all variables. Here is the JS I'm using:
$("#loaduserdata").click(function(){
$("#userdata tbody").html("");
$.getJSON("trendFetch", function(data){
$.each(data.list, function(i, data){
var jsondata = data.action;
console.log (jsondata);
});
}
);
I'm not sure where the problem exists, because console isn't giving me any kind of errors or any reason to think that the JSON isn't formatted correctly: http://i.imgur.com/ySpdR.png
For whatever it's worth, here is the code I'm using to generate the JSON - maybe there is an issue on that end?
$curl = curl_init();
$url = 'http://api.site.com';
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
if($resp){
echo $resp;
header("Content-Type: application/json", true);
}
else {
echo 'Error - no response!';
}
curl_close($curl);
EDIT - including JSON output:
{
"status": "ok",
"list": {
"list_id": "2gz",
"title": "Test List",
"description": "description text...",
"image": [
"http://t2.gstatic.com/images?q=tbn:ANd9GcTz6_4aV6oHsI2kgJRRoSFCTWbew5ChTeBrAmXYh4Gez2J7usm8nwMOsA",
"http://cdn.list.ly/logos/default-list-image.png"
],
"views": 0,
"item_count": 1,
"curator_count": 1,
"follower_count": 1,
"listly_url": "http://api.list.ly/list/2gz-test-list",
"items": [
{
"item": {
"name": "Link 1",
"image": "http://t2.gstatic.com/images?q=tbn:ANd9GcTz6_4aV6oHsI2kgJRRoSFCTWbew5ChTeBrAmXYh4Gez2J7usm8nwMOsA",
"note": null,
"url": null,
"likes": 0,
"dislikes": 0
}
}
],
"suggested_items": []
}
}
echo $resp;
header("Content-Type: application/json", true);
should be:
header("Content-Type: application/json", true);
echo $resp;
You need to send HTTP headers before you output any content.
Set the header before any output
header("Content-Type: application/json", true);
echo $resp;
Musa was able to solve this for me, so in case someone Googles, the problem was that I was trying to use $.each when I didn't need to. Here is the correct code in case anyone is interested:
$.getJSON("trendFetch",function(data){
var tblRow =
"<tr>"
+"<td>"+data.list.list_id+"</td>"
+"<td>"+data.list.title+"</td>"
+"<td>"+data.list.description+"</td>"
+"</tr>"
$(tblRow).appendTo("#userdata tbody");
}
);
It'd help if you provided the JSON response.
When I'm having these types of issues, I typically take a step back (in the code) and console.log() earlier. For example, console.log(data) within the function(data) {}.
I think -- from looking at the output -- that your problem is that list isn't actually a list. data.list is, in fact, an object. Therefore .each() will iterate over the individual items (like list_id, title, etc). None of these have a .action property.
I can't see any action property, so I can't make a solution suggestion. It's possible that it's within the list object -- but you're still treating it like an array (as if it's list: [{}, {}] rather than list: {}). In this case, you either need to fix the returned JSON or get rid of the $.each(), and just console.log(data.list.action).

Categories