JSONP callback is returning error - javascript

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.

Related

JSON Data cannot be stored in variable

Im trying to load the content of a JSON File into an variable.
Before, the variable looked something like this:
var Data = {
teams : [
["Team 1", "Team 2"],
["Team 3", "Team 4"]
],
results : [
[[1,2], [3,4]],
[[4,6], [2,1]]
]}
Now I have a JSON File looking something like this:
{"teams":[["Team 1","Team 2"],["Team 3","Team 4"],"results":[[[[1,2],[3,4]],[[4,6],[2,1]]]}
Now I want that the the content of the JSON File is stored in the Data Variable before. I tried it with Ajax which looks like this:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data
},
});
Console.log works perfect, but the Data is not saved in the variable and I'm getting the error: Uncaught ReferenceError: Data is not defined.
I also tried it with var Data = JSON.parse(data), but this doesn't seem to work either.
And now I'm stuck without any clue.
Thanks for help in advance.
I'm not sure what your code looks like after the ajax call, but I'm guessing the the code where you are using Data is after the ajax call. ajax is asynchrounous. That means that your code doesn't wait for it to finish before moving on. Any code that needs to wait until after it's done fetching the data, you can put in the .success function. Also, it's worth noting that success only gets called when the ajax request is successful. If you want to handle errors, you can use .error Something like this should work:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data;
// Anything that needs to use Data would go inside here
},
error: function(err) {
// handle errors
console.error(err);
}
});
// Any code here will not wait until `Data` is defined
// console.log(Data) // error

Appending JSON Data from PHP to script after JQuery Ajax Call

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.

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.

How can I get response from webservice in jquery?

I want to get the data response from my login webservice. Here is my web service
http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a
(for testing). Here is my code:
$("#login").click(function () {
var url = "http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a";
$.ajax({
url: url,
type: 'Get',
success: function (data) {
alert(data.Medical_id);
},
});
});
The alert() shows me undefined. Please advise on what the problem could be.
The result is an array, so in order to get that field you have to iterate the result or get the first item:
for (var i in data) {
console.log(d[i].Medical_id);
}
Or you can simply get the first result:
$.ajax({
url: 'http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a',
type: 'Get',
success: function (data) {
alert(data[0].Medical_id);
}
});
The JSON result you are getting is :
[{"$id":"1","id":8,"Medical_id":"a","Password":"a","Name":null,"Email":null,"gender":null,"Type":null}]
use for each to iterate through the results or
instead of this you can check the result like this :
var data = [{ "$id": "1", "id": 8, "Medical_id": "a", "Password": "a", "Name": null, "Email": null, "gender": null, "Type": null }]
alert(data[0].Medical_id);
If you develop application in localhost then refer this questions also.
"No 'Access-Control-Allow-Origin' header is present on the requested resource"
If you are using chrome, then use this link to use CORS enable plugin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US
hope this will help

Jquery Autocomplete Search with Ajax Request as sourcedata

What I want to do:
I want to do a input text field with a jquery autocomplete function which gets the source data from a cross-domain curl request. The result should be exactly like this example (CSS not important here): http://abload.de/img/jquerydblf5.png (So I actually want to show additional infos which I get from the curl Request). The URL to get the source data is http://www.futhead.com/15/players/search/quick/?term= and in the end I add those letters which are currently typed in at my input field (for example "Ronaldo").
At the moment I only tried to perform the searchrequest without showing all infosin the dropdown as shown in the screen above. I only want to see which playernames I actually got back by the curl request. Later I will try to add more information for the dropdown. Maybe you guys can help me as well with this as well (I think its called custom renderItem ??).
This is what I've tried:
<script>
$( "#tags" ).autocomplete({
source: function (request, response) {
$.ajax({
type: 'GET',
url: 'playerscraper.php',
dataType: "json",
data: function () {
return $("#results").val()
},
success: function (data) {
// I have no idea what this response and map is good for
response($.map(data, function (item) {
return {
label: item.label,
id: item.value,
};
}));
},
});
}
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
My playerscraper.php is performing the curl request and actually returns a array (tested with echo):
$term = $_GET['term'];
$curlRequest = new CurlRequest();
$result = $curlRequest->get('http://www.futhead.com/15/players/search/quick/?term=' . $searchterm);
$players = array();
return json_encode($result);
My problem:
I have no idea how to do the source part for the autocomplete function this way, that I get the right results from the ajax request with my searchterm from the input field. When I type in something in the input field, nothing happens (the function which defines the source is getting called - tested with an alert).
First try to fix the problem with your help (current Code):
<script>
$( "#tags" ).autocomplete({
source: function (request, response) {
$.ajax({
type: 'GET',
url: 'playerscraper.php',
dataType: "json",
data: function () {
term: request.term
},
success: function (data) {
// I have no idea what this response and map is good for
response($.map(data, function(item) {
return {
label: item.full_name,
value: item.player_id
};
}));
},
});
},
minLength: 3,
delay: 500
});
</script>
The JSON is in a format which is incompatible with what autocomplete widget expects. This is where the $.map comes into play. You use this function to convert the JSON to desired format. Begin by returning a {label: "display name", value: "some id"} pairs like this:
response($.map(data, function(item) {
return {
label: item.full_name,
value: item.player_id
};
}));
Notes:
You should send content type header with your JSON:
header("Content-Type: application/json");
echo $result;
You should use request.term instead of input element value for the data parameter like this:
data: { term: request.term }
You should set higher delay and minLength values to reduce number of JSON requests:
delay: 500,
minLength: 3,
There are some undefined variables in your PHP script. Fix. Make sure that you echo the JSON instead of returning it. The remote server sends JSON so there is no need to json encode it again.
$term = $_GET['term'];
$result = file_get_contents('http://www.futhead.com/15/players/search/quick/?term=' . $term);
header("Content-Type: application/json");
echo $result;
Always check your PHP scripts for issues by opening directly in browser. Always look at browser JavaScript console to look for JavaScript errors and warnings.
Few things are looking wrong in in jQuery code
You have used $_GET['term'] in server side code but not passed term in ajax request query string
Need to fix as
data: {term: request.term}
extra comman(,) in code, it will create issue in IE browsers
response($.map(data, function (item) {
return {
label: item.label,
id: item.value
};
}));

Categories