How to get data from ajax GET query - javascript

I'm doing a GET request using $.ajax():
jQuery(function ($) {
$('#acsess').on('click', function () {
$.ajax({
url: 'http://f4c0c1f3aa9a506c69b3b6642864b3590fb8f76f#504080.com/api/v1/services/categories',
method: 'GET',
beforeSend: function(req) {
req.setRequestHeader('Authorization', "f4c0c1f3aa9a506c69b3b6642864b3590fb8f76f");
},
success: function(data) {
console.log(data);
jQuery.each(data, function (index, value) {
// need to create divs with *icon and *title from data
})
},
error: function(error) {
alert("error");
}
})
});
});
I got this in my console:
And I can't retrieve icon link and title text. Please help.

You can access the data (which seems to be an array) by data[index].icon and data[index].title.
If you need to access all the items, I recommend a simple loop:
success: function(data) {
for (var i = 0; i++; i < data.length) {
data[i].icon // it's here, what to do is up to you
}
}

it helps me to resolve problem
success: function(data) {
var ololo = data.data;
for (let i = 0; i < ololo.length; i++) {console.log(ololo[i].title);}
}

Related

How to parse json value (Javascript Ajax)

I need to check the status of BranchName every 10 seconds
Need to get "BranchName, status" value,But the result is not smooth.
I'm not familiar with parsing json of javascript.
How can i do?
Thank you!
get "BranchName, status" value, like this:
BranchNameA
1
BranchNameB
1
The get request returns value(json) like this:
[
{
"BranchNameA":{
"branchNumber":"X20001",
"companyId":"64400001",
"shopName":"BOLLYTEST",
"status":"1",
"statusText":"Online",
"statusMessage":"bbbb",
"errorMessage":"",
"connectTime":"xxxxxx",
"disconnectTime":"",
"CheckModel":{
}
}
},
{
"BranchNameB":{
"branchNumber":"X20001",
"companyId":"64400001",
"shopName":"BOLLYTEST",
"status":"1",
"statusText":"Online",
"statusMessage":"bbb",
"errorMessage":"",
"connectTime":"xxxxxx",
"disconnectTime":"",
"CheckModel":{
}
}
}
]
code:
<script>
getApi()
function getApi() {
setTimeout(getApi, 10 * 1000);
$.ajax({
url: "(api)",
type: "Get",
dataType: "json",
success: function (data) {
console.log(JSON.stringify(data));
let user = JSON.parse(data);
var jsonData = JSON.parse(data);
for (var i = 0; i < jsonData.fields.length; i++) {
var Status= jsonData.fields[i];
console.log(counter.status);
}
}
})
}
</script>
This will solve:
success: function (data) {
var jsonData = apiData;
console.log(jsonData);
for (i in jsonData)
{
data = jsonData[i];
keys = Object.keys(data);
console.log(keys[0]);
console.log(data[keys[0]].status);
}
}

How to autocomplete an input from and API url on wordpress?

I am trying to make a request on an API, from an input. I want to autocomplete airport,cities suggestions etc.
I need to do this on Wordpress and i keep getting an error. This is what i did:
$(function() {
$("#autocompletedep").autocomplete({
source: function(request, response) {
$.ajax({
url: "https://www.fly-go.ro/ajax_autocomplete_flight?temp=",
dataType: "json",
data: {
q: request.term
},
success: function(data) {
var user = new String()
user = data.Title;
for (i = 0; i < user.length; i++) {
$('#autocompletedep')
.append($('<option>', { value: user[i] })
.text(user[i]));
}
}
});
},
});
});
I am not sure if i am doing the right way.
The error is:
flight-search.js?ver=5.3:1 Uncaught TypeError: $ is not a function
at flight-search.js?ver=5.3:1
Any help would be very appreciated, thank you!

How to check when the functions initiated by the loop have completed?

I am running match() to loop through an array or stop ID's. For each stop ID I am calling a function which loops through another array of route ID's and through the response of the AJAX call to find a match.
If it finds a match between the routeID and the RouteID in the array then it adds the result to another array in each loop.
My problem is that I can't find a way to determine when the functions called by the match() loop are complete.
The reason I need to do this, is that I need to make sure that the jpFromStops array is complete and ready to be processed by another function.
What is the best way to do this?
function match() {
// Array length is 5
for(i=0; i < fromStopsAr.length; i++) {
getFromRoutesStopId(fromStopsAr[i]);
}
console.log("Match Array Output: " + jpFromStops.toString());
}
function getFromRoutesStopId(id) {
jpFromStops=[];
tempAr = [];
jQuery.ajax({
type: "GET",
url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
$.each( matchRoutes, function(index, value) {
$.each(data.response, function(key, data) {
if(data.route_short_name.toString() == value) {
jpFromStops[jpFromStops.length] = id + ":" + value;
}
});
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There is a problem");
}
});
}
Console log Output:
Match Array Output:
jp-main.js (line 177)
2
115
jp-main.js (line 199)
2
113
jp-main.js (line 199)
2
087
You can use a counter...sort of like:
var count = 0;
function getFromRoutesStopId(id) {
jpFromStops=[];
tempAr = [];
jQuery.ajax({
type: "GET",
url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
count++;
if(count == fromStopsAr.length){your code or function call}
$.each( matchRoutes, function(index, value) {
$.each(data.response, function(key, data) {
if(data.route_short_name.toString() == value) {
jpFromStops[jpFromStops.length] = id + ":" + value;
}
});
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
count++;
if(count == fromStopsAr.length){your code or function call}
alert("There is a problem");
}
});
}
You can return promise and use $.when
function match() {
var promises = [];
// Array length is 5
for(i=0; i < fromStopsAr.length; i++) {
promises.push(getFromRoutesStopId(fromStopsAr[i]));
}
$.when.apply($, promises).then(function() {
console.log("Match Array Output: " + jpFromStops.toString());
});
}
function getFromRoutesStopId(id) {
jpFromStops=[];
tempAr = [];
return jQuery.ajax({
type: "GET",
url: 'http://apu-url.com/v1/gtfs/routes/stopid/'+id+'?api_key=API_KEY',
dataType: "jsonp",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
$.each( matchRoutes, function(index, value) {
$.each(data.response, function(key, data) {
if(data.route_short_name.toString() == value) {
jpFromStops[jpFromStops.length] = id + ":" + value;
}
});
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There is a problem");
}
});
}
When dealing with ajax calls, you need wait until each of them has finished the execution.
Follow this pattern:
var jobs = [11, 12, 14, 15];
function doTheJob() {
if (jobs.length === 0) {
alert('All jobs are done now.');
complete();
return;
}
var job_Id = jobs.pop();
$.ajax({
url: "/DoTheJob",
complete: function () {
doTheJob();
}
});
};

jQuery ajax loop and iteration scope

I'm wondering why in the code below the i variable still shows "5" instead of showing "1" then "2" then "3" and so on ? Must be a scope issue but I don't really get it as I changed the scope of i variable in global and dom scope and still getting the same problem.
When I alert i outside the ajax function, it works well.
for (var i = 0; i < 5; i++) {
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i) // always 5
}
})
$('#outsideAjax').append(i); // is okay
}
Here is the fiddle
EDIT :
I went for #Tushar Gupta solution as it best suits my needs but I get another issue, the iteration won't work if I set this option : processData: false
See the fiddle
Why is this not working ?
This is due to Closures in JavaScript. Here's the fix -
for (var i = 0; i < 5; i++) {
(function(i){
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i)
}
})
})(i);
$('#outsideAjax').append(i);
}
you can fix this using closures, wrapping the value of i:
for (var i = 0; i < 5; i++) {
(function(val){
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(val);
}
})
$('#outsideAjax').append(val); // is okay
})(i);
}
fiddle Demo
var i = 0;
function ajax_call() {
$.ajax({
url: '/echo/html/',
method: 'post',
data: {
html: 'Ajax data'
},
success: function (resp) {
$('#success').append(i++);
if (i < 5) {
ajax_call();
}
}
});
$('#outsideAjax').append(i);
};
ajax_call();
Solution using Function#bind():
http://jsfiddle.net/RQncd/1/
for (var i = 0; i < 5; i++) {
$.ajax({
url: '/echo/html/',
method:'post',
data: {
html: 'Ajax data'
},
success: (function (i, resp) {
$('#success').append(i);
}).bind(null, i)
});
$('#outsideAjax').append(i);
}

Uncaught TypeError: Object has no method autocomplete and its blocking to populate dialogue box to delete

I'm sorry similar post is already there in the community, But i'm finding it strange. Its working fine but it affected my other views and not allowing other view pages to populate any dialogue boxes..
I tried to fix it by wrapping it in function() like this
$('#_auto').autocomplete(function(){
But, with this i'm not getting jason values in the _auto textfield and getting unexpected token error with following line.
can anyone help me to solve this please.
source: function(request,response){
this is my code:
$(function () {
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
var sval = $('#_auto').val();
//alert(sval);
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': sval,
},
dataType: 'json',
success: function (data) {
console.log(data);
var dta = [];
orgdetails = [];
//response(data.d);
for (var i in data) {
dta.push(data[i].name);
orgdetails[data[i].name] = data[i].id;
}
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
});
Many Thanks
I think the for loop should be
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
Fiddle.
Another observation, You can get the current searched term using request.term rather than $('#_auto').val()
Complete code:
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': request.term,
},
dataType: 'json',
success: function (data) {
console.log(data);
orgdetails = {};
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});

Categories