I am finding it difficult to send data to the controller through Ajax post since the object to be sent to the controller cannot be used within the ajax post because of the structure of my code.I am using knockout for data-binding the click event of the Update button.
This is my code
$(document).ready(function () {
var provider = function () {
var self = this;
self.providerID = ko.observable(providerEditInfo.ProviderID);
self.firstName = ko.observable(providerEditInfo.FirstName);
self.lastName = ko.observable(providerEditInfo.LastName);
self.contactEmail = ko.observable(providerEditInfo.ContactEmail);
self.NPI = ko.observable(providerEditInfo.NPI);
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: { providerForUpdate }, -- Cant send this
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
self.cancelEdits = function () {
if (confirm("Are you sure you want to Cancel?")) {
window.location.href = "/Provider/ShowTheListOfProviders";
}
};
}; //End of Constructor.
var providerForUpdate = new provider();
ko.applyBindings(providerForUpdate);
});
On the clck of Update Button,I am calling the 'updateProviderDetails' method.
HTML
#model Greenway.Demo.DataAccess.Entity.Provider
<body>
<div class="container">
<h1 class="col-sm-offset-2">Edit Provider Details:</h1>
<br />
<form class="form-horizontal" role="form" id="editProviderDetailsForm">
<div class="form-group">
<label class="col-sm-2 control-label labelfont">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" autofocus="autofocus" placeholder="Enter the First Name" id="firstName" name="firstName" data-bind="value:firstName , event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Last Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Enter the Last Name" id="lastName" name="lastName" data-bind="value:lastName ,event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group text-center">
<button type="Submit" data-bind="click: updateProviderDetails" class="btn btn-primary">Update</button>
<button type="button" data-bind="click: cancelEdits" class="btn btn-primary">Cancel</button>
</div>
</form>
</div>
</body>
<script type="text/javascript">
var providerEditInfo = #Html.Raw(Json.Encode(Model));
</script>
<script type="text/javascript" src="../../App_Scripts/Shared/Functions.js"></script>
Could someone guide me on how I can send the data to the controller with this code structure.I can't put updateProviderDetails outside the constructor because otherwise, I can't bind it.
Use ko.toJSON to serialize your view model to json:
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
This is also in the Knockout Tutorial
Related
My server generates a csrfToken, which is inserted into the following element:
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
The {{_csrfToken}}, is used for templating, but at run time is replaced at the server with the actual token.
<div class="formContainer">
<form class="form-horizontal signupform" role="form" action="/process?form=signupform" method="POST">
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
<div class="form-group">
<label for="fieldName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control"
id="fieldName" name="name">
</div>
</div>
<div class="form-group">
<label for="fieldEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" required id="fieldName" name="email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-default">Register</button>
</div>
</div>
</form>
</div>
{{#section 'jquery'}}
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
{{/section}}
How do I update my jQuery call to include the token ? Right now it is generating errors because the token is not included...
Try this, you did not post anything in fact. I did not test it, if it fails, maybe you should collect data manually.
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
+ var payload = $(this).serializeArray()
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
+ data: payload,
success: function(data){
if(data.success){ $container.html('<h2>Thank you</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
though it looks like it's a duplicate post still as far as answer is concerned this is how you should do check this SO post
and I am writing the code for you here
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer');
var token = $('input[name="_csrf"]').attr('value')
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', token);
}
});
$.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
I'm using a Google Form's value to integrate with my website where I want to submit the form and store data in google sheet as form responses. I'm using AJAX to redirect to another page instead of google form submit page. But whenever I'm trying to submit it's redirecting to my page accurately but datas are not saved in google sheet. Here are my codes,
<strong>Full Name</strong>
<input type="text" name="Fullname" class="form-control" id="Fullname" />
<strong>Email Address</strong>
<input type="text" name="Email" class="form-control" id="Email" />
<strong>Subject</strong>
<input type="text" name="Subject" class="form-control" id="Subject" />
<strong>Details</strong>
<textarea name="Details" rows="8" cols="0" class="form-control" id="Details"></textarea><br />
<button type="button" id="btnSubmit" class="btn btn-info" onclick="postContactToGoogle()">Submit</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry_805356472": fullname,
"entry_1998295708": email, "entry_785075795":
subject, "entry_934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>
How can I save the data in google sheet? Am I missing something in my code? Need this help badly? Thanks.
You can directly copy the form from google view form page like shown in the demo, and then do the following changes in the AJAX call as shown below.
And now once you submit data it is visible in google forms, view responses.
$(function(){
$('input:submit').on('click', function(e){
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/d/18icZ41Cx3-n1iW7yTOZdiDx9a6mySWHOy9ryd1l59tM/formResponse",
data:$('form').serialize(),
type: "POST",
dataType: "xml",
crossDomain: true,
success: function(data){
//window.location.replace("youraddress");
//console.log(data);
},
error: function(data){
//console.log(data);
}
});
});
});
<div class="ss-form"><form action="https://docs.google.com/forms/d/18icZ41Cx3-n1iW7yTOZdiDx9a6mySWHOy9ryd1l59tM/formResponse" method="POST" id="ss-form" target="_self" onsubmit=""><ol role="list" class="ss-question-list" style="padding-left: 0">
<div class="ss-form-question errorbox-good" role="listitem">
<div dir="auto" class="ss-item ss-text"><div class="ss-form-entry">
<label class="ss-q-item-label" for="entry_1635584241"><div class="ss-q-title">What's your name
</div>
<div class="ss-q-help ss-secondary-text" dir="auto"></div></label>
<input type="text" name="entry.1635584241" value="" class="ss-q-short" id="entry_1635584241" dir="auto" aria-label="What's your name " title="">
<div class="error-message" id="1979924055_errorMessage"></div>
<div class="required-message">This is a required question</div>
</div></div></div>
<input type="hidden" name="draftResponse" value="[,,"182895015706156721"]
">
<input type="hidden" name="pageHistory" value="0">
<input type="hidden" name="fvv" value="0">
<input type="hidden" name="fbzx" value="182895015706156721">
<div class="ss-item ss-navigate"><table id="navigation-table"><tbody><tr><td class="ss-form-entry goog-inline-block" id="navigation-buttons" dir="ltr">
<input type="submit" name="submit" value="Submit" id="ss-submit" class="jfk-button jfk-button-action ">
</td>
</tr></tbody></table></div></ol></form></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
If you go to your form on Google and click on 'View Live Form', and then view source on the form, you'll see that the fields you want to upload have aname in the form entry.12345678; the id is in the form entry_12345678. You need to use the name value. Try this:
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry.805356472": fullname,
"entry.1998295708": email,
"entry.785075795": subject,
"entry.934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>
I have a modal in which there's a form that I want users to be able to submit an email with. I set up the ajax post like I usually would, however, the post keeps failing. When it does, I get the following two errors in the console.
Setting XMLHttpRequest.withCredentials for synchronous requests is deprecated
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
Interestingly, the email sometimes sends regardless of the errors, but sometimes it doesn't either.
Here is my Html:
<form class="cmxform" id="contactForm" >
<div class="row">
<div class="col-xs-6">
<label class="col-md-12 control-label" style="text-align: left;" >Name</label>
<div class="col-md-12">
<input required class="form-control" id="FromName" name="FromName" style="margin-bottom: 10px;" type="text" value=""/>
</div>
</div>
<div class="col-xs-6">
<label class="col-md-12 control-label" style="text-align: left;" >Email</label>
<div class="col-md-12">
<input required class="form-control" style="margin-bottom: 10px;" id="FromEmail" name="FromEmail" type="text" value=""/>
</div>
</div>
</div>
<label class="col-md-12 control-label" >Message</label>
<div class="col-md-12">
<textarea required class="form-control contact-message" cols="20" id="Message" name="Message" rows="2"></textarea>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-info" value="Submit" />
</div>
</form>
And my JS:
function sendMessage(messageData) {
$.ajax({
async: true,
url: '/api/SendMessageApi',
type: 'POST',
data: messageData,
success: function () {
},
error: function (ex) {
alert('there was an error');
}
});
}
$("#contactForm").submit(function () {
var name = $('#FromName').val();
var email = $('#FromEmail').val();
var message = $('#Message').val();
var messageData = { Name: name, Email: email, Message: message };
sendMessage(messageData);
});
Any help would be much appreciated!
To submit the form after ajax success, you can use:
function sendMessage(messageData) {
$.ajax({
context: this, // set context to the form
async: true,
url: '/api/SendMessageApi',
type: 'POST',
data: messageData,
success: function () {
this.submit(); // submit form on success
},
error: function (ex) {
alert('there was an error');
}
});
}
$("#contactForm").submit(function (e) {
e.preventDefault();
var name = $('#FromName').val();
var email = $('#FromEmail').val();
var message = $('#Message').val();
var messageData = { Name: name, Email: email, Message: message };
sendMessage.call(this, messageData); // set context to the form
});
My code is working in chrome,safari but its not working in firefox.
Here is my code
<script>
$(document).ready(function () {
$("#loginform").on('submit',(function(e) {
e.preventDefault();
$('#loading').html("Loading....");
$.ajax({
url: "login.php",
type: "POST",
data: new FormData(this),
contentType:false,
cache: false,
processData:false,
async:false,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
return false;
}));
});
</script>
Can anyone solve this issue??? I have one more same script in the same page only url is different but its working fine,but this script is not working .Iam getting empty data .But in chrome,safari its working fine.
My Html Code :
<form role="form" method="post" id="loginform" action="">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Username" required>
</div>
<div class="form-group">
<label for="password"> Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<div class="checkbox">
<label><input type="checkbox" value="" name="user_rememberme" checked>Remember me</label>
</div>
<div id="loading"></div>
<div id="message"></div>
<button type="submit" name="login" class="btn btn-success pull-right">Login</button>
</form>
Never use async:false in ajax call unless you knows specifically wat you are doing.The problem is that async:false freezes the browser until ajax call is complete (either error or success).set it to true or remove it (by default it is true).Implement error block too and check if its an error from server side
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
},error:function(data){
console.log(data)
}
Try this:
<script>
$(document).ready(function () {
$("#loginform").on('submit',(function(e) {
dta = $(this).serialize();
e.preventDefault();
$('#loading').html("Loading....");
$.ajax({
url: "login.php",
type: "POST",
data:dta,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
return false;
}));
});
</script>
I'm using knockout to get some data from an API to fill my textboxes. I want to get the unit price from the API when you select a drug. How can I do this?
<div class="control-group">
<label class="control-label">Drug:</label>
<div class="form-horizontal">
<select id="Drug_ddl" data-bind="options: drugs, optionsText: function (item) { return item.Description; }, value: selectedDrug" class="input-xlarge"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">Unit Price:</label>
<div class="form-horizontal">
<input type="number" data-bind="value: unitPrice" step="0.01" class="input-xlarge" id="UnitPrice_txt" />
</div>
</div>
<div class="control-group">
<label class="control-label">Quantity:</label>
<div class="form-horizontal">
<input type="number" data-bind="value: quantity" step="1" class="input-xlarge" id="Qty_txt" />
</div>
</div>
<div class="control-group">
<label class="control-label">Cost:</label>
<div class="form-horizontal">
<input type="text" data-bind="value: drugcost" readonly="readonly" step="0.01" class="input-xlarge" id="Cost_txt" />
<input type="button" id="AddDrugs_btn" data-bind="click: addDrug" class="btn btn-primary" value="Add" />
</div>
</div>
This is the code for the viewModel:
var claimEntryViewModel = function () {
var drugs = ko.observableArray([]);
var unitPrice = ko.observable('0.00');
var quantity = ko.observable('1');
var drugcost = ko.computed(function () {
return quantity() * unitPrice();
});
var loadDrugs = function () {
url = apiServerUrl + "Items/";
$.ajax({
url: url,
headers: { 'Access-Control-Allow-Origin': '*' },
contentType: 'application/json',
dataType: 'json',
type: 'GET',
crossDomain: true,
success: function (data) {
drugs(data);
},
error: function (data) {
console.log("Is not answered");
console.log(data);
}
});
}
var selectedDrug = ko.observable();
var addDrug = function () {
var match = ko.utils.arrayFirst(claimDrugs(), function (item) {
return selectedDrug().ID === item.Id;
});
if (!match) {
claimDrugs.push({
Id: selectedDrug().ID,
Description: selectedDrug().Description,
unitPrice: selectedDrug().SalesPrice,
quantity: quantity(),
drugcost: drugcost(),
});
} else {
errorMessage("Already exists!");
}
}
return {
drugs: drugs,
addDrug: addDrug,
selectedDrug: selectedDrug,
unitPrice: unitPrice,
quantity: quantity,
drugcost: drugcost,
}
}
someone kindly provide me with a code that can do this, i'm fairly new to knockout and don't really know how to go about this. thanks
super cool is right, subscribing is a good way to handle this.
selectedDrug.subscribe(function (newValue) {
neededInfo(getSelectedDrugInfoFromApi(newValue));
});
This will call the getSelectedDrugInfoFromApi() every time the selectedDrug observable value changes, and update the neededInfo observable.
Keep in mind not to update the selectedDrug value inside the subscribe function though, as it will create a loop.