Im learning Angular JS im using a REST api in slim that returns JSON data objects. I have a search controler where i have a submitform method wich gets data. But now i have another controler that also needs this data. now i have read about this and found that it can be don using a factory service but for some reason im getting this error:
TypeError: undefined is not a function
at http://localhost/c2dmobile/js/main.js:72:23
at https://code.angularjs.org/angular-1.0.0.min.js:8624:11
at wrappedCallback (https://code.angularjs.org/angular-1.0.0.min.js:6585:59)
at https://code.angularjs.org/angular-1.0.0.min.js:6622:26
at Object.Scope.$eval (https://code.angularjs.org/angular-1.0.0.min.js:7769:28)
at Object.Scope.$digest (https://code.angularjs.org/angular-1.0.0.min.js:7641:25)
at Object.Scope.$apply (https://code.angularjs.org/angular-1.0.0.min.js:7855:24)
at done (https://code.angularjs.org/angular-1.0.0.min.js:8844:20)
at completeRequest (https://code.angularjs.org/angular-1.0.0.min.js:8984:7)
at XMLHttpRequest.xhr.onreadystatechange (https://code.angularjs.org/angular-1.0.0.min.js:8954:11) angular-1.0.0.min.js:5525
(anonymous function) angular-1.0.0.min.js:5525
(anonymous function) angular-1.0.0.min.js:4659
wrappedCallback angular-1.0.0.min.js:6587
(anonymous function) angular-1.0.0.min.js:6622
Scope.$eval angular-1.0.0.min.js:7769
Scope.$digest angular-1.0.0.min.js:7641
Scope.$apply angular-1.0.0.min.js:7855
done angular-1.0.0.min.js:8844
completeRequest angular-1.0.0.min.js:8984
xhr.onreadystatechange
here is the code:
//SHARE DATA BETWEEN CONTROLLERS
c2dApp.factory("ShareData", function() {
return {
//ZipCode: function() {return ZipCode;},
resList: function() {return ResList;}
};
});
//CONTROLLERS: SEARCHLIST
c2dApp.controller('SearchResultController', function($scope, ShareData) {
//NEEDS THE RESTULT FROM SEARCH
});
//CONTROLLERS: SEARCH
c2dApp.controller("SeachController", function($scope, $http, ShareData) {
$scope.message = 'dit is search';
$scope.myData = {};
$scope.myData.haveZip = false;
$scope.searchForm = {};
$scope.searchForm.zipCode = "";
$scope.searchForm.getFormFieldCssClass = function(ngModelController) {
//console.log("getting css class: " + ngModelController.$valid) ;
if(ngModelController.$pristine) return "";
return ngModelController.$valid ? "fieldValid" : "fieldInvalid";
};
$scope.submitForm = function() {
//console.log("--> Submitting form");
$http({
url: "http://localhost/c2dapi/search",
data: $scope.searchForm,
method: 'POST',
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data){
//console.log("OK", data);
if (angular.equals(data[0], 'no_location_found')) {
console.log('geen lokatie gevonden');
}
if (angular.equals(data[0], 'restaurants_found')) {
console.log('restaurant lijst');
console.log(data);
ShareData.ResList() = data; // <------ REturns ERROR
}
}).error(function(err){"ERR", console.log(err)});
};
});
//UPDATE
cshion awnser works partial
ShareData.ResList() = data;
returns the error ReferenceError: Invalid left-hand side in assignment
so i changed it to; ShareData.ResList = data;
now the json objects are found when i call ShareData.ResList
but this is only after the post, i want to so something like
if (ShareData.ResList) {
}
the problem is that ShareData.ResList is never "undefined" but returns:
function () {
return ResList;
}
when its not set? i want it do return false.. how can i do this ?
You can share data between controllers , directives ,etc with Service or Factory.
Using factory:
c2dApp.factory("ShareData", function() {
var ResList;
return {
resList: function() {return ResList;}
};
});
In your controller:
ShareData.resList() = data
Related
I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?
I am trying to integrate google-recaptcha but no success.
Getting error
feedback.js:39 Uncaught TypeError: grecaptcha.render is not a function
main.js
'googlerecaptcha':'https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit',
define(['ojs/ojcore', 'knockout', 'jquery', 'appController', 'ckeditor', 'googlerecaptcha', 'ojs/ojlabel',
'ojs/ojknockout', 'ojs/ojinputtext', 'ojs/ojformlayout'],
function (oj, ko, $, app, ckeditor, grecaptcha) {
/**
* The view model for the main content view template
*/
function feedbackViewModel() {
var self = this;
// For small screens: labels on top
// For medium screens and up: labels inline
this.labelEdge = ko.computed(function () {
return app.smScreen ? "top" : "start";
}, this);
onloadCallback = function (a) {
grecaptcha.render('submit', {
'sitekey': 'YOUR_API_KEY',
'callback': self.onSubmit
}, true);
};
this.handleActivated = function (info) {
};
self.onSubmit = function (token) {
console.info("google recatpcha onSubmit", token)
//do validation/application code using token
var data = {secret: grecaptcha, response: recaptchaToken};
$.post({
url: "https://www.google.com/recaptcha/api/siteverify",
form: data
}).then(function (e) {
//recaptcha service called...check result
var resp = JSON.parse(e);
if (resp.success == false) {
console.info("recaptcha token outcome is false")
} else {
console.info("recaptcha token validated")
}
});
};
}
return feedbackViewModel;
});
Do you have a mapping for 'googlerecaptcha' in src/js/path_mapping.json? If I go to https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit, I do not see that it is returning any valid object. So most likely 'grecaptcha' variable is undefined.
reCaptcha + RequireJS
Looks like reCaptcha is a function that has to be executed vs an object that can be interacted with directly. So you may need a different approach, something mentioned in this thread.
how to pass a variable with the help of ajax jquery into a function directly, which is on another page
function show_data2(str1) {
xml2http = new XMLHttpRequest();
xml2http.onreadystatechange = function () {
if (xml2http.readyState === 4 && xml2http.status === 200) {
document.getElementById("show_data_sal").innerHTML = xml2http.responseText;
}
};
xml2http.open("POST", "functions.php?r=" + str1, true);
xml2http.send(str1);
};
functions.php
class querydb
{
function useHere()
{
...I want to use that variable 'r' here.
}
}
If you are using jQuery, this will be the easiest way to send post data via ajax:
var jqxhr = $.ajax( {
method: "POST",
url: "functions.php",
data: { r: "some value", s: "another value" }
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
function.php
class querydb
{
function useHere()
{
// We're sending our post data as json so we'll need php to decode it for us to use.
$foo = json_decode($_POST[], true);
// you can now access your variables like an array
$bar = $foo['r'];
}
}
Just be sure to clean anything from post before you do anything with it to prevent any malicious parameters coming through
Here is my code I am trying to access the content on HTTP page from an HTTPS page it is giving me an error in browser console that it is an insecure content, following is an error ' Loading mixed (insecure) active content on a secure page "http://pnrbuddy.com/api/station_by_code/code/cnb/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/906544ca31f9c0048e80bde8127556af828e313b" ' , it is showing Json inbrowser console but unable to read it. How can I read that JSON?
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
//////////////////////////////////////////////
$.ajax({
url: siteurl,
type: "GET",
dataType: 'json',
/* headers: {
"accept": "application/json;odata=verbose",
}, */
success: function (data) {
alert("Success");
alert(data.Station);
/* $.each(data.d.results, function (index, item)
{
alert("My ID"+index);
alert("Item"+item);
});
//var str=JSON.parse(data);
var myResults = [];
$.each(data, function (index, item) {
alert("dsfsd"+item.station_by_code)
myResults.push({
id: item.id,
//text: item.first_name + " " + item.last_name
});
}); */
},
error: function (error) {
alert("IN Error");
alert(JSON.stringify(error));
}
});
/////////////////////////////////////////////
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
//////////////////////////////////////////////
$.ajax({
url: siteurl,
type: "GET",
dataType: 'json',
success: function (data) {
alert("Success");
alert(" Code : "data.stations[0].code+" Name : "+data.stations[0].name);
},
error: function (error) {
alert("IN Error");
alert(JSON.stringify(error));
}
});
/////////////////////////////////////////////
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
I have a controller and factory defined as below.
myApp.controller('ListController',
function($scope, ListFactory) {
$scope.posts = ListFactory.get();
console.log($scope.posts);
});
myApp.factory('ListFactory', function($http) {
return {
get: function() {
$http.get('http://example.com/list').then(function(response) {
if (response.data.error) {
return null;
}
else {
console.log(response.data);
return response.data;
}
});
}
};
});
What confuses me is that I get the output undefined from my controller, and then the next line of console output is my list of objects from my factory. I have also tried changing my controller to
myApp.controller('ListController',
function($scope, ListFactory) {
ListFactory.get().then(function(data) {
$scope.posts = data;
});
console.log($scope.posts);
});
But I receive the error
TypeError: Cannot call method 'then' of undefined
Note: I found this information on using a factory through http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html
You need to either use a callback function or just put a return before $http.get...
return $http.get('http://example.com/list').then(function (response) {
if (response.data.error) {
return null;
} else {
console.log(response.data);
return response.data;
}
});
$http.get is asynchronous so at the time you try to access it (inside your controller) it may not have data (hence you get undefined).
To solve this I use .then() after I call the factory method from my controller. Your factory then would look something like:
myApp.factory('ListFactory', function($http) {
return {
get: function() {
$http.get('http://example.com/list');
}
};
});
And your controller:
myApp.controller('ListController', function($scope, ListFactory) {
ListFactory.get().then(function(response){
$scope.posts = response.data;
});
// You can chain other events if required
});
Hope it helps