while($row = $result->fetch_array()) {
array_push($json_result,
array('crewID'=>$row[0],
'FName'=>$row[1],
'LName'=>$row[2],
'smBook'=>$row[3],
'contactNo'=>$row[4],
'email'=>$row[5],
'address'=>$row[6],
'birthday'=>$row[7],
'emergencyCN'=>$row[8],
'emergencyPerson'=>$row[9],
'loyaltyCN'=>$row[10]));
}
echo json_encode(array($json_result),JSON_PRETTY_PRINT);
This is my jQuery code:
function displayGuestData(guestID) {
$.ajax({
url:"functions/f_get_guests_json.php",
method:"POST",
data:{guestID:guestID},
dataType: "json",
success:function(response) {
alert(response.FName);
}
});
}
Now my problem is I'm getting an undefined error when I alert any of the JSON data like FName. What could be the problem? I'm new with JSON in jQuery. I even have this code in my PHP:
header("Content-Type: application/json", true);
EDIT:
This is the JSON:
[
{
"crewID": "4",
"FName": "Abc Abc",
"LName": "Abc",
"smBook": "ABC123",
"contactNo": "12312312",
"email": "asdasd#yahoo.com",
"address": "56 Sasdasd Asds",
"birthday": "1995-06-11",
"emergencyCN": "12312312",
"emergencyPerson": "asdasdasd",
"loyaltyCN": "ABC123"
}
]
I think the problem is here;
success: function(response){
alert(response.FName);
}
You are returning, as far as I can tell, an array which contains your results.
So perhaps you should attempt changing the above to the following;
success: function(response){
alert(response[0].FName);
}
This accesses the first result in the array, and proceeds to access then alert the contents of it's FName attribute.
Using console.log(response) would be a good way to view the full object your dealing with, and therefore work out how to use it.
Updated
Since you have provided the output json, it appears you have an array containing an array of your results.
You'll be able to see this clearly if you use console.log but you need response[0][0].FName to puncture through your two arrays.
Related
I'm trying to load my JSON Data into my script after an ajax call, but I can't seem to be getting it right.
I have a Javascript library that loads a set of music by having a set of JSON data. For example, this is how loading the script with a few songs would look like:
<script>
Amplitude.init({
"songs": [
{
"name": "Song Name 1",
"artist": "Super Dj",
"album": "2018 Super Hit",
"url": "songs/1.mp3",
"cover_art_url": "../album-art/2018superhit.png"
},
{
"name": "Song Name 2",
"artist": "Super Dj",
"album": "2018 Super Hit",
"url": "songs/2.mp3",
"cover_art_url": "../album-art/2018superhit.png"
}
]
});
</script>
Now, I'm trying to fetch the songs list data from my database using an ajax call, to populate this list of songs dynamically. PHP-wise, it's all good and the data is fine. However, on the ajax call, the Amplitude.init does not work when I add my JSON data to it. The code below will give you a better idea of what I mean:
$(".mu-container").click(function(e){
e.preventDefault();
var albumId = $(this).attr("data-album");
$("#musicContainer").fadeIn();
$("#playerRibbon").fadeIn();
$.ajax({
url: "includes/app/load_music.php",
type: "POST",
data: "album_id="+albumId,
dataType: 'JSON',
success: function(data)
{
Amplitude.init({
"songs": [
data
]
});
},
error: function(err)
{
alert(err);
}
});
});
Finally, here's my PHP code which returns the JSON data, that I want to load into Amplitude.init after the ajax call is made:
//Database connection done above
$data = array();
foreach($songs as $song){
$data[] = array("name" => $song['title'], "artist" => $song['artist'], "album" => $song['album_title'], "url" => $song['url'], "cover_art_url" => $song['album_art']);
}
echo json_encode($data); //If I run the php as a standalone with a test ID, it works just fine
Use
Amplitude.init({
"songs": data
});
Because data is already an array of objects.
I have this script:
<script type="text/javascript">
function requestimg(username){
$.ajax({
url: '{% url "image" %}',
data: {
'username': username
},
dataType: 'json',
success: function (data) {
if (data) {
//Printing the whole data
console.log(data);
//Printing to see where I am
console.log("Name: ");
//Trying to rint the name
console.log(data[0].nombre);
}else {
alert("May Day");
}
}
});
}
I have a problem reading the properties in the json object
When i print the data I get this:
{
json: "[
{
"model": "polls.imagen",
"pk": 17,
"fields": {
"n…"36",
"imagen": "polls/static/pictures/dr.jpg"
}
}
]"
}
And when i print the data as I have it on the code i get:
Uncaught TypeError: Cannot read property 'nombre' of undefined
I have tryied writing it like data.nombre but i just get undefined
I have also tried this console.log(data[0].fields); , data[0].model, data.model
IMPORTANT I want to clarify that i wont know why there are 2 json objects im supposed to get just one and even if i try to put a [1] instead of the [0] i get the same mistakes.
I've tried answers from some previous similar questions and they didn't help.
You will be able to access the fields per
data.json[0].fields
the response of your url is an array, named json
Additionally data.json is returning a string, so convert it to JSON with
data.json = JSON.parse(data.json);
Convert it to JSON first JSON.parse(data.json)
This will give you the access to the fields object data.json[0].fields
I'm trying to learn JSONP. From my research online, I understood that it's invoke function with callback.Apart from that everything else (the way data is handled/data format) similar to JSON?
I'm just playing with JSONP as below. But It's returning error, please explain in detail about it, please..
Script.js
function test(){
jQuery.ajax({
url: "/plugins/system/chat/jsonstr.php",
dataType: "jsonp",
jsonpCallback: "logResults"
});
jsonstr.php
logResults(){
$arr = '[{
"title": "keren",
"picture": "http://something.png",
"id":1
}, {
"title": "diana",
"picture": "/plugins/system/conversekit/conversekit/images/avatar.png",
"id": 2
}]';
echo $arr;
}
I expect this call to return json object so that I can manipulate it in success function of test. But error as below is thrown:
<br />
<b>Parse error</b>: syntax error, unexpected '{' in <b>C:\projects\easysocial.com\plugins\system\conversekit
\jsonstr.php</b> on line <b>14</b><br />
The url in console is as this:
GET http://mysite.localhost.com/plugins/system/chat/jsonstr.php?callback=logResults
logResults() is JavaScript callback, not PHP function. jsonstr.php should only return valid JSON.
So jsonstr.php should look like this
<?php
$arr = [
[
'title' => "keren",
'picture' => "http://something.png",
'id' => 1,
],
[
'title' => "diana",
'picture' => "/plugins/system/conversekit/conversekit/images/avatar.png",
'id' => 2,
],
];
echo(json_encode($arr));
And Script.js
function logResults() {
console.log('ajax done');
}
function test(){
jQuery.ajax({
url: "/plugins/system/chat/jsonstr.php",
dataType: "jsonp",
jsonpCallback: logResults
});
}
Two issues:
Your server-side script doesn't return anything, as the Net pane in your browser developer tools should reveal.
JSONP is just a dirty trick to avoid cross-site permission issues in AJAX, not a way to make PHP code interact with JavaScript (something that is not possible). So when you say "I want a callback function called logResults" you mean a JavaScript function.
If you want to use JSONP you need:
Make your server actually return JSONP (not even JSON):
$callback = filter_INPUT(INPUT_GET, 'callback');
// ...
echo sprintf('%s(%s);', $callback, $json);
Define a JavaScript function to process the returned data:
function logResults (data) {
alert(data[0].title);
}
This way you basically get a dynamically generated good old <script> tag that loads a simple script:
logResults([{
"title": "keren",
"picture": "http://something.png",
"id":1
}, {
"title": "diana",
"picture": "/plugins/system/conversekit/conversekit/images/avatar.png",
"id": 2
}]);
But since you are making an AJAX call in your own domain:
url: "/plugins/system/chat/jsonstr.php",
^^
No "http://example.com/` prefix pointing to a third-party site
... you don't need JSONP at all: plain JSON will be enough.
I am new to Yii2 framework and PHP.I used Mongo DB as the backend database.I fetched a document from a collection and returned the data as Json from the controller.The data returned back is given below.
{
"55b08c383e1a36233fdbdc06": {
"_id": { "$id": "55b08c383e1a36233fdbdc06" },
"address": [ "abcdgt", "zxcv" ],
"age": "23",
"email": [ "qwert#gmail.com","abcd#mail.com" ],
"location": "kollam",
"name": "ajiths",
"phoneno": [ "9522585456", "7875642256" ] ,
"sex": "male"
}
}
But I am getting 'Undefined' when trying to alert result.name in Javascript code.The code at the front end is given below.
function loadClient(id){
url = "<?= Yii::getAlias('#serverpathweb')?>/client/showclient?id="+id;
$.ajax({
url: url ,
method: "GET",
success: function(result){
alert(result.name);
}
});
}
The code at the controller end is given below.
public function actionShowclient($id) {
$clientdetail = Yii::$app->mongodb->getCollection('client');
$result = $clientdetail->find(["_id" =>$id]);
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $result;
}
Can anyone tell me how to get the value result.name.
your getting JSON result with id as key so access ur JSON data like this
first get the key of ur JSON using Object.keys
next using key print the values you need
var id=Object.keys(result)[0]; //it will print your JSON key i.e. "55b08c383e1a36233fdbdc06"
alert(result[id]['name']); // it will print the name
Note if you are getting multiple user details please let me know
Your "result" object is probably a String because you're not telling jQuery otherwise. Trying adding the option dataType:json to your request as in:
$.ajax({ url: url, method: 'GET', dataType: 'json', etc...
Edit: It also looks like there's a simple bug in your code. You need to access your property where it's nested in the resulting object:
result[id].name
I'm trying to get the hand on JQuery and JSON using an ASP.NET webservice. The Webservice returns this result:
{
MyResult: {
Ticket: {
"Author": "rd",
"CssClass": "RED",
"ExpirationDateTime": "2009-08-16T16:55:43.577+02:00",
"id": "38",
"Message": "We are going down",
"ModifiedDateTime": "2009-08-17T11:14:20.5+02:00",
"MoreInfo": null
}
}
}
On the client side I'm using JQuery to get the result using the ajax function like this:
$.ajax({
type: "POST",
url: "TickerFeeder.asmx/GetTicket",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(resultJSON) {
//-- Please fill your code here for getting the first item from the array into variables
}
But I'm missing out the stuff how to retrieve the first item from the JSON array into some variables. Something like this (pseudo-code):
var message = resultJSON[0].Message
var cssclass = resultJSON[0].CssClass
Anybody with a hint,help?
Thanks for your help
Cheers
Frank
Your JSON is not valid, you should use quotes on the MyResult and Ticket members.
{
"MyResult": {
"Ticket": {
"Author": "rd",
"CssClass": "RED",
"ExpirationDateTime": "2009-08-16T16:55:43.577+02:00",
"id": "38",
"Message": "We are going down",
"ModifiedDateTime": "2009-08-17T11:14:20.5+02:00",
"MoreInfo": null
}
}
}
Also there is no array involved, the arrays are defined with the square bracket characters [....] literal notation, so you can access your values directly:
resultJSON.MyResult.Ticket.Message;
resultJSON.MyResult.Ticket.CssClass;
Ok, found out that my Asp.Net webService was producing a wrong result set. So instead of returning a string item I returned a complete object and handled the Json conversion to Asp.Net webservice. That did the trick !