sending JSON to google app engine datastore - javascript

So I've been scouring the interwebs and I cant find anything that works for me. I have a simple html form that I need to send via JSON to the app engine datastore.
HTML form:
<form method="get" name="vehicle-form" id="vehicle-form">
<input type="text" name="type" placeholder="Vehicle Type" requried>
<input type="text" name="make" placeholder="Make" requried>
<input type="text" name="model" placeholder="Model" requried>
<input type="text" name="year" placeholder="Year" requried>
<button id="submit-btn">Add</button>
</form>
Javascript: EDIT: Changed this- now all the values are going in as null
var formData = {};
$("#part-form").serializeArray().map(function (x) { formData[x.name] = x.value; });
//var par = document.getElementById("test2");
//par.innerHTML += "<p>";
//for (var i in formData) {
// par.innerHTML += formData[i] + "<br>";
//}
//par.innerHTML += "</p>";
var uriString = myUrl;
$.ajax({
url: uriString,
type: "POST",
//data: JSON.stringify(formData)
data: { "type" : formData[0], "quantity" : formData[1], "cost" : formData[2], "vehicle_id" : formData[3] }
});
I am doing this on a windows 8 phone, and the success function doesn't execute, and no data is added to the datastore.
Here is the backend code for the POST request
class AddVehicle(webapp2.RequestHandler):
def post(self):
"""Creates a vehicle entity
POST Vehicle Variables:
vehicle_type = vehicle type - required
make = Make - requried
model = Model - required
year = Year - required
"""
new_vehicle = Vehicle()
vehicle_type = self.request.get('type', default_value=None)
make = self.request.get('make', default_value=None)
model = self.request.get('model', default_value=None)
year = self.request.get('year', default_value=None)
# all required info
new_vehicle.vehicle_type = vehicle_type
new_vehicle.make = make
new_vehicle.model = model
new_vehicle.year = year
self.response.write(new_vehicle)
# post data into datastore
key = new_vehicle.put()
out = new_vehicle.to_dict()
self.response.write(json.dumps(out))
return
This is the ndb model
class Vehicle(ndb.Model):
vehicle_type = ndb.StringProperty(required=True)
make = ndb.StringProperty(required=True)
model = ndb.StringProperty(required=True)
year = ndb.StringProperty(required=True)

Got it to work:
$.ajax({
url: uriString,
type: "POST",
contentType: "application/x-www-form-urlencoded", //<-- THIS
data: { type: vehicle_type, make: vehicle_make, model: vehicle_model, year: vehicle_year },
success: function (result) {
WinJS.Navigation.navigate("/pages/vehicleAdd/vehicleAdd.html");
}
});
Turns out I needed to send url encoded form data instead of json...

Related

ajax dont send the variables, send undefined

I have code in html inputs and checkbox the javascript code collects the data of the inputs and in ajax must send the information does not reach the php where it receives it and puts it in session.
ajax send the array for the php file, but the array is empty and i dont know what happen, im sorry my english is very ugly :(
function addcarto() {
var quantity1 = document.getElementById("quiantitynice1").value;
var quantity2 = document.getElementById("quiantitynice2").value;
var quantity3 = document.getElementById("quiantitynice3").value;
var quantity4 = document.getElementById("quiantitynice4").value;
var quantity5 = document.getElementById("quiantitynice5").value;
var quantity6 = document.getElementById("quiantitynice6").value;
var quantity7 = document.getElementById("quiantitynice7").value;
var quantity8 = document.getElementById("quiantitynice8").value;
var quantity9 = document.getElementById("quiantitynice9").value;
var quantity10 = document.getElementById("quiantitynice10").value;
var quantity11 = document.getElementById("quiantitynice11").value;
var quantity12 = document.getElementById("quiantitynice12").value;
var quantity13 = document.getElementById("quiantitynice13").value;
var quantity14 = document.getElementById("quiantitynice14").value;
var quantity15 = document.getElementById("quiantitynice15").value;
var quantity16 = document.getElementById("quiantitynice16").value;
var quantity17 = document.getElementById("quiantitynice17").value;
var quantity18 = document.getElementById("quiantitynice18").value;
var quantity19 = document.getElementById("quiantitynice19").value;
var quantity20 = document.getElementById("quiantitynice20").value;
var quantity21 = document.getElementById("quiantitynice21").value;
var quantities = [quantity1, quantity2, quantity3, quantity4, quantity5, quantity6, quantity7, quantity8, quantity9, quantity10, quantity11, quantity12, quantity13, quantity14, quantity15, quantity16, quantity17, quantity18, quantity19, quantity20, quantity21];
$.ajax({
type: 'post',
url: 'php/addCart2.php',
data: 'cantidades=' + quantities,
//data: { 'cantidades': JSON.stringify(quantities)},
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
}
<div class="form-check">
<input class="form-check-input" name="ingrediente" type="checkbox" id="ing19" value="19">
<label class="form-check-label" for="ing19">CAMARON</label>
</div>
<div class="quiantitynice" id="quiantitynice19" style='position:relative;display:none'>
<input class="formgroup" type="number" name="quantity" id="quiantitynice19" min="1" value="" Style="width:45Px" placeholder="1">
</div>
<div class="row text-center">
<div class="col">
<button class="btn btn-lg btn-wy" name ="btnsubmin" type = "submit" onclick="addcarto('');">AGREGAR</button>
</div>
</div>
this is the code of the php file:
<?php
session_start();
if(!empty($_POST)) {
//si llega id y cantidad
$canti = $_POST['cantidades'];
$_SESSION["canti"] = $canti;
}
?>
use these code in your ajax:
contentType: 'application/json; charset=utf-8',
dataType: "JSON",

Pushing array of values from a form into Google Spreadsheet comes through as 'undefined'

I have a form with text fields which the user can "Add New" by clicking a button. These fields share the same name. I'm trying pass the values into Google Spreadsheets, but the values all come through as 'undefined' with the following code, even though console.log prints the answers as strings which look okay to me.
So if the user for example submits 3 separate entries for SUNDAY_NOTES[], all 3 strings should end up in one cell broken up by new lines, but instead I'm just getting "undefined".
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // the user can create multiples of these ^ for each day of the week
<input type="submit" id="submit" />
</form>
<script>
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray().map((e) => {
return e.value
}).join('\n')
});
})
});
</script>
Your code works. In the snippet below I am storing the data split by \n in a variable and logging it. You can check the output.
Although your JS is correct, I suspect that you actually want to be using a different HTTP method. Perhaps POST or PUT? I can't be specific as you have not said which API endpoint you are using.
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var data = $form.serializeArray().map((e) => {
return e.value
}).join('\n');
console.log(data);
var jqxhr = $.ajax({
url: url,
method: "POST",
dataType: "json",
data: data
}).done(response => {
console.log(response);
}).fail((jqXHR, textStatus) => {
console.log("Request failed: " + textStatus);
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="submit" id="submit" />
</form>
remove the [] from your input's name as this is needed if you want to receive an array in the server side, then create a function that groups the values according to the inouts' keys :
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
and use it like :
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray()),
//... rest of your code
this will keep the original structure that works,
here's a snippet :
var $form = $('form#timesheet');
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
$form.submit(function(e) {
e.preventDefault();
var grouped = group($form.serializeArray());
console.log(JSON.stringify(grouped))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES"><br />
<input type="text" name="SUNDAY_NOTES"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES"> // and so forth
<input type="submit" id="submit" />
</form>

ajax get wrong value

I used ajax for my current project with laravel and i try to pass value of textbox using ajax but it pass R every time, even if i pass the wrong variable with ajax. my code is as below
<div class="form-group">
<label for="">Total Amount</label>
<input type="text" class="form-control" id="total_amount" value="123" name="total">
</div>
javascript code
$("#id_label_multiple").on('change', function () {
var list = $("#id_label_multiple").val();
var total = $("#total_amount").val();
console.log()
$.ajax({
url: "{{ action('hkcontroller#getTotal') }}",
data: {
lists: list, total: total, "_token": "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
$('#msg').html('Received ' + data + ' stones form exporter successfully!')
console.log(data);
}
});
});
laravel method
public function getTotal(Request $request)
{
$list = #$request['lists'];
$total = #request['total'];
return $total;
}
varibale list work fine but total always return value R, when it print first time log that time it print correct value in console, but second time in success function of ajax it print always R. where i made mistake??
Change this:
$total = #request['total'];
to this:
$total = #$request['total'];
^
Try like below:
$("#id_label_multiple").on('change', function () {
var list = $("#id_label_multiple").val();
var total = $("#total_amount").val();
console.log()
$.ajax({
url: "{{ action('hkcontroller#getTotal') }}",
data: "lists="+list+"&total="+total+"&_token={{ csrf_token()}}",
type: "POST",
success: function (data) {
$('#msg').html('Received ' + data + ' stones form exporter successfully!')
console.log(data);
}
});
});

Sending files with ajax not working as expected

I have a form which gets files along with other inputs , I want to pass those data to my ajax function. But when i check for those files in server , the server doesn't receive the file. I am new to ajax and Jquery. Here is what i have done.
<form id = "comp_inter_form">
<input type="radio" name="inter_fit" id="inter_good_fit" value = "good" >
<input type="radio" name="inter_fit" id="inter_bad_fit"
<input id="report_upload" type="file"/>
<input id="skype_upload" type="file"/>
<input id="audio_upload" type="file"/>
<input type = "submit" class = "update_interview_btn btn btn-primary" value = "Update"/>
</form>
Ajax function
function completeInterview(id,profile_id){
console.log("Candidate ID is : "+id+"\n Profile id is :"+profile_id );
$('#completeIntModal').modal('show');
var candidate_id = id;
var profile_id = profile_id;
var inter_fit,report_file,skype_file,audio_file;
$("#comp_inter_form").on('submit',function(){
var inter_fit = $("input[name=inter_fit]:checked").val();
var report_file = $("#report_upload").prop('files');
var skype_file = $("#skype_upload").prop('files');
var audio_file = $("#audio_upload").prop('files');
var dataString = 'inter_fit=' +inter_fit+ '&report_file=' +report_file+ '&skype_file=' +skype_file+ '&audio_file=' +audio_file+ '&candidate_id=' +candidate_id+ '&profile_id=' +profile_id;
$.ajax({
type: "POST",
url: "/complete_interview",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: dataString,
cache: false,
success: function(data) {
alert(data.msg);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
alert(xhr);
}
});
});
Please try to make it like following and check if it works, As you are trying to post content VIA ajax with file input, it has to be treated separately.
You have to use FormData for this.
$("#comp_inter_form").on('submit',function(){
var inter_fit = $("input[name=inter_fit]:checked").val();
var report_file = $("#report_upload").prop('files');
var skype_file = $("#skype_upload").prop('files');
var audio_file = $("#audio_upload").prop('files');
var dataString = 'inter_fit=' +inter_fit+ '&report_file=' +report_file+ '&skype_file=' +skype_file+ '&audio_file=' +audio_file+ '&candidate_id=' +candidate_id+ '&profile_id=' +profile_id;
var formData = new FormData();
formData.append("inter_fit",inter_fit);
formData.append("candidate_id",candidate_id);
formData.append("profile_id",profile_id);
var fileInput = $("#report_upload").get(0);
formData.append("report_file",fileInput.files[0]);
fileInput = $("#skype_upload").get(0);
formData.append("skype_file",fileInput.files[0]);
fileInput = $("#audio_upload").get(0);
formData.append("audio_file",fileInput.files[0]);
$.ajax({
type: "POST",
url: "/complete_interview",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
contentType: false, // Not to set any content header
processData: false, // Not to process data
cache: false,
success: function(data) {
alert(data.msg);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
alert(xhr);
}
});
On the server side you need to check for posted file array and process those accordingly.

Variable doesn't get passed to Ajax call : undefined variable

I've edited this question from the original OP to better represent my issue.
How can I pass the variable data-uid with AJAX ?
Right now the variable doesnt get passed.
var uid = $(this).data("uid"); doesn't work = undefined
var uid = '199'; gets passed. works.
is it possible to have something like : var uid = $uid; ?
HTML
<form>
<fieldset>
<textarea id="post_form" type="text" data-uid="<?php echo $uid ?>"/></textarea>
<button type="submit" id="add" value="Update" name="submit" />OK</button>
</fieldset>
</form>
JS
$(function() {
$("#add").click(function() {
var boxval = $("#post_form").val();
var uid = $(this).data("uid"); // this needs to be changed
var dataString = 'post_form=' + boxval + '&uid=' + uid;
if (boxval == '') {
return false;
} else {
$.ajax({
type: "POST",
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
return false;
});
});
problem in your code in:
var uid = $(this).data("uid");
you're trying to wrap this into jquery object, but it is button object in this context, then you're trying to obtain something unassigned from it
you shoud use:
var uid = $('#post_form').attr('data-uid');
or, you can add <input type="hidden" name=... value=... and get id from it, this is more general way
Looks like your issue is with the data attribute that should be data-uid="somevalue" Like.
Check this fiddle to see if this solves your main problem

Categories

Resources