I am trying to call the function in onPaymentMethodReceived:function (obj) method but I am getting an error the obj contains the payments nonce.
My JS code is
this.braintree.setup(this.clientToken, "dropin", {
container: "dropin-container",
onPaymentMethodReceived:function (obj) {
console.log("nonce "+obj.nonce);
this.ckeckoutClick(obj.nonce) //I want call this function which is post request to server//
}
})
my HTML is
<form id="checkout">
<div id="dropin-container"></div>
<input type="submit" value="Place Order">
</form>
Please tell me what I am doing wrong
Thank you
If you want to use this inside the function use () => instead of function ()
this.braintree.setup(this.clientToken, "dropin", {
container: "dropin-container",
onPaymentMethodReceived: (obj) => {
console.log("nonce "+obj.nonce);
this.ckeckoutClick(obj.nonce) //I want call this function which is post request to server//
}
})
otherwise this.checkoutClick() will call checkoutClick on braintree or from wherever the callback is called.
Related
In this scenario I'm using the ui-bootstrap typeahead to capture an object from an external api. Using the select callback I'm getting that object and have the results set in a separate function within my controller.
The issue is that I want to take those results and send them off to a separate api with a click function I already have set up. My question is how do i get the results of the type-ahead into the click function to post? The user flow is as follows.
<div>
<input type="text" placeholder="Find A Game"
typeahead-on-select="setGames($item)"
ng-model="asyncSelected"
typeahead="test.name for test in getGames($viewValue)"
typeahead-loading="loadingLocations" typeahead-min-length="3"
typeahead-wait-ms="500" typeahead-select-on-blur="true"
typeahead-no-results="noResults">
</div>
<div ng-show="noResults">
No Results Found
</div>
<button ng-disabled="!asyncSelected.length"
ng-click="addtodb(asyncSelected)">Add To Database</button>
As you can see the label is set to the items name and this works fine. When the user selects the name I then use typeahead-on-select="setGames($item)" to send off the entire object to its own funtion. From there I want to take the object and pass it to another function that you can see within the button tags ng-click. I currently have it passing the model, but what I really want is to pass the entire object within $item from the select event. So far my controller looks like this:
angular.module('2o2pNgApp')
.controller('GiantCtrl', function ($scope, $http, TermFactory, $window, SaveFactory) {
$scope.getGames = function(val) {
return $http.jsonp('http://www.example.com/api/search/?resources=game&api_key=s&format=jsonp&limit=5&json_callback=JSON_CALLBACK', {
params: {
query: val
}
}).then(function(response){
return response.data.results.map(function(item){
return item;
});
});
};
$scope.setGames = function (site) {
var newsite = site;
};
$scope.addtodb = function (asyncSelected, newsite) {
TermFactory.get({name: asyncSelected}, function(data){
var results = data.list;
if (results === undefined || results.length === 0) {
SaveFactory.save({vocabulary:'5', name:newsite.name, field_game_id:newsite.id}, function(data) {
$window.alert('All Set, we saved '+asyncSelected+' into our database for you!')
});
} else {
// do stuff
});
}
});
No matter what I do I cant seem to pass the entire $item object into this click function to post all the info i need.
Via New Dev in Comments:
$item is only available locally for typeahead-on-select... you can
either assign it to some model within your controller, or, in fact,
make the model of typeahead to be the item: typeahead="test as
test.name for test in getGames($viewValue)" – New Dev
I'm having a problem with logging out on my website. I have looked at the documentation on the parse website but it does not really provide much detail on how to log out the user, also does not help when I am not proficient with JavaScript.
When I click my log out button, it just refreshes the page and nothing more but I would like to take it back to the sign in screen.
My current script file that I have written is shown below (for obvious reasons I have removed my parse unique ids):
$(function() {
Parse.$ = jQuery;
Parse.initialize("MY CODE HERE", "MY CODE HERE");
$('.form-logout').on('submit', function(e) {
// Prevent Default Submit Event
e.preventDefault();
//logout current user
var currentUser = Parse.User.current();
if (currentUser) {
Parse.User.logout();
window.location="Sign_In.html";
} else {
window.location="Sign_In.html";
}
});
});
The section where I create the button is located here in my html file:
<form class="form-logout" role="form">
<input type="submit" value="Logout" id="logout" class="btn btn-primary btn-lg">
</form>
Add
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.4.2.min.js"></script>
to your page.
Then use this script:
jQuery(document).ready(function() {
Parse.$ = jQuery;
Parse.initialize("...", "...");
$('.form-logout').on('submit', function (e) {
// Prevent Default Submit Event
e.preventDefault();
console.log("Performing submit");
//logout current user
if ( Parse.User.current() ) {
Parse.User.logOut();
// check if really logged out
if (Parse.User.current())
console.log("Failed to log out!");
}
// do redirect
//window.location.replace("Sign_In.html");
// or
window.location.href = "/Sign_In.html";
});
});
create a function
const handleLogout = () => {
window.localStorage.clear();
window.location.reload(true);
window.location.replace('/');
};
then call it in this way
<Button className="button" onClick={() => handleLogout()}>
<i className="fas fa-power-off"></i>
</Button>
You can self-execute a custom callback function on the logout() object.
That is you first wrap your logout() function within an anonymous function, a syntax like:
function(){logout()}
You self execute it:
(function(){
logout()
})()
and you pass your callback as parameter!
(function(aFunctionIsToBePassedHere){
logout()
})(myCallbackFunction())
All of this become:
function logout() {
(function(myCallbackGoesHereAsVariable) {
Parse.User.logOut();
})(myFunctionToShowTheLoginScreen())
}
and then you bind the logout() function to your form.
I have an upload view that needs to be used to upload three attachments. Now I used this code for the UI part in the view:
<div id="theDeliveryNoteContent">
<form action='Order/Save' method="post" enctype="multipart/form-data" id="deliveryNoteForm">
<div >
<label style="text-align: left;">Delivery note:</label>
<input type="file" name="DeliveryNoteFile" id="DeliveryNote" style="width: 400px;" />
<div style="margin-top:4px;margin-bottom:4px" >
<input type="submit" value="Upload" id="btnAddAttachment" />
</div>
</div>
</form>
</div>
Now the method that I want to call is situated inside my Orders controller. Here is the method I'm using. The code works fine until the return part.
[HttpPost]
public ActionResult Save(HttpPostedFileBase DeliveryNoteFile)
{
try
{
string customer = GetCustomerLinkedToPortalUser();
var uploadPath = "C:\\Attachments\\" + customer;
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
if (DeliveryNoteFile != null)
{
var fileName = Path.GetFileName(DeliveryNoteFile.FileName);
var physicalPath = Path.Combine(uploadPath, fileName);
DeliveryNoteFile.SaveAs(physicalPath);
}
return RedirectToAction("Index");
}
catch (Exception)
{
throw;
}
}
The problem is that when the method returns to the screen it refreshes the screen and all the entered information is lost. I want to save the file to that directory and come back to the order screen and upload the next file. Now how I'm supposed to do that I'm not sure so that is what I need help with.
A colleague mentioned that I could use jQuery.Form script to do an ajax call so what I did is I added the jquery.form.js script to my project, did the referencing and I also added this to my javascript:
$("#deliveryNoteForm").ajaxForm({
target: "#theDeliveryNoteContent"
});
So now it returns to my screen, but it messes up the layout and refreshes the screen (seems) anyway. Is there any other easy way to return to the previous screen with the method which I used without losing all the entered information?
you need async file upload. Use this. Read some docs it is all simple.
Example:
Javascript initialize:
$(function () {
$('#DeliveryNote').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});
});
Html:
<input id="DeliveryNoteFile" type="file" name="files[]" data-url="yourUploadController/Save/" style="width: 400px;" />
and remove submit button.
function loadDate()
{
$.ajax({
type : "POST",
url : "/ajax/date",
data : "text",
success : function(response)
{
$('#dateSection').html(response);
},
error : function(e)
{
alert('Ajax Request Failed: ' + e);
}
});
}
function loadPoop()
{
if(true)
$.ajax({
type : "POST",
url : "/ajax/poop",
data : "text",
success : function(response)
{
$('#poopSection').html(response);
},
error : function(e)
{
alert('Ajax Request Failed: ' + e);
}
});
}
This is essentially what I'm trying to do but nothing I try works beyond making one call
function ajaxCaller(function_name)
{
setInterval(window[function_name], 1000);
//or
setInterval(function_name, 1000);
}
html page
<button type="button" onclick="loadDate()">Date Button</button>
<div id="dateSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller(loadDate())">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller(loadPoop())">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>
Functions in JavaScript are first-class objects. That means that you can use them the same way you would use any other ordinary variable. If you loose the parentheses in your HTML code:
<button type="button" onclick="ajaxCaller(loadDate)">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller(loadPoop)">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>
You tell JavaScript not to call the function loadPoop or loadDate, but pass it directly to function ajaxCaller as a variable.
With the brackets () you are first running loadDate, after which you pass the result of loadDate to ajaxCaller. In this case both loadDate and loadPoop return nothing, so ajaxCaller will also recieve nothing, and no timeout gets set.
Samw's answer is correct - but I want to try and elaborate a bit on the matter.
In your code you're passing the return value of loadPoop() and loadDate() as a parameter to ajaxCaller(). Basically - first loadPoop() gets called, and then the value it returns (which is nothing in your case) gets passed on into ajaxCaller().
In Samw's answer a pointer to the functions loadPoop() and loadDate() is passed as a parameter, allowing you to later call the functions using function_name(). The same thing is happening with setInterval, where you pass a pointer to the function you want to invoke within setInterval as a parameter.
If you think of the parameters not as an object or a value but as addresses then this makes a bit more sense - basically what happens is that the execution of the code "jumps" to the memory address (a variable name is just what we humans call that specific memory address) - and since a function starts executing at that point in memory - it just carries on.
Now this might be a bit of an oversimplification, but hopefully it'll give you a better idea of why this is OK, and why your method didn't work.
Welcome to the world of pointers!
Since you're using jQuery I'd be inclined to rework the code a little bit to take advantage of it. You can separate out the inline code which is a good thing, and you can reduce the number of ajax functions to one by passing in the function parameter.
<button type="button" data-fn="default">Date Button</button>
<div id="dateSection">Ajax Me Bro!</div>
<button type="button" data-fn="date">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" data-fn="poop">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>
$(function () {
function loadAjax(fn) {
$.ajax({
type: "POST",
url: "/ajax/" + fn,
data: "text",
success: function (response) {
$('#' + type + 'Section').html(response);
},
error : function (e) {
alert('Ajax Request Failed: ' + e);
}
});
}
}
$('button').click(function () {
var fn = $(this).data('fn');
switch (fn) {
case 'date':
setTimeout(function () {
loadAjax('date');
}, 1000);
break;
case 'poop':
setTimeout(function () {
loadAjax('poop');
}, 1000);
break;
default:
loadAjax('date');
break;
}
});
});
Declaration :
function ajaxCaller(fn) {
setInterval(fn, 1000);
}
Usage :
ajaxCaller(loadDate) // instead of : ajaxCaller(loadDate())
ajaxCaller(loadPoop) // instead of : ajaxCaller(loadPoop())
Don't call fn yourself, let setInterval do this job.
i think the argument can't be a function !! anyway just use following
function ajaxCaller(value)
{
if (value=="loadPoop")
setInterval(function(){loadPoop()},1000);
if (value=="loadPoop")
setInterval(function(){loadDate()},1000);
}
and change arguments to be string
<button type="button" onclick="ajaxCaller("loadDate")">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller("loadPoop")">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>
i think solution here is more dynamic though:
How to execute a JavaScript function when I have its name as a string
in .gsp file i have javaScript function
<script type="text/javascript">
function getCurrentItemNumber(){
return document.getElementById('item_itemNumber').innerHTML.substr(6);
}
</script>
and in g:remoteLink I like to pass param using that function
something like following ...
<g:remoteLink id="remove_item_button" action="removeItem" update="itemBox"
params="[itemNumber:getCurrentItemNumber()]">- Remove Item</g:remoteLink>
How can I achieve that?
AS workaround I can suggest following
change g:remoteLink to simple link
"<"a id="remove_item_button" class="btn small primary" onclick="removeItem();">- Remove Item "<"/a>
Add javaScript function which will submit data via AJAX
function removeItem() {
$.ajax({type:'POST',
data:{'itemNumber':getCurrentItemNumber()},
url:'${createLink(action: 'removeItem')}',
success:function (data, textStatus) {
jQuery('#itemBox').html(data);
}});
}