Knockout Json Mapping Issue - javascript

Hi I have a View Which Contains a ADDBasicDetailsForm (This JSP view is rendered using spring MVC)
BasicDetailView.jsp
<div data-bind="if: profileDto.basicDetailsDTO">
<div class="basicDetails">
Contact No :
<b data-bind="value: profileDto.basicDetailsDTO.contactNo"> </b>
contactMailId :
<b data-bind="value: profileDto.basicDetailsDTO.contactMailId"> </b>
</div>
</div>
<form id="BasicDetailsform" method="POST">
<fieldset class="contactMailId">
<input id="contactMailId"
type="text" placeholder="Mail Id" maxlength="32"
name="contactMailId"></input>
</fieldset>
<fieldset class="contactNo name">
<input id="contactNo"
type="text" placeholder="contactNo" maxlength="32" name="contactNo"></input>
</fieldset>
<fieldset class="buttons">
<button class="saveactionbutton" type="submit">SAVE</button>
</fieldset>
</form>
</div>
Inially contact no and conatct mail ID is not shown in UI. It should be shown when i submit the form and i am using knockout for automatic UI referesh.But It is not working
BasicDetails.js
function BasicViewModel() {
var self = this;
}
var viewModel = new BasicViewModel();
$(document).ready(function(){
$("#BasicDetailsform").submit(function(e)
{
var form = $(this);
e.preventDefault(); //STOP default action
var input = '{';
input += '"contactMailId":"'+$('#contactMailId').val()+'",';
input += '"contactNo":"'+$('#contactNo').val()+'"';
input += '}';
alert(input);
$.ajax({
type: "POST",
dataType: "json",
url : "addBasicDetails",
contentType: "application/json; charset=utf-8",
data: input,
dataFilter: function (response) {
return response;
},
async:false,
success: (function(data, textStatus, jqXHR) {
alert("ajax Success");
form.hide();
data = ko.toJSON(data);
alert("JSON Data in Alert"+data );
ko.mapping.fromJSON(data, {}, self);
ko.applyBindings(viewModel);
}),
error : function(data,textStatus,error){
alert("ajax failure");
}
});
});
});
My JSON response from server
{
"basicDetailDTO":{
"contactNo":"86878",
"contactMailId":
"rahuljain#gmail.com"
}
}
After the Form submission details are not getting reflected in my jsp view .
Please let me know where is the issue in my code.

Related

laravel ajax unexpected end of json input

Hello guys i am desperate i am not getting completly this syntax / concept of Ajax.
I have 2 forms on my page. Based on the value of the hidden field a certain logic in my controller will be executed. Its simple actually -- i thought. I am trying to pass an array from my ajax to my controller and then passing it back to my view. I know it doesnt make much sense. But i am trying to understand how that works. The first logic gets executed but the other one gets me this error:
jqXHR is : [object Object] textStatus is : parsererror errorThrown is : SyntaxError: Unexpected end of JSON input
Why is that ? Can you guys please give me an advice.
Update
I tried not to put the whole code and just reduce it to the main question. But since it caused confusion of the rootcause i will show the whole code of the parts which might be relevant. I edited the question to the below.
BLADE
<center>
<div class="col-md-12">
<h3>xlsx, xls, ods, csv to Text</h3>
<form id="xlsForm" enctype="multipart/form-data">
#csrf
<input type="file" name="excelfile" />
<input name ="loadSubmit" id="loadSubmit" type="submit"/>
<input type ="hidden" name="load" value="0">
</form>
</div>
</center>
<div class ="row">
<div class ="col-md-3">
<div class="container mt-5">
<h2 id="words" class="mb-4">Skills found</h2>
</div>
<form id="xlsFormUpdate" enctype="multipart/form-data">
<input type ="hidden" name="load" value="1">
<div id="inner">
</div>
<input name ="updateSubmit" id="updateSubmit" type="submit"/>
</form>
</div>
<div class ="col-md-9">
#include('layouts.partials.datatable')
</div>
</div>
Controller:
if ($request->input('load') == '0') {
//some code -- this works fine
return response()->json($data); //This data can be send - no problem
} elseif (($request->input('load') == '1')) {
$data = $request->post('checkbox_array');
return response->json($data); // i tried json_encode too .. not working.
}
Jquery code
$(document).ready(function(){
$('#xlsForm').submit(function uploadFile(event){
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success:function (response) {
$("#inner").empty();
$.each(response,function(index,value){
$("#inner").append
('<div class="row">' +
'<div class="col-xs-2">'+
'<input type="checkbox" class="'+value+'" value="'+value+'" name="checkbox[]" checked > <label style="font-weight: bold" for="skillChoice_'+index+'">'+value+' </label>' +
'</div>'+
'<div class="col-xs-1">'+
'<input class="'+value+'" type="number" name="weight[]" min="1" max="3" value="1"> '+
'</div>'+
'</div>');
});
}
});
});
$('#xlsFormUpdate').submit(function uploadFile(event) {
event.preventDefault();
var checkbox_array = [];
$('input[type=checkbox]').each(function (index,value) {
if (this.checked)
{
checkbox_array.push(1);
}
else {
checkbox_array.push(0);
}
});
let checkbox_s = JSON.stringify(checkbox_array)
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('ExcelToArray')}}",
method: "POST",
data: {checkbox_array:checkbox_s},
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function (response) {
alert('The Response is ' + response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('jqXHR is : ' + jqXHR
+ 'textStatus is : ' + textStatus
+ ' errorThrown is : ' + errorThrown);
},
})
});
});
When using ajax submit event to send data to controller, the data in the field data: {checkbox_array:checkbox_s}, will be send to the controller. Since the input field load was never sent, the elseif (($request->input('load') == '1')) clause was never true and the controller was never going into that section and was never returning the right response. The data had to be changed like this var my_datas JSON.stringify({mydata:checkbox_array, load: "1"}); and then in ajax the data could be send like data:my_datas. In controller the field load can then be processed.

Ajax in django form

My Ajax request works correctly when I use change and the input is checkbox, but my Ajax request does not work when use input type submit !!
I want my type in the input submit and when I do this the Ajax request will not work and the page will reload.
$(document).on('change','.filter-form',function(event){
event.preventDefault();
$.ajax({
type:'GET',
url:'filter/',
data : $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
alert("error" + data);
}
});
});
my form :
<form action="" class="filter-form">
<input type="submit" name="price" value="new">
<input type="submit" name="discount" value="discount">
<input type="submit" name="old" value="old">
</form>
I don't think submit buttons trigger the change event, so you'll have to listen for something else, also .serialize() do not give you the name/value pair of submit buttons.
Use the click event on the buttons and use the element properties to get the data to post.
$(document).on('click','.filter-form input[type=submit]',function(event){
event.preventDefault();
$.ajax({
type:'GET',
url:'filter/',
data : {[this.name]: this.value}
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
alert("error" + data);
}
});
});
First added a clicked property to the identify which submit is clicked. Then used the clicked property to get the value & name of the submit to pass in form submit event handler.
$(document).ready(function(){
// To identify which submit is clicked.
$("form.filter-form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
// Form submit event handler
$("form.filter-form").submit(function(event) {
event.preventDefault();
$clickedInput = $("input[type=submit][clicked=true]");
dataString = {[$clickedInput.prop('name')]: $clickedInput.val()};
console.log('dataString', dataString);
$.ajax({
type:'GET',
url:'filter/',
data : dataString,
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
console.log("error" + data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="filter-form">
<input type="submit" name="price" value="new">
<input type="submit" name="discount" value="discount">
<input type="submit" name="old" value="old">
</form>

html form not transferring data to google spreadsheets

Hi I have been following this tutorial submit data from html forms to google sheets
The ajax code is as follows:
var $form = $('form#test-form'),
url =
'https://script.google.com/macros/s/AKfycbwoNkRscUxkp7bOdHx3pPwj4D2doLATbgqEYKOoaIRFXCdRPlM/exec'
$('#submit-form').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeObject()
}).success(
// do something
);
})
The problem I am getting is that the data is not transferring over to the google spreadsheet. Below is the html code.
<form id="test-form">
<div>
<label>Field 1</label>
<input type="text" name="Groceries" placeholder="Field 1"/>
</div>
<div>
<label>Field 2</label>
<input type="text" name="Diary" placeholder="Field 2"/>
</div>
<div>
<label>Field 3</label>
<input type="text" name="Meat" placeholder="Field 3"/>
</div>
<div>
<label>Field 4</label>
<input type="text" name="Fish" placeholder="Field 4"/>
</div>
<div>
<button type="submit"id="submit-form">Submit</button>
</div>
Are you getting a CORS error in the console?
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If so, I got it to work by changing the data type from 'json' to 'jsonp'. Also, the success part of the AJAX request should be inside the object.
$('#submit-form').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "jsonp",
data: $form.serializeObject(),
success: function() {
console.log('it worked')
}
})
})
unfortunately that did not work when I click the submit button the error Did not load script at 'https://script.google.com/macros/s/AKfycbwoNkRscUxkp7bOdHx3‌​pPwj4D2doLATbgqEYKOo‌​aIRFXCdRPlM/exec?cal‌​lback=jQuery31106050‌​297388535439_1513880‌​634404&Groceries=100‌​&Diary=100&Meat=100&‌​Fish=100&_=151388063‌​4405' because non script MIME types are not allowed when 'X-Content-Type: nosniff' is given
The above issue can be solved by adding the below code in you doget function -
function doGet(e) {
// do whatever this webapp is for
var result = doSomething(e);
// prepare the result
var s = JSON.stringify(result);
// publish result
return ContentService
.createTextOutput(result.params.callback ? result.params.callback + "(" + s + ")" : s )
.setMimeType(result.params.callback ? ContentService.MimeType.JAVASCRIPT : ContentService.MimeType.JSON);
}

Click function won't update information on page

I want my submit button to pull the value from the input box next to it, change the '#' to a '-' and then pass it on so that I can pull information respective to that user and then populate the field in HTML. But the page just refreshes and a '?' gets added to the url.
$("#usernameBtn").click(function() {
var unTouchedID = $("#userid").val();
var usrID = unTouchedID.replace("#", "-");
$.ajax({
url: "https://owapi.net/api/v3/u/" + usrID + "/stats",
dataType: 'json',
data: "",
success: function (data) {
$('#heroStats_elims').html('<h2>'+ data.us.stats.competitive.average_stats.eliminations_avg + '</h2>');
//var avgElims = //data.us.stats.competitive.average_stats.eliminations_avg
}
}); });
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Battle.net Tag" id="userid">
</div>
<button type="submit" class="btn btn-default" id="usernameBtn">Submit</button>
You need to use event.preventDefault(); as #Andrew mentioned to prevent the default behavior of submitting the page.
$("#usernameBtn").click(function(e) {
e.preventDefault();
var unTouchedID = $("#userid").val();
var usrID = unTouchedID.replace("#", "-");
$.ajax({
url: "https://owapi.net/api/v3/u/" + usrID + "/stats",
dataType: 'json',
data: "",
success: function (data) {
$('#heroStats_elims').html('<h2>'+ data.us.stats.competitive.average_stats.eliminations_avg + '</h2>');
//var avgElims = //data.us.stats.competitive.average_stats.eliminations_avg
}
});
});
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Battle.net Tag" id="userid">
</div>
<button type="submit" class="btn btn-default" id="usernameBtn">Submit</button>

How to Autofill and login into a website from external login page?

Different customers use different websites to log-in to their account. i want to provide them a single form to put their credentials onto it, and select the domain/platform t they want themselves log in to and those credentials are passed to the desired website's login form log them into it. So, help me to send the credentials to the website. You can see the login form # www.ubfmgps.com/login.html
Here is my html form to get the credentials
<form action="#" id="gaq-form" class="form-b" method="post">
<fieldset>
<p>
<span>
<label for="fba">Username</label>
<input type="text" id="txtUserName" name="txtUserName" autocomplete="on" required>
</span>
<span>
<label for="fbb">Password</label>
<input type="Password" id="txtUserPassword" name="txtUserPassword" required>
</span>
</p>
<p>
<solid>Choose Platform</solid>
<select name="platform" id="platform" width=100px>
<p> <option value="Jimishare" id="Jimishare">Jimishare</option>
<option value="Tracksolid" id="Tracksolid">Tracksolid</option>
<option value="Gpsyeah" id="Gpsyeah">Gpsyeah</option>
</select>
</p>
</p>
<p><button type="submit" onclick="login();">Log Me In</button></p>
</fieldset>
</form>
<script type="text/javascript">
function login()
{
if(document.getElementById("platform").value=='Jimishare')
{
var txtUserName = document.getElementById("username").value;
var txtUserPassword = document.getElementById("password").value;
$.ajax({
url : "http://www.jimishare.com",
type : 'post',
data : 'txtUserName=' + encodeURIComponent(username) + 'txtUserPassword=' + encodeURIComponent(password),
dataType : 'json',
error : function(data) { console.log("error"); console.error(data); },
success : function(data) { console.log("success"); console.info(data); }
});
}
else if (document.getElementById("platform").value=='Tracksolid') {
document.write("Tracksolid");
var account = document.getElementById("username").value;
var password = document.getElementById("password").value;
$.ajax({
url : "http://www.tracksolid.com/mainFrame",
type : 'post',
data : 'account=' + encodeURIComponent(account) + 'password=' + encodeURIComponent(password),
dataType : 'json',
error : function(data) { console.log("error"); console.error(data); },
success : function(data) { console.log("success"); console.info(data); }
});
}
else {
document.write("Gpsyeah");
}
}
</script>
As everyone said, you are looking for a SSO system. Anyway, if you want to make a quick login system, you have to add some javascript to perform this operation.
You need to define a mapping which describe the username and password fields name for each sites. Assuming you have jQuery, you can try like this :
$(document).ready(function() {
form = $("#gaq-form");
websitePickerField = $("select[name='platform']");
usernameField = $("#username");
passwordfield = $("#password");
submitBtn = $('#submit');
form.submit(function() {
updateFormAttrs($(this).val());
});
});
function updateFormAttrs(currentWebsite) {
var options = mapping[currentWebsite];
form.attr('action', options.url);
usernameField.attr('name', options.usernameName);
passwordfield.attr('name', options.passwordName);
submitBtn.attr('name', options.submitName);
}
See this jsfiddle

Categories