html form not transferring data to google spreadsheets - javascript

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);
}

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.

formdata with jquery not working,server returns empty string

I have gone through most of the responses from previous similar questions and tried, yet same result. There is no server error, data fields received by server are null.I am using form data.
$("#sbtn").onclick( function(){
var url = "php/add.php";
var fd = new FormData();
fd.append('file',files[0]);
fd.append('type',"music");
fd.append('username', $("input[name=username]").val());
$.ajax({
type :"POST",
url : url,
data : fd,
contentType: false,
processData: false,
success : function(resp){ alert("server response : " + resp );}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form onsubmit="return false;">
<label for="username">Name</label>
<input type="text" size="10" name="username">
<input type="file" required />
<input type="submit" value="add" id="sbtn"/>
</form>

How to properly get form data with JQuery and formData

I am trying to upload some form data using ajax and php but for some reason my data is not being catch or passed.
Here is what I have:
form.html ( basic form with 3 text inputs and 1 file)
<form class="form" id="superform" action="nada.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="tituloQuiz">Resultado:</label>
<input type="text" class="form-control resultado" id="titulo" name="titulo" placeholder="Ex: Paris">
</div>
<div class="form-group">
<label for="desc">Descrição do Site:</label>
<textarea class="form-control" id="desc" name="descricao" placeholder="Ex:"></textarea>
</div>
<div class="form-group">
<label for="desc">OG FB DESC:</label>
<textarea class="form-control" id="facedes" name="descricao" placeholder="facebook description"></textarea>
</div>
<div class="form-group">
<label for="imggrande">Imagem</label>
<input type="file" id="imggrande" name="imgres">
<p class="help-block">Imagem usada na página de resultado e Facebook 600 x 400.</p>
</div>
<button type="button" class="btn btn-primary btn-lg addres">Adicionar Resultado</button>
<button type="button" class="btn btn-danger btn-lg">Próxima Etapa</button>
</form>
And here is the JS that makes the ajax call:
myjs.js
$("document").ready(function(){
$('.row').on('click','.addres',function(){
console.log('Click Detectado');
var formulario = $('#superform');
var formData = new FormData(formulario);
$.ajax({
type: "POST",
url: "addres.php",
data: formData,
async: false,
success: function(data) {
console.log('Funcionou');
},
error: function(data) {
console.log('Erro no formulario');
},
cache: false,
contetType: false,
processData: false
});
});
});
Nothing is being passed and the POST call is empty (See screenshots below).
**addres.php**
<?php
var_dump($_FILES);
var_dump($_POST);
?>
$.ajax({
url: 'address.php',
type: 'POST',
data: new FormData($('#superform')[0]), // The form with the file inputs.
processData: false, // Using FormData, no need to process data.
contentType:false
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multi-part/form one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
read from php using
$_FILES['file-0']
(There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)
Additional info:
See for yourself the difference of how your formData is passed to your php page by using console.log().
var formData = new FormData($('#superform')[0]);
console.log(formData);
var formDataSerialized = $('#superform').serialize();
console.log(formDataSerialized);
Hope this helps.
extra information read this upload files asynchronously
Note : formData doesn't work in IE 9
You can use .serializeArray() to get the data in array format and then convert it into an object. like this:
function getFormData(formId) {
let formData = {};
let inputs = $('#'+formId).serializeArray();
$.each(inputs, function (i, input) {
formData[input.name] = input.value;
});
return formData;
}

Knockout Json Mapping Issue

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.

this works in developer mode with breakpoint ....but doesnt work without it

I have a textbox which is passed to the api....the text entered is stored...
<input type="text" id="name" placeholder="Type something">
The below code works in developer mode of chrome with breakpoints but doesnt work without it...
$("#submit").click(function() {
var name = $('#name').val() ;
var url = "https://www.mariyano.com/app-server/test/?action=add_list&name="+name;
$.ajax({
url: url,
dataType: "jsonp",
});
Actually no idea what's wrong but here is a working source code: http://jsfiddle.net/HLmsr/
JavaScript
$("#submit").click(function() {
var name = $('#name').val() ;
var url = "https://www.mariyano.com/app-server/test/?action=add_list&name="+name;
$.ajax({
url: url,
dataType: "jsonp",
error: function (e) {
console.log(e);
},
success: function (data) {
console.log(data);
}
});
});
​
HTML
<input type="text" value="" id="name" />
<input type="button" id="submit" value="Submit" />​
Try to modify your code like this:
$("#submit").click(function(evt) {
evt.preventDefault();
var name = $('#name').val() ;
...
If you don't call preventDefault and "submit" is a submit-input type, it could happen that the code is not executed because instead the browser navigates to another page.
See jquery reference for more details: jquery

Categories