Can I use jquery ajax response for Autocomplete - javascript

It's 3am. I've been banging my head against the wall for hours on this and just don't get it.
I'm trying to use jQuery autocomplete with the source data coming from an ajax request.
Ajax seems to be working great, but I can't seem to use the response for the source data.
Anonymous function fetches data on ready. Success calls test(response) passing the data to the function with autocomplete. The response looks exactly like the sample code. And when I paste my response from the console it works perfectly. But it will not let me use the variable 'albums' for the source.
$(function(){
$.ajax({
dataType: 'text',
type: 'POST',
url: '/albums/fetch_albums',
success: function(response){
console.log(response); // logs ["Italy","Hawaii"] -as expected
test(response);
}
});
});
function test(data){
var albums = data;
console.log(albums); // logs ["Italy","Hawaii"] - as expected
console.log(typeof albums); //logs string - as expected
$('#autocomplete').autocomplete({
source: albums, //this is what I want... errors out.
//source: ["Italy","Hawaii"] // pasted response if un-commented works fine.
});
}
Here is the error message.
GET http://journal.localhost.com/[%22Italy%22,%22Hawaii%22]?term=h 403 (Forbidden)jquery-2.1.1.min.js:4 n.ajaxTransport.k.cors.a.crossDomain.sendjquery-2.1.1.min.js:4 n.extend.ajaxjquery-ui.min.js:7 e.widget._initSource.e.isArray.string.options.source.sourcejquery-ui.min.js:7 e.widget._searchjquery-ui.min.js:6 (anonymous function)jquery-ui.min.js:7 e.widget.searchjquery-ui.min.js:6 (anonymous function)jquery-ui.min.js:7 (anonymous function)jquery-ui.min.js:6 i
There has to be a way to fetch data from the database and feed it to this function.
Help me Obiwan!

$(function(){
$.ajax({
dataType: 'text',
type: 'POST',
url: '/albums/fetch_albums',
success: function(response){
console.log(response); // logs ["Italy","Hawaii"] -as expected
var arrResponse = JSON.parse(response); //convert json object to array
test(arrResponse);
}
});
});

Related

shift() and pop() is not a function

So i was making a random quote generator machine project for learning purposes and encountered a error.
I tried looking for it in other answers but couldn't understand/solve it.
here is the JS code:
$('#new').on('click', function(e) {
e.preventDefault();
$.ajax( {
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback',
success: function(data) {
console.log(data);
var post = data.shift(); // The data is an array of posts. Grabbing the first one.
$('.author').text(post.title);
console.log(post.title);
$('.quote').html(post.content);
console.log(post.content);
},
cache: false
});
});
For the first console.log it shows data in form of array, So I tried pop and shift functions to extract the data. here is the format of data:
/**/mycallback([{"ID":1640,"title":"Scott Belsky","content":"<p>To envision what will be, you must remove yourself from the constant concern for what already is.<\/p>\n","link":"https:\/\/quotesondesign.com\/scott-belsky\/","custom_meta":{"Source":"<a href=\"http:\/\/the99percent.com\/book\">book<\/a>"}}])
It gave undefined for the next 2 console.log() .
Here is the error:
Uncaught TypeError: data.shift is not a function
and it gave errors on both functions. any help would be appreciated.
Two things:
Don't define the callback function. Leave that to $.ajax by replacing the explicit function name to ?
Set the data type to jsonp
$.ajax( {
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?',
dataType:'jsonp',
cache: false,
success: function(data) {
console.log(data);
var post = data.shift();
console.log(post);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

Retrieve all 'data' properties of json data with ajax

I'm trying to figure out how to access to all the data from a json provided by movie database api, but I don't understand how to retrieve it.
The console log give me an "data is not defined" error.
So here is my code:
$(document).ready (function(){
var key = 'api key provided';
$.ajax({
type: 'GET',
url : 'http://api.themoviedb.org/3/search/movie'+key+'&query=Minions',
dataType: 'jsonp',
data: {
format:'json'
},
error: $('#result').append("errore"),
success: function(data){$('#result').append("ok")}
});
var jsonData=data.results.original_title;
//this give me a data is not provided
});
Here a portion of json:
Let's assume that I only want to access to the release_date propriety, how can I achieve this?
data not is defined out of $.ajax() closure, you need to move the code to success handler like, then loop through the JSON data.results.
success: function(data){
$('#result').append("ok");
console.log(data);
$.each(data.results, function(i, result) {
console.log('Release date is' + result.release_date);
});
}
alternatively, you can define a variable, then update that variable in success handler of $.ajax()
var ajaxResponse;
$.ajax({
/* skipped lines*/
success: function(data){
ajaxResponse = data
}
});

Uncaught SyntaxError: Unexpected end of input in parseJSON method javascript

In a webpage that uses javascript, I pass data to a hidden input field using
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
and then later access that data using
waypts_input = $.parseJSON($("#waypt_sel").val())
This works, except that sometimes it gives a
Uncaught SyntaxError: Unexpected end of input
. I tracked the error to this line with the json parsing. but I am baffled because this works sometimes but sometimes it doesn't for the same, identical string.
I checked the values that are passed to the html inputs and it works and doesn't work for the same values.
Here's an example of the json string I am passing:
"[{\"location\":\"8.3353156, 80.3329846\",\"stopover\":true}, {\"location\":\"8.0326424, 80.7446666\",\"stopover\":true}, {\"location\":\"7.9577778, 80.667518\",\"stopover\":true}, {\"location\":\"7.953208, 81.006675\",\"stopover\":true}, {\"location\":\"7.885949, 80.651479\",\"stopover\":true},{\"location\":\"7.2905425, 80.5986581\",\"stopover\":true},{\"location\":\"7.300322, 80.386362\",\"stopover\":true}]"
Here's the structure of the code I use.
$(document).ready(function() {
$.ajax({
url: "aa.php",
type: "POST",
data: {
id: selected_i
},
success: function(result) {
itins = $.parseJSON(result);
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
}
});
$.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php",
success: function(result) {
locations = $.parseJSON(result);
initializeMap();
}
});
function initializeMap() {
//other code
calculateAndDisplayRoute();
//other code
function calculateAndDisplayRoute() {
//other code
waypts_input = $.parseJSON($("#waypt_sel").val());
waypts_json_input = $.parseJSON(waypts_input);
//other code
}
}
});
And here is the detailed error message I get on firefox developer edition browser.
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
calculateAndDisplayRoute() map.js:366
initializeMap() map.js:290
.success() map.js:62
m.Callbacks/j() jquery-1.11.3.min.js:2
m.Callbacks/k.fireWith() jquery-1.11.3.min.js:2
x() jquery-1.11.3.min.js:5
.send/b() jquery-1.11.3.min.js:5
Thanks in advance.
"\" is unnecessary when deserialize json string in javascript .
what json tools you used?
you serialize in one tool , and deserialize with other , may get this scene .
The issue was that I was using an asynchronous ajax request to retrieve json data. by the time the data had been retrieved and pasted to the html, the execution of the code that used the html data had happened, and thus gave an error. I used a callback function for the ajax query and this did the job.
function get_det(callback) {//Your asynchronous request.
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
callback();//invoke when get response
}
});
}
and in the code where this is called:
get_det(secondFunction);//calling with callback function
function secondFunction()//your callback function
{
alert("2nd Call");
}
Alternatively you may also try async: false in the ajax query parameters. But this can cause browser freezing and is not recommended.

Grabbing JSON data with AJAX

I have a JSON URL that I need to grab the variables from and use them as jQuery stings. I've tried several different approaches and all of them are unsuccessful.
Approach 1
$.getJSON('http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get', function(data) {
alert(JSON.stringify(data))
});
Resilt
I receive an 200 OK message, but I do not get any data returned.
Approach 2
$.ajax({
url:"http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",
dataType:'jsonp',
success:function(data){
var obj = jQuery.parseJSON(data);
alert(obj.title);
}
});
Result
I receive on 200 OK but the obj value is NULL
Approach 3
$.getJSON("http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",function(ajaxresult){
window.artist = ajaxresult.track.artist;
});
Resilt
I receive an 200 OK message, but I do not get any data returned.
You didn't look with attention at the JSON object returned by the service.
What you're looking for is the data property of the returned object which is an array.
Something like this do work :
$.ajax({
url: "http://radio.silvertoneradio.com/rpc/incoleyl/streaminfo.get",
dataType: 'jsonp',
success: function (data) {
console.log(arguments);
alert(data.data[0].title);
}
});
JSFiddle to demo

JSON Data returned from Ajax on Safari is converted into a javascript list

This is something I recently found out, I have the following piece of code in JS:
$.ajax({
type: 'POST',
url: '/requestHandle',
data: data,
success: function(data) {
var places = JSON.parse(data);
// do something
},
error: function(data) {
// do something else
}
});
The data returned from my backend is indeed in JSON format, and var places = JSON.parse(data); this line works perfectly in Chrome and Firefox, it parses my JSON data into a JS list; however, in Safari, var places = JSON.parse(data); gives me error, because data is already a JS list. Instead of doing var places = JSON.parse(data), just changing to var places = data solved the error, I am wondering why it is converted automatically?
Thanks in advance
Your best solution would be to tell jQuery that the response is json so that you will always receive it as js object
$.ajax({
type: 'POST',
url: '/requestHandle',
data: data,
success: function(obj) {
// do something
},
error: function(data) {
// do something else
},
dataType: 'json' // reponse is json so it will always be pre-parsed
});

Categories

Resources