JSONP adapter Phonegap project not working - javascript

I am using the sample code (slightly modified) to implement a JSONP adapter found here: http://coenraets.org/blog/2013/04/building-pluggable-and-mock-data-adapters-for-web-and-phonegap-applications/
My modified in-memory adapter works, but when I try to change from using the mock data, to a JSONP data object from a remote server, it doesn't work. Below is my memory adapter:
var JSONPAdapter = function() {
this.initialize = function(data) {
var deferred = $.Deferred();
url = data;
deferred.resolve();
return deferred.promise();
}
this.findById = function(id) {
return $.ajax({url: url + "/" + id, dataType: "jsonp"});
}
this.findByName = function(searchKey) {
return $.ajax(
{
url: url + "?Name=" + searchKey,
dataType: "jsonp",
success: function (data) { },
error: function (XHR, textStatus, errorThrown) { alert("error: " + errorThrown + '\nurl: ' + url + "?Name=" + searchKey);
}
});
}
this.getAll = function getAll() {
return $.ajax({ url: url, dataType: "jsonp" });
}
var url;
}

You don't need the /callback=? appended to the end of the url. This is taken care of automatically because the dataType is set to 'jsonp'.

I suspect this is due to the scope of your JSONData variable.
It is not initialised correctly if there is an error within the getJSONData() call. Try declaring the JSONData variable before the function is defined.

Related

Extract json array data using javascript

I would like to obtain the formatted_address from the json data returned from the following query string by using javascript.
http://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&sensor=true
function getReverseGeocodingData(lat, lng) {
//use ajax and json
$.ajax({
type: "POST",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+sessionStorage.latitude+","+sessionStorage.longitude+"&sensor=true",
data: jsondata,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var address = response.Result;
var error = response.Error;
if (address != null) {
alert("Found current location: " + address.formatted_address);
sessionStorage.currentAddress = address.formatted_address;
return;
}
},
error: function (msg) {
errorConnection();
}
});
}
I tried getting formatted_address but it return undefined.
You can get formatted address like this (Ajax Success)
success: function (results) {
var address = (results[0].formatted_address);
alert(JSON.stringify(address));
},
just changed the success function with this, you will get all the formatted address
success: function (response) {
var address = response.results;
var error = response.error; //write exact word of the "error" which you get in response
if(address.length > 0) {
for(i=0; i<address.length; i++) {
console.log("Found current location: " + address[i].formatted_address);
}
}
},
Sorry my previous response only fixed the AJAX request-
specifying contentType on a request is not required and has no impact - this is controlled by the server.
jQuery already will parse the request to an object, calling JSON.stringify on the response was causing the object to be parsed into a JSON formatted string, removing that line resolved the issue. Also specifying dataType didn't seem to be necessary.
It's worth noting that you're passing lat, and lng arguments to the function but not using them - I'd suggest either adding a lines like:
lat = lat || sessionStorage.latitude;
lng = lng || sessionStorage.longitude;
Below should be a solution complete with my suggestions:
function getReverseGeocodingData(lat, lng) {
lat = lat || sessionStorage.latitude;
lng = lng || sessionStorage.longitude;
jsondata = {};
//use ajax and json
$.ajax({
type: "POST",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + sessionStorage.latitude + "," + sessionStorage.longitude + "&sensor=true",
data: jsondata,
success: function (response) {
var address = response.results[0].formatted_address;
var error = response.Error;
if (address != null) {
alert("Found current location: " + address);
sessionStorage.currentAddress = address;
}
},
error: function (msg) {
errorConnection();
}
});
}
There are a few things to fix:
apparently you don't have to post data as you're making a GET request.
I rewrote your code to take the parameters from lat and lng in order to test it easily.
response is an object that contains an array of results objects (lowercase r plural). Each object contains a formatted_address property.
Most likely you'll want to fetch the first one:
response.results[0].formatted_address
function getReverseGeocodingData(lat, lng) {
//use ajax and json
$.ajax(
{
type: "GET",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true",
dataType: "json",
success: function (response) {
alert("Found current location: " + response.results[0].formatted_address);
},
error: function (msg) {
alert('error');
}
});
}
To try it:
getReverseGeocodingData(44.4647452,7.3553838);
Outputs:
Found current location: Via Pasubio, 34, 12025 Dronero CN, Italia

Data is lost after ajax call

I've got one ajax call after two previous. I need to pass results of those calls to the new one, so I do the following
$.when(getRespData(), getAxisComponents()).done(function (respData, axisData) {
var a = respData; //everything is ok
var b = axisData; //everything is ok
$.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName+ '&type=' + 'VAL',
success: (function (data) {
var c = respData; //everything is ok
var d = axisData; // Uncaught ReferenceError: axisData is not defined
}
but I've got Uncaught ReferenceError when I try to get my axisData inside my new ajax call, although operations with respData are ok.
My first 2 ajax calls look like
function getRespData() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName + '&type=' + 'RESP',
success: (function (data) {
return data;
})
});
}
function getAxisComponents() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload/axis?runName=' + runName,
success: (function (data) {
return data;
})
});
}
where runName, type, taskName are some params of function which contains all these ajax calls.
How can I fix this error, so that I would be able to access both respData and axisData ind my inner ajax call?
i solved it putting async false and declaring an array out of ajax call, like this
let array = [];
$.ajax({
url: path,
type: 'GET',
async: false,
dataType: 'json',
success: function(response){
array = response;
}
});
return array;
You're calling data in your success function but data isn't set before this.
In a jQuery .ajax function, data is the data that is sent to the server when performing the Ajax request, which is why you may think it is lost (because it was never there).
Consider the following:
$.ajax({
data: {"data": data},
dataType: "json",
url: 'yourURl',
success: function(data){
return data;
}

How can I parse JSON using the data parameter in JQuery?

I am making a web application using Jersey and JQuery for client-side.
I have the following URL that returns a JSON string:
http://localhost:8080/messenger/webapi/messages/1
returns:
{"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}
when typed into the browser.
Now I am attempting to get this data client-side using the following JQuery functions:
var rootURL = "http://localhost:8080/messenger/webapi/messages";
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL +"/1",
dataType: "json", // data type of response
success: (function(data) {
var obj = jQuery.parseJSON(data);
alert('ID: ' + obj.id);
})
});
}
});
EDIT: When the "btnRegister" is pressed nothing is displayed at all
which just doesn't make sense to me.
There is some unwanted $ wrapping in success callback function, also there is no need to parse the response as you set dataType:'json'. For better understanding of $.ajax() read documentation here.
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL + "/1",
dataType: "json", // data type of response
success: function(data) {
//----^----------- remove the $ sign
alert('ID: ' + data);
}
});
}
});
You can access the value using obj.prop or obj['prop']
var obj= {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"};
alert(obj.author);
alert(obj['author']);

Ruby on Rails: Get json from controller in Javascript file

in my controller I've some json:
votes_controller.rb:
def create
...
vote_status = current_user.user_votes.pluck(:recipient_uid).include?(#user.uid)
render json: vote_status
end
I need to get vote_status in javascript file
votes.js:
jQuery(function($) {
$(".doWant").click( function () {
var status = vote_status.evalJSON();
var uid = $(this).parents("#dialog")[0];
var username = $(this).parents("#dialog")[0];
if(confirm("Are you sure?")) {
$.ajax({
url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
type: 'POST',
success: function(data) {
console.log(data)
}
});
};
});
});
But there is an error Uncaught ReferenceError: vote_status is not defined. What am I doing wrong?
Thanks!
You're not defining this variable:
var status = vote_status.evalJSON();
You must define that variable.
It seems likely that you intended for that code to go into the success function, which returns the data from the ajax call as the first argument in that function:
success: function(data) {
console.log(data)
}
The vote_status is returned in success json callback, init the status there
$.ajax({
url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
type: 'POST',
success: function(data) {
var status = JSON.parse(data);
}
});

javascript and order of execution of functions

My Class looks like
function classUser() {
var userName;
var firstName;
var lastName;
var sessionid;
}
classUser.prototype.set_user_name = function (user_name) {
this.userName = user_name;
}
classUser.prototype.set_first_name = function (first_name) {
this.firstName = first_name;
}
classUser.prototype.set_last_name = function (last_name) {
this.lastName = last_name;
}
classUser.prototype.get_curr_session = function () {
return this.sessionid;
}
classUser.prototype.save = function () {
$.ajax({
type: "POST",
url: "http://myapihost.com:8080/api/1.0/user/",
data: JSON.stringify(this),
dataType: "json",
success: function (apiResponse) {
var currSessionID = apiResponse.sessionId;
this.sessionid= currSessionID;
},
error: function (apiResponse) {
alert("error : " + apiResponse);
this.sessionid= "Error";
}
});
}
I call them as
var User = new classUser();
User.set_first_name(userFirstName);
User.set_last_name(response.last_name);
User.set_user_name(response.username);
User.save();
var currSessionID = User.get_curr_session();
Sometimes, get_curr_session is called before success: call.
Question :
I tried returning sessionid from success itself so that save() function does the job. That is not working. hence i split across 2 functions.
Can I do it in one call itself? if I have use 2 functions - how do i make sure that it works all the time.
I could actually put assigning the currSessionID within success, however that breaks class sanctity. I have seen other solution like using "done", not sure if that would help here.
=======================================
I modified the code as below
classUser.prototype.save = function (callback) {
$.ajax({
type: "POST",
url: "http://myapihost.com:8080/api/1.0/user/",
data: JSON.stringify(this),
dataType: "json",
success: function (apiResponse) {
var currSessionID = apiResponse.sessionId;
this.sessionid= currSessionID;
callback(null, currSessionID);
},
error: function (apiResponse) {
alert("error : " + apiResponse);
this.sessionid= "Error";
callback("error", null);
}
});
}
When I call
User.save(mycallback);
function mycallback(error, sessId){
if(error) {
console.log("Some error occurred. Check code");
return;// Something went wrong
} else {
console.log("Session : " + sessId);
}
}
Is this good now?
Thanks
Ajay
That's because the success and error function of the ajax request are executed asynchronously.
To make sure this doesn't happen, you should add a callback to your save function that is called after the success or error functions ran.
classUser.prototype.save = function (callback) {
$.ajax({
type: "POST",
url: "http://myapihost.com:8080/api/1.0/user/",
data: JSON.stringify(this),
dataType: "json",
success: function (apiResponse) {
var currSessionID = apiResponse.sessionId;
this.sessionid= currSessionID;
callback(null, currSessionID);
},
error: function (apiResponse) {
alert("error : " + apiResponse);
this.sessionid= "Error";
callback(apiResponse, null);
}
});
}
Then, when calling the save function, you can do something like this:
User.save(function(error, sessId) {
if(error) {
// Something went wrong
} else {
// Do whatever you need to do
}
});
You should note that this will also run asynchronously. So if you want to work with the session ID, don't do that after the User.save(...) call, but inside the function.
$.ajax() issues an asynchronous call to the url specified in the options object. See the jQuery documentation at http://api.jquery.com/jQuery.ajax/
success is a callback function that is invoked when the call is completed and all the response stream is read by the browser so basically in most of the cases the callback (updating the session id) will execute after you try to retrieve it.
I think what is happening here is that the default ajax call is async which means that the code var currSessionID = User.get_curr_session(); can execute before the success call completes.
You have a couple of options, you can try and update your code to be more async capable, using callbacks or other methods, or specify that you want your ajax call to be synchronous.

Categories

Resources