catch response when send jsonp request phonegap - javascript

I write application by phonegap
Server Side I write by nodejs
exports.login = function(request, response) {
var keys = Object.keys(request.query);
request.body= JSON.parse(keys[1]);
Accounts.findOne({
name : request.body.name
}, function(err, docs) {
if (!docs) {
response.json('{"error": "user-not-found"}');
} else {
console.log("docs: ", docs);
Accounts.validatePassword(request.body.password, docs['hashedPass'], docs['salt'], function(error, res) {
if (error) {
response.json(error);
}
if (res) {
generateToken(request.body.name, request.body.device, function(res) {
if (res) {
response.json('{"token": "' + res + '"}');
} else {
response.json('{"error": "cant-create-token"}');
}
});
} else {
response.json('{"error": "invalid-password"}');
}
});
}
})
}
Phonegap: I write function to login
function LoginUser(info)
{
var varUrl=server+"/auth/login";
$.ajax({
url:varUrl,
type:"GET",
contentType:"application/json",
headers: {
Accept:"application/json",
"Access-Control-Allow-Origin": "*"
},
data:info,
dataType:"jsonp",
success:function(data)
{
console.log("HERE");
console.log(data);
},
error: function(err){
console.log(err);
}
});
}
and I request it will like this http://localhost:3000/auth/login?callback=jQuery161014894121675752103_1361459462241&{%22name%22:%22fdfdfd%22,%22password%22:%22fdfdfdfd%22}&_=1361459615743
and when I see in the response of tab network of developer of chrome is "{\"error\": \"user-not-found\"}"
but I can not catch this repsonse in function LoginUser(info) above
How to get it because in console it print error: function(err){
console.log(err);
}
I dont know why.
Can you help me.

On the server side you have to use callback and in the response of your
jsonp file you need to do:
jQuery161014894121675752103_1361459462241({"error": "user-not-found"})
Where the function name comes from the callback variable in your jsonp request.
Cause a jsonp request just "include" a script tag in your site, which can execute js (basically).

Related

Calling sync ready made async ajax javascript function

I want to call this function on button click after login and wait for result, to get token value. This function cannot be changed, it is async and supplied from other currently unavailable team.
I already tried something like this, but with no success. I get web service results, but I can't write appropriate sync call to wait to return token.
function getToken() {
param1 = "123456";
ajax_oauth(param1, function (success, response) {
success: return response.token;
});
}
function ajax_oauth(param1, callback) {
APP.debug("oauth login with param1 " + param1);
try {
APP.blockUI();
var DeviceID = APP.readRegistry(APP_CONFIG.REGISTRY.DeviceID);
//---------------------------------------------------------------
$.ajax(
auth_token_url,
{
method: "GET",
accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
'param1': param1,
'deviceId': DeviceID
}),
xhrFields: {
withCredentials: false
},
statusCode: {
201: function (response) {
APP_STATE.hasOauth = true;
APP.debug('got response 200 from oauth');
auth.login(response.token); //TODO read expiration from token
try {
var decoded = jwt_decode(response.token);
APP_STATE.uid = decoded.uid;
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
},
401: function () {
},
500: function () {
},
503: function () {
}
},
success: function (response) {
APP.unblockUI();
APP_STATE.restAvailable = true;
},
error: function (jqXHR, textStatus, errorThrown) {
APP.unblockUI();
APP_STATE.restAvailable = false;
APP.restError(auth_token_url, jqXHR, errorThrown, textStatus);
APP.callback(callback, false);
}
}
);
} catch (err) {
APP.error("unable to do oauth login, " + err);
}
};
After user clicks on login button, I want to call function ajax_oauth and to return token if params ok. If not, to return login error. Login can't be async, as far as I can see.
For whatever reason you can't tap into the original ajax response, you could intercept the request using $.ajaxPrefilter.
From your code it looks like auth_token_url has a global reference. You could use this to intercept the call by matching the outgoing request on the resource URL.
$.ajaxPrefilter('json', function(options, originalOptions, jqXHR) {
if (options.url === auth_token_url) {
jqXHR.done(function(response) {
try {
var decoded = jwt_decode(response.token);
console.log(decoded);
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
});
}
});
Note that this needs to be declared well before the request is made preferably after jQuery is loaded.

Why am I getting Ajax error {"readyState":0,"responseText":"","status":0,"statusText":"error"}

Okay so I have a node js server running on my local machine and I'm trying to make an Ajax call to my server, the server is accepting the request and the request is executing successfully on the server side but on the client side I'm always getting the error response,
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
My code to make Ajax request is as below,
$(document).ready(function() {
$("#button").click(function(e) {
e.preventDefault();
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://192.168.1.3:8080/insertintoplaylist?videoid=' + $("#videoid").val(),
async: true,
dataType: 'json',
success: function(res) {
alert("response"+res);
},
error: function(error) {
alert("error!" + JSON.stringify(error));
}
});
});
});
Here is the code snippet which will be executed when client makes a request to the path as mention in the url parameter of ajax call,
var req = youtube.videos.list({
id: video,
part: 'snippet,id'
},function(err,data,response){
if(err){
console.error('Error: ' + err);
}
if(data){
console.log(data.items);
var dataItem = data.items[0];
writeUserData(dataItem.id,dataItem.snippet.title,dataItem.snippet.thumbnails.medium.url,function(){
res.json({msg:'Saved'});
});
}
if(response){
console.log('Status code: ' + response.statusCode);
}
});
function writeUserData(videoId, title, thumbnail,cb) {
console.log("\nWriting data for video ");
firebase.database().ref('kidspoemTesting/' + videoId).set({
title: title,
thumbnail: thumbnail,
},function(err){
if(err){
console.log("Failed to save data"+err);
console.log("\nWriting data failed for video ");
}
else {
console.log("Data saved");
console.log("\nWriting data succeed for video ");
cb();
}
});
}

Passing parameters to routes in node.js

I am very new to Web Development. I used to do desktop development using WPF and C#. Now I am learning Node.js
I have a model called Party.js in which I define two exports as follows:
module.exports.getAllParties = function(callback){
Party.find().lean().exec(function(err, parties){
if (err) return callback(err, null);
callback(null, parties);
});
};
module.exports.getPartyByPartyCode = function(partyCode, callback){
Party.find({partyCode: partyCode}).exec(function(err, party){
if(err) return callback(err, null);
callback(null, party);
});
};
Now, I also have a route called Party.js in which I have two get methods as follows:
router.get('/', function(req, res, next){
//retrieve all parties from Party model
Party.getAllParties(function(err, parties) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function(){
res.render('Party', {
title: 'Party',
"parties" : parties
});
},
//JSON response will show all parties in JSON format
json: function(){
res.json(parties);
}
});
}
});
});
router.get('/:partyCode', function(req, res, next){
Party.getPartyByPartyCode(function(err, party) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function(){
res.render('Party', {
title: 'Party',
"party" : party
});
},
//JSON response will show all parties in JSON format
json: function(){
res.json(party);
}
});
}
});
});
Now, when I use ajax:
var inputElem = $('#partyForm :input[name="partyCode"]'),
inputVal = inputElem.val(),
data = { partyCode : inputVal },
eReport = ''; //error report
$.ajax(
{
type: "GET",
url: "/Party",
dataType: "json",
data: data,
beforeSend: function(jqXHR, settings)
{
console.log(settings.url);
},
success: function(party)
{
if (party)
{
console.log(party);
return 'Party ' + party.partyName + ' has already taken party code: ' + party.partyCode + '. Please choose a different PartyCode.';
}
else
{
console.log("party does not exist.");
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
alert('ajax loading error... ... '+url + query);
return false;
}
});
My question is: Why the above ajax call returns me all the parties? I just want to get a party whose patyCode is passed in to the ajax call's data....
There are some errors in both your router response code and ajax function:
First correct your router code:
You were not using the provided party code in your model.
router.get('/:partyCode', function (req, res, next) {
var partyCode = req.param('partyCode');
Party.getPartyByPartyCode(partyCode, function (err, party) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//response in dust or jade files
html: function () {
res.render('Party', {
title: 'Party',
"party": party
});
},
//JSON response will show all parties in JSON format
json: function () {
res.json(party);
}
});
}
});
});
Correct Ajax function calling
You must provide the party code as a URL parameter as your router indicates like that /:partyCode. Try the following:
var inputElem = $('#partyForm :input[name="partyCode"]'),
inputVal = inputElem.val(),
eReport = ''; //error report
$.ajax({
type: "GET",
url: "/"+inputVal,
dataType: "json",
data: data,
beforeSend: function (jqXHR, settings) {
console.log(settings.url);
},
success: function (party) {
if (party)
{
console.log(party);
return 'Party ' + party.partyName + ' has already taken party code: ' + party.partyCode + '. Please choose a different PartyCode.';
}
else
{
console.log("party does not exist.");
return true;
}
},
error: function (xhr, textStatus, errorThrown) {
alert('ajax loading error... ... ' + url + query);
return false;
}
});

Meteor.js: Wait for server to finish

I'm running into a scenario where my meteor server call is posting to a remote URL and then returning the result. However, my meteor client is expecting a result right away and its receiving an empty string (the default return).
What is the correct way of implementing this?
Meteor.methods({
run: function(options){
return HTTP.post(apiUrl, {
params:
{
"headers": headers
}
},
function (error, result)
{
if (error)
{
console.log("error: " + error);
}
else
{
console.log("result: " + JSON.stringify(result));
console.log(result.content);
}
})
});
on my client
Meteor.call('run', '1', function(err,response) {
if(err) {
console.log(err);
return;
}else{
r = response;
console.log(JSON.stringify(r));
FileSystem.update({ _id: fileid }, { $set: {taskid:taskid} }, function (e, t) {
if (e) {
}else{
}
});
}
});
I'm expecting on the client side that it waits for the full result to come in which contains the desired data to save to data base (taskid).
You are calling HTTP.post asynchronously. Just remove the callback function and it becomes synchronous, i.e., you will get a return value that contains the result of the call:
Meteor.methods({
run: function(options){
return HTTP.post(apiUrl, {
params:
{
"headers": headers
}
});
});
});

How use the success call back in a delete ajax [NODE.JS]

I'm using the following code to delete a collection in my db:
Client:
$('.destroy').click(function() {
if(confirm("Are u sure?")) {
$.ajax({
type: 'DELETE',
url: '/destroy/' + dataId,
success: function(response) {
console.log('Success');
}
});
} else {
alert('Cancelled');
}
});
Server:
app.get('/destroy/:id', function(req, res) {
var id = req.param("id");
MyModel.remove({
_id: id
}, function(err){
if (err) {
console.log(err)
}
else {
console.log('Collection removed!');
}
});
});
Is working, if i click in the destroy button and reload the page, the collection will not be there, but the success callback function with the: [console.log('Success');] is not running..
I need send a callback from the server to the client ir order to make the success function run???
How make the console.log('Success'); run??
Thanks.
The ajax call probably just times out, as it's never getting a response back from the server.
Send a response from the server
app.get('/destroy/:id', function(req, res) {
var id = req.param("id");
MyModel.remove({
_id: id
}, function(err){
if (err) {
res.end('error');
}
else {
res.end('success');
}
});
});
Then catch it
$.ajax({
type : 'DELETE',
url : '/destroy/' + dataId,
success : function(response) {
if ( response === 'error' ) {
alert('crap!');
} else if (response === 'success' ) {
alert('worked fine!');
}
}
});
This is a simplified example, you can return whatever you like, send statusCodes or whatever.

Categories

Resources