Appending JSON Data from PHP to script after JQuery Ajax Call - javascript

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.

Related

Build cusom json for ajax rest request

Im trying to send a request to a rest API and granted my knowledge using jquery is not advance however through numerous tutorials I'm struggling a bit to build a request based on this swagger documentation.
{
"fields": {
"": [
{
"NAME": "NAME"
},
{
"ADDRESS": "ADDRESS"
},
{
"EMAIL": "EMAIL"
}
]
}
}
This is the model of how i need to send the Rest request, im able to do this using postman however i struggle to do this in javascript.
var data = {};
var json = [{ "NAME": "name", "ADDRESS": "address", "EMAIL": "email" }];
data.fields ={json};
My problem is that in the model there is an empty quotation which im unable to replicate. I suspect that either the rest API is not the best or im missing something quite vital in building a request. See below for the actual ajax jquery request.
var request = $.ajax({
type: "POST",
url: urlBase,
contentType: 'application/json',
data: JSON.stringify({json}),
});
request.done(function (msg) {
alert(msg);
$("#log").html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
Error message based on the above request
Invalid field groups: [json] used in the search fields not found in duplicate store schema
You can create a json like this:
var obj = {
"": [{
"NAME": "NAME"
},
{
"ADDRESS": "ADDRESS"
},
{
"EMAIL": "EMAIL"
}
]
}
console.log(obj)
Hope it helps. Revert for any doubts.

Cannot get JSON echo from PHP to $.ajax

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.

JSONP callback is returning error

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.

MediaWiki JSON Api always returning "undefined"

I'm trying to retrieve some data from the MediaWiki Api; especifically the registration date of a certain user. Taking Wikipedia as a live example, according to their Api sandbox, the request URL to get the information of Jimmy Wales would be:
/w/api.php?action=query&list=users&format=json&usprop=registration&ususers=Jimbo_Wales
So I make an Ajax call:
$.ajax({
dataType: "jsonp",
url: "/w/api.php?action=query&list=users&format=json&usprop=registration&ususers=Jimbo_Wales",
success: function (data) {
var timestamp = data.query.registration;
console.log(timestamp);
}
});
But if I run that script on Firebug, I simply get "undefined". What am I missing?
The resulting JSON data is something like:
{
"batchcomplete": "",
"query": {
"users": [
{
"userid": 24,
"name": "Jimbo Wales",
"registration": "2001-03-27T20:47:31Z"
}
]
}
}
Of course, data.query.registration is undefined. it is not available. Your have to "address" the user itself. Like data.query.users[0].registration.

Value showing undefined when trying to output data returned as json from server

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

Categories