I'm having some trouble accessing the model correctly in a controller for a separate route.
Currently I have this going on...
App.CheckoutRoute = Ember.Route.extend({
model: function(){
return this.modelFor('product');
}
});
And that's working in my template and it seems in the other properties on the controller
App.CheckoutController = Ember.ObjectController.extend({
publishable: 'pk_test_AtBneKs2kGmWkyD60ymyh5fw',
number: '',
cvc: '',
expMonth: '',
expYear: '',
errors: '',
charge: function() {
var p = this.get('model.price');
return p + '00';
}.property('model.price'),
actions: {
tokenize: function() {
//disable the submit button to prevent repeated clicks
$('button[type=submit]').attr("disabled", "disabled");
//Set Stripe Publishable Key
Stripe.setPublishableKey(this.get('publishable'));
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.createToken({
number: this.get('number'),
cvc: this.get('cvc'),
exp_month: this.get('expMonth'),
exp_year: this.get('expYear')
}, this.didCreateToken.bind(this));
return false;
}
},
didCreateToken: function(status, response) {
// console.log(status);
// console.log(response);
if(response.error) {
$('button[type=submit]').removeAttr('disabled');
return this.set('errors', response.error.message);
}else{
var form = $("#payment-form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// post via ajax
$.ajax({
url: 'stripe/submit.php',
type: 'post',
data: $('#payment-form').serialize()
})
.done(function(data, status, xhr) {
console.log(data);
console.log(status);
console.log(xhr);
})
.fail(function(data, status, xhr){
console.log(data);
console.log(status);
console.log(xhr);
});
}
}
});
The problem comes to when I am trying to access the model to update it's quantity property to persist back to my parse server.
I want to do that in the done statement of the didCreateToken function but trying to get the model like normal I get an error in the console saying that it has no method get. How can I gain access to the model to be able to update and .save() the quantity property after the payment in stripe has gone though.
Also everything as far as stripe goes works just fine, I can successfully make payments and get to that done statement.
you're just out of scope, set a reference to this or the model and use it inside the done.
didCreateToken: function(status, response) {
var self = this;
// console.log(status);
// console.log(response);
if(response.error) {
$('button[type=submit]').removeAttr('disabled');
return this.set('errors', response.error.message);
}else{
var form = $("#payment-form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// post via ajax
$.ajax({
url: 'stripe/submit.php',
type: 'post',
data: $('#payment-form').serialize()
})
.done(function(data, status, xhr) {
var model = self.get('model');
console.log(data);
console.log(status);
console.log(xhr);
})
.fail(function(data, status, xhr){
console.log(data);
console.log(status);
console.log(xhr);
});
}
}
Related
I need to send a value from a input form to a nodejs server, which triggers a calculation with this value and needs to update an p element with the result of the calculation on the client side.
How can this be done?
This is what i have:
//Server side:
app.post('/calculate/:id', function(req, res){
var title = 'Tax Calculation';
var tax= taxcalculation(req.params.id);
res.render('index', {
title: title,
tax: tax,
});
});
//Client side:
var income= document.getElementById("income");
var tax = document.getElementById("tax")
$(income).on('change', function() {
console.log("changed");
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function() {
$('#tax').html('<%= tax %>');
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
});
Okay, so you don't give a lot of data, but this sounds as simple as sending a response with the results to the client side in your Node web service that does the calculations and append the result to the P element
Your server code to handle the ajax call should output a json response which will contain the content for the <p>. It should not re-render the whole index page. I don't do a lot of node.js so I'll leave that for you to figure out.
The ajax success function should accept a response as a parameter, and then operate on that response.
Assuming the server response to this ajax request is of the format {"tax": 15.99}:
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function(response) {
if (response.tax || response.tax === 0) {
$('#tax').html(response.tax);
}
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
Good day everybody. I have a question about how to use the right way to save data into SQL database through KnockoutJs. The record are display well in the table. It should be able to save the data via this pop-up Modal. But after I click the Create button in that modal, it only pop-up a failed Message. Can anybody please help me to solve this problem? Thank you very much.
Below is extract from main js file about Save function
var data = ko.toJSON(self.Profiles());
$.ajax({
type: 'POST',
url: '/ajaxCall/insertProAjax',
data: "{ Customer:" + ko.utils.stringifyJson(self.Name) + ",customerRemove:" + ko.utils.stringifyJson(self.CustomerRemove) + "}",
contentType: "application/json",
success: function (data) {
alert("Record has been saved Successfully");
MarkCustomerAsSaved();
$('#AddNewModel').modal('hide');
},
error: function () {
alert("Failed");
}
}).fail(function (xhr, textStatus, err) { alert(err); });
Below is extract from the ViewModel about save function
var Customer = {};
Customer.Id = c.Id;
Customer.Name = c.Name;
Customer.Age = c.Age;
Customer.Address = c.Address;
if (isNewRecord === false) {
$.ajax({
type: "PUT",
url: "/api/CustomerAPI/" + c.Id,
data: Customer
})
.done(function (resp) {
self.Message("Record Updated Successfully ");
self.reset();
})
.fail(function (err) {
self.Message("Error Occures, Please Reload the Page and Try Again " + err.status);
self.reset();
});
}
if (isNewRecord === true) {
isNewRecord = false;
$.ajax({
type: "POST",
url: "/api/CustomerAPI",
data: Customer
})
.done(function (resp) {
self.Message("Record Added Successfully ");
self.reset();
loadData();
}).fail(function (err) {
self.Message("Error Occures, Please Reload the Page and Try Again " + err.status);
self.reset();
});
}
Knockout and Javascript (in this manner) are being processed client side. You will need to create something on the back end to accept your data payload and save it to the database. If you want to stay in the JavaScript family, I would recommend
node.js. Alternatively this is where php, or C# would come into play.
I have a view file which contains a button (link):
<a href id="savebutton" class="btn btn-warning">Save</a>
Somewhere else in this view I have also declared some hidden fields in a form that contain my userid and vacancyid.
echo form_input(dataHiddenArray('userid', $this->auth_user_id));
echo form_input(dataHiddenArray('vacancyid', $vacancydetails[0]->vacancy_id));
These hidden fields translate to:
<input type="hidden" value="2" class="userid">
<input type="hidden" value="1" class="vacancyid">
Now I want to be able to send these values to my controller (via AJAX) so that I can insert them in my database.
My JS file looks like this:
$(function() {
var postData = {
"userid" : $("input.userid").val(),
"vacancyid" : $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
cache: false,
type: 'POST',
url: "<?php echo base_url();?>dashboard/vacancy/saveVacancy",
contentType: 'application/json',
dataType: 'text'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function(data) {
alert(data); // plausible [Object object]
//alert(data[0]); // plausible data
console.log(data); // debug as an object
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
And my controller looks like this (it is not doing much because it doesn't return anything):
public function saveVacancy() {
//$this->load->model('user/usersavedvacancies_model');
/*$data = array(
'userid' => $this->input->post('userid'),
'vacancyid'=>$this->input->post('vacancyid')
);*/
echo $this->input->post('userid');
}
Minor changes to javascript
$(function () {
var postData = {
"userid": $("input.userid").val(),
"vacancyid": $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
type: 'POST',
url: "<?php echo base_url('dashboard/vacancy/saveVacancy);?>",
dataType: 'json'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function (data) {
console.log(data); // debug as an object
if (data.result === 'success') {
alert("Yeah, it saved userid " + data.userid + " to vacancy id " + data.vacancyid);
}
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
});
In the controller
public function saveVacancy()
{
//assigning a more useable object name to the model during load
$this->load->model('user/usersavedvacancies_model', 'save_vacancy');
$data = array(
'userid' => $this->input->post('userid'),
'vacancyid' => $this->input->post('vacancyid')
);
//send data to model and model returns true or false for success or failure
$saved = $this->save_vacancy->doSaveId($data); //yes, I made up the method, change it
$result = $saved ? "success" : "failed";
echo json_encode(array('result' => $result, 'userid' => $data['userid'], 'vacancyid' => $data['vacancyid']));
}
You need to understand that $.ajax takes two methods i.e GET and POST and from the documentation you can see that default method is GET so Since you have not defined method as GET/POST probably the method is taken GET so first change define ajax method to POST as well as you need to be clear about dataType of ajax it may be one of JSON/html and default is json.
$.ajax({
method: "POST",
url: url,
data: data,
dataType:'html'
});
I guess this helped you can learn detail from
Learn more.
I am building a chat app and I want to ask users to input their username. JQuery front-end code slides a form into view (on ready), stores the data into variables and then loads the chat (when enter key or button is pressed). How do I stop that animation until I validate user input on server-side? I am using node.js for backend. Any ideas?
Thanks in advance!
Front-end jQuery:
var nameChoice, roomChoice; //to store user input
var initName = function() {
nameChoice = $("#init-name input").val(); //save chosen name in nameChoice
$("#current-name").text("Username: " + nameChoice); //put chosen name in chat header
$("#init-name").animate(
{"left" : "-35%"}, 300,
function() {
$(this).addClass("hidden");
$("#init-room").removeClass("hidden");
$("#init-room").animate({"left" : "35%"}, 300);
}); //remove name form and slide in room form in callback
} //end initName
var initRoom = function() {
roomChoice = $("#init-room select").val(); //save chosen room in roomChoice
$("#current-room").text("Room: " + roomChoice); //put chosen room in chat header
$("#init-room").animate(
{"left" : "-35%"}, 300,
function() {
$(this).addClass("hidden");
$("#chat-main").removeClass("hidden");
}); //remove room form and show page in callback
} //end initRoom
var btnHover = function() {
$(".btn-form").hover(
function() {
$(this).stop().animate(
{
backgroundColor : "#FFBD7A"
}, 300);
},
function() {
$(this).stop().animate(
{
backgroundColor : "white"
}, 300);
});
}
var init = function() {
$("#init-name").removeClass("hidden").animate({"left" : "35%"}, 300); //slide in name form
$(document).keydown(function(event) { //submit choice on enter key
if (event.which === 13) {
if (!$("#init-name").hasClass("hidden")) { //if user is choosing name
event.preventDefault();
initName(); //call initName function
}
if (!$("#init-room").hasClass("hidden")) { //if user is choosing room
event.preventDefault();
initRoom(); //call initRoom function
}
}
}); //end enter key submission
$("#init-name .btn-form").click(initName);
$("#init-room .btn-form").click(initRoom);
btnHover();
} //end init
$(document).ready(init);
I'm still learning node, so no back-end code yet...
rough code for this ...
$http.post("/login", {"username":username, "password": password}).then(function(response) {
console.log("success - do animation here");
}.catch(function(response) {
console.log("failure a non 2xx HTTP response - handle error here");
});
This code is crude since the http request should prob be in a service, also I have not linted this code, BUT you should get the general IDEA!
APOLOGIES THIS IS ANGULAR, JQUERY WAS ASKED FOR ... HERE GOES ...
$.ajax({
method: "POST",
url: "/login",
data: { username: username, password: password }
})
.then(
function( data, textStatus, jqXHR ) {
console.log("success - do animation here");
},
function( jqXHR, textStatus, errorThrown ) {
console.log("failure a non 2xx HTTP response - handle error here");
}
);
Never tried this in Jquery before but the docs suggest this approach.
Check the docs at ...
http://api.jquery.com/jquery.ajax/
Thanks
Edit: in case promise based jQuery code not available:
$.ajax({
method: "POST",
url: "/login",
data: { username: username, password: password }
})
// for older versions of jQuery, replace .done and .fail with .success and .error
.done(function( data, textStatus, jqXHR ) {
console.log("success - do animation here");
})
.fail(function( jqXHR, textStatus, errorThrown ) {
console.log("failure a non 2xx HTTP response - handle error here");
});
im trying to send values in a form via POST in ajax, how do i capture them in send them, this is wat i have now while in GET
function test(ans_field_uuid){
var result = "";
var url="ajax_pages/remove_answer_field_ajax.php"
url += '?uuid=' + ans_field_uuid;
$.get(
url,
function (data) {
result = data;
}
)
.success(function () {
if (result != "") {
addTableRow('tb_add_field', result);
$('#ajaaxDiv').html(result);
}
})
.complete(function () {
$('#img_create_subcat').hide();
$('#dialog').dialog('close');
})
.error(function () {
alert('An error has occurred.');
});
return false;
}
since you already use jQuery
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
data: name and location are your POST variable.
You can fetch the POST variable in this example in some.php with
$_POST["name"]
which equals "John"
If you want to receive something then like "Hello".
Inside your some.php
echo "Hello";
and it will be send to your ajax function as response in your done function as variable msg
Documentation for jQuery post
// ...
var url = "ajax_pages/remove_answer_field_ajax.php";
$.post( url, "uuid=" + ans_field_uuid, function (data) {
result = data;
}
// ...