json parsing in backbone - backbone.js

I have a success callback function which returns the following always :
{"ss":0,"me":"Invalid Username or Password"}
success :function(result){
console.log("RESULT : "+result.ss);
}
But this always ends up as undefined.. If i print the result, i get the above array. If i return result.ss or result.me i get undefined.
I think there is a very silly reason for why this is happening, but i cannot get my head around.
Backbone View(removing other codes) :
this.model.save({un : username,pd : password, ky : ky}, {
success :function(result){
console.log("RESULT : "+result.ss);
return false;
if(result.ss==1){
$("#login_message").addClass('alert-success');
var userType = result.pp.ut;
if(userType=="T"){
window.location.href="trainer/index.html";
}else if(userType=="C"){
window.location.href="clients/index.html";
}else if(userType=="A"){
window.location.href="admin/index.html";
}else{
return false;
}
return false;
}
if(result.ss==0){
console.log(result);
$("#login_message").addClass('alert-error');
console.info("Failed to Log In.");
}
return false;
},
error: function(res){
console.log(res);
return false;
}
});
return false;

Backbone success function has the result parameter after model parmeter, you are using model instead of result.
success:function(model, response){}

Related

How to return data from web api controller using angularjs?

Hi I am developing one web api with angularjs application. I am doing file upload module. I am facing problem in returning object once file upload is finished.
Below is my api code to save file related data to database and if it is succsfull I am returning object.
NCT_FileUpload obj = new NCT_FileUpload();
obj.file_path = uploadPath;
obj.user_id =9;
entityObject.NCT_FileUpload.Add(obj);
int result = entityObject.SaveChanges();
if (result == 1)
{
return Request.CreateResponse<NCT_FileUpload>(HttpStatusCode.OK, obj);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "1");
}
This is my angularjs code.
$scope.uploadFiles = function () {
$scope.uploading = true;
uploadService.uploadFiles($scope)
// then() called when uploadFiles gets back
.then(function (data) {
// promise fulfilled
$scope.uploading = false;
if (data === '') {
alert("Done!!!")
$scope.formdata = new FormData();
$scope.data = [];
$scope.countFiles = '';
$scope.$apply;
} else {
alert("Shit, What happended up there!!! " + data);
}
}, function (error) {
$scope.uploading = false;
//Server Error
alert("Shit2, What happended up there!!! " + error);
}
);
};
Below is my service code in angularjs
if (typeof response.data === 'string') {
return response.data;
} else {
return $q.reject(response.data);
}
Here i want to check with object and not as string.
I am able to save data in server, If i put below code in api controller i am able to display done. But i am returning object so my data will not be empty. Currently my error function is executing. I want to handle object returned from api in success function. Is there any way to do this? Any help would be appreciated. Thank you.
return new HttpResponseMessage(HttpStatusCode.OK) ;
I think the problem here is the generic parameter. Change this:
return Request.CreateResponse<NCT_FileUpload>(HttpStatusCode.OK, obj);
To this:
return Request.CreateResponse(HttpStatusCode.OK, obj);

AngularJS access JSON Object returned from $http.get

I try to access to json object generated by google api.
function getAvengers() {
return $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA')
.then(getAvengersComplete)
.catch(getAvengersFailed);
function getAvengersComplete(response) {
return response.data;
}
function getAvengersFailed(error) {
console.log('XHR Failed for getAvengers.' + error.data);
}
}
TestCtrl.dataTest = dataservice.getAvengers();
console.log(TestCtrl.dataTest.status);
Log generate undefined.
Could you help me?
Thanks
As getAvengers returns with a promise, you cannot use it's result as an immediate value, but you can subscribe to it's resolution. See a promise tutorial for more details.
function getAvengers() {
return $http.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA')
.then(getAvengersComplete)
.catch(getAvengersFailed);
function getAvengersComplete(response) {
return response.data;
}
function getAvengersFailed(error) {
console.log('XHR Failed for getAvengers.' + error.data);
}
}
TestCtrl.dataTest = null;
dataservice.getAvengers().then(function(data) {
TestCtrl.dataTest = data;
console.log(TestCtrl.dataTest.status);
});

Return when .each is completed

Promise.try(function (){
return Promise.all(splitup); // [Show, me, stocks, for, Google, and, Microsoft]
}).each(function (item) { // Looping through entities, [Show] [me] [stocks] ...
alchemyapi.entities('text', item, { 'sentiment' : 1}, function (response) {
if(response.entities) { // An entity is found, ex. Microsoft
if(response.entities[0].type === "Company") {
requestBody.push(item);
console.log("Item was found, added " + item);
} else {
console.log(item + " Is not a company");
}
} else { // no entity found for that one word
console.log("No entity found for " + item);
}
});
}).then(function (response) {
// send requestBody when loop is completed.
});
I start by returning an array of strings splitup so I can loop through each element on line 3.
Let's say the splitup array looks like: [Apple, And, Mexico]
Apple is a company, so if(response.entities) returns true, it then checks the JSON response to see if it is a company, that statement returns true and It's added to the new requestBody array I'm building up.
Next, the word 'And' returns false on if(response.entities) so It goes to the else statement.
Next, let's pick Mexico, It'll return true for if(response.entities) but return false on if(response.entities[0].type === "Company")
My question is, I'd like to return the new requestBody array when It has completed looping through each item, but I'm not entirely sure how I can tell when the loop is completed, and when to return requestBody
You need to use Promise.filter instead of Promise.each. Promise.filter filters the given array to another using filterer function passed to it.
So when you encounter a company ('Apple') you resolve with its value, if its anything else ('Mexico' and 'And') you resolve with false.
Promise.filter(splitup, function (item) { // Looping through entities, [Show] [me] [stocks] ...
return new Promise(function(resolve, reject) {
alchemyapi.entities('text', item, { 'sentiment' : 1}, function (response) {
if(response.entities) { // An entity is found, ex. Microsoft
if(response.entities[0].type === "Company") {
console.log("Item was found, added " + item);
return resolve(item);
} else {
console.log(item + " Is not a company");
return reject(false);
}
} else { // no entity found for that one word
console.log("No entity found for " + item);
return reject(false);
}
});
});
}).then(function (requestBody) {
// send requestBody when loop is completed.
});
Ok too late :). Here was my result:
var alchemyapi = require('alchemy-api');
var Promise = require('bluebird');
var alchemyapi = new alchemyapi(<YOUR_KEY>);
var test = ['Microsoft', 'and', 'Apple'];
Promise.filter(test, function(item) {
return getCompanyName(item).then(function(){
return true;
}, function(reason) {
console.log(reason.message);
return false;
});
}).then(function(requestBody){
console.log(requestBody);
});
function getCompanyName(item) {
return new Promise(function(resolve, reject) {
alchemyapi.entities(item, {sentiment: 1}, function (err, response) {
if (err) reject(err);
if (response.entities.length > 0) { // An entity is found, ex. Microsoft
if (response.entities[0].type === "Company") {
resolve(item);
} else {
reject(new Error(item + " Is not a company"));
}
} else { // no entity found for that one word
reject(new Error("No entity found for " + item));
}
});
});
}

how to get JSON array value from internet

I want to get value of an array from JSON code in internet. from this URL : http://olympics.clearlytech.com/api/v1/medals/
after that, I want to display that array of my script without rewrite that JSON code on this URL http://olympics.clearlytech.com/api/v1/medals/
so, what code (script) that I can use?
for example, I want to display value from this array
var JSONs = {
example:['one','two','three']
};
the code is
document.write(JSONs.example[0]);
but if I want get the array value from the internet, what code/script that I can use?
Using jQuery, here is an example. In the success event, turn the resulting json text into a json object. You could also set the content type as json so you wouldn't have to call the JSON.parse().
$.ajax({
url: "http://olympics.clearlytech.com/api/v1/medals/",
success: function(data) {
var json = JSON.parse(data);
}
});
This is another way of doing the same i hope you asked how to parse through each value just try this in jsfiddle
$(document).ready(function(){
alert("here");
$.getJSON("http://olympics.clearlytech.com/api/v1/medals/",function(data){
$.each(data,function(key,value){
alert(data[key].country_name);
alert(data[key].rank);
console.log(data[key].rank));
});
});
});
public void handleResponse(String response)
{
// display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
jso = new JSONObject(response);
String status = jso.getString("status");
int valid=jso.getInt("valid");
// display("Welcome : "+UName);
if(valid>0)
{
if( status.equalsIgnoreCase("") || status==null || status.equalsIgnoreCase("Failed"))
{
invalid.setText("Invalid password");
//reset();
pwd.setText("");
}
else
{
//display(status);
intObj=new Intent(MainActivity.this,Design_Activity.class);
intObj.putExtra("Username", mUname);
startActivity(intObj);
MainActivity.this.finish();
}
}
else
{
invalid.setText("Invalid userid");
uname.setText("");
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Althought you want us to do everything, thats why your question went negative. Anyhow this is how you can do it in plain ajax
function getData(){
// Initialize the Ajax request
var xhr=new XMLHttpRequest();
xhr.open('get', 'http://olympics.clearlytech.com/api/v1/medals/');
// Track the state changes of the request
xhr.onreadystatechange=function(){
// Ready state 4 means the request is done
if(xhr.readyState === 4){
// 200 is a successful return
if(xhr.status === 200){
alert(xhr.responseText); // 'This is the returned text.'
}else{
alert('Error: '+xhr.status); // An error occurred during the request
}
}
}
// Send the request to send-ajax-data.php
xhr.send(null);
}

Ext Js ajax request not working for failure function

here is my function sending ajax request for checking email duplication while getting response from my php file , not falling on failure function it returns only in success function , for this i have checked result.responseText == to "false" and with else condition now in this condition it shows the error popup message too but donot abort the request continuoues its execution and saves the data
function email_check(userType) {
//alert(userType);
var extmail= Ext.Ajax.request({
url: '<?= Extjs_renderer::ajaxurl();; ?>ajax/emailcheck',
success: function ( result, request ) {
if(result.responseText=='false'){
//Ext.Ajax.abort(extmail); tried
Ext.MessageBox.alert('Error', "email already exist");
// return false;
//Ext.getCmp('email').setValue(''); works
}else {
return true;
}
},
failure: function(response, options) {
Ext.MessageBox.alert('Error', "email already exist fail");
},
params: {merc_mem_tab:userType }
});
}
here is my ajax.php code
function emailcheck(){
$get_email=$this->db->query("select * from customers where email='".$_REQUEST['merc_mem_tab']."'");
if($get_email->num_rows==0){
echo "true";
return true;
}else{
echo "false";
// echo "{success: true}";
return false;
}
}
while on my panel handler i am also trying to check the response but could not succeeded
if('<?= $this->controller->name; ?>'=="customers"){
//alert(Ext.getCmp('email'))
if(email_check(Ext.getCmp('email').getValue()) == false){
return false;
}
}
You can't return from an ajax request, It is asyncron, and this bit of code if(email_check(Ext.getCmp('email').getValue()) == false) won't wait for the answer.
Also the failure is as Imad said, just for http failures not for false responses. your code to check for response false was correct but i suggest you call a saving method on the success function.Like:
function email_check(userType) {
//alert(userType);
var extmail= Ext.Ajax.request({
url: '<?= Extjs_renderer::ajaxurl();; ?>ajax/emailcheck',
scope: this,
success: function ( result, request ) {
if(result.responseText=='false'){
Ext.MessageBox.alert('Error', "email already exist");
//do nothing else
}else {
this.saveData();
}
},
failure: function(response, options) {
Ext.MessageBox.alert('Error', "Communication failed");
},
params: {merc_mem_tab:userType }
});
}
The choice of success or failure callback is based on the HTTP response code. So, if you want to reach the failure function, you'll have to do some :
function emailcheck(){
$get_email=$this->db->query("select * from customers where email='".$_REQUEST['merc_mem_tab']."'");
if($get_email->num_rows==0){
echo "true";
return true;
}else{
throw new Exception("Error : Email Already Exists !");
}
}
It should provoke an error 500 (exception unhandled) and ExtJS will identify it as a failure response.

Resources