GAE: Not posting to local datastore (angular) - javascript

Ive got the following code. From chrome dev tools everythin is 200 OK and 302 after clicking post button but nothing is showing up on local datastore.
"Recommendation" model
class Recommendation(ndb.Model):
comment = ndb.StringProperty()
post method from python webapp2
def post(self):
r = json.loads(self.request.body)
new_comment = Recommendation(comment=r['comment'])
new_comment.put()
/exp.html
<form ng-submit="addComment()" method="post" id="frmComment">
<textarea ng-model="formFields.comment" id="comment" name="comment" class="form-control status-box comment" rows="2"></textarea>
</form>
<div class="button-group pull-right">
<button form ="frmComment"class="btn btn-primary pst sameline" type="submit">Post</button>
</div>
angular http post
$scope.formFields = {
comment : ""
}
$scope.comments = [];
$scope.addComment = function() {
var form_comment = $scope.formFields.comment
var payload = {
comment: form_comment
}
$http({
method: 'POST',
url: '/exp.html',
data: payload
}).then(function(response) {
$scope.comments.push(payload);
console.log(payload)
}, function(response) {
});

Related

Send a value of foreach loop form using ajax in laravel

I'm trying to send value from form to controller but the error that faced me all forms send value as a first form id I want each form to send the data inside it when I press the send button, but what happens is that everyone sends its content based on the first ID of the form;
blade code
#forelse($matches as $match)
<form class="ajaxform">
#csrf
<div class="wrapper-new1">
<input type="text" class="form-control" name="record_one" id="validationCustom18" value="{{$match->record_one}}" required>
<input type="text" class="form-control" name="record_two" id="validationCustom18" value="{{$match->record_two}}" required>
<input type="hidden" class="form-control" name="id" value="{{$match->id}}" id="validationCustom18" >
</div>
<button type="submit" style="margin-top: 4px;" class="btns">تغيير نتيجة المباراة </button>
</form>
#empty
<div class="alert alert-danger"> لا يوجد مباريات لعرضها الان </div>
#endforelse
ajax code
$('.btns').on("click", function(event){
event.preventDefault();
let record_one = $("input[name=record_one]").val();
let record_two = $("input[name=record_two]").val();
let id = $("input[name=id]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: "/admin/team/matchesList/"+id+"",
type:"POST",
data:{
record_one:record_one,
record_two:record_two,
id :id,
_token: _token
},
success:function(response){
console.log(response);
if(response) {
$('.success').text(response.success);
$(".ajaxform")[0].reset();
}
},
});
});
$('.btns').on("click", function(event){
event.preventDefault();
let form = $(this).closest('.ajaxform');
let record_one = form.find("input[name=record_one]").val();
let record_two = form.find("input[name=record_two]").val();
let id = form.find("input[name=id]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: "/admin/team/matchesList/"+id+"",
type:"POST",
data:{
record_one:record_one,
record_two:record_two,
id :id,
_token: _token
},
formElement:form,
success:function(response){
console.log(response);
if(response) {
$('.success').text(response.success);
this.formElement[0].reset();
}
},
});
});

Sending image from Form in FormData with Ajax doesn't appear on server side (Flask python)

I want to create Bootstrap Modal that has a form with textarea and image, and send that to the server.
My form on modal looks like this:
<form id="formData" method="POST" enctype="multipart/form-data">
<fieldset class="form-group">
<div class="form-group">
<textarea class="form-control" id="content" name="content" required></textarea>
</div>
<div class="form-group">
<label for="image">Got any photo?</label>
<input class="form-control-file" id="image" name="image" type="file">
</div>
</fieldset>
<button class="btn purple-btn-outline-modal" type="submit">Add</button>
</form>
The AJAX I'm using:
var form = document.forms.namedItem("formData");
form.addEventListener('submit', function (ev) {
var oData = new FormData(form);
oData.append('image', $('#image')[0].files[0])
for (var p of oData) {
console.log(p); // <- logs image in oData correctly
}
$.ajax({
url: '/test/',
type: 'POST',
method: 'POST',
data: oData,
enctype: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
success: function (data) {
},
});
ev.preventDefault();
}, false);
But on the server side (Python Flask) the image is not in request form:
#main.route('/test/', methods=['POST'])
def test():
if request.method == 'POST':
app.logger.debug(request.form) # ImmutableMultiDict([('content', 'my sent content')])
app.logger.debug(request.form['content']) # 'my sent content'
app.logger.debug(request.form['image']) # <- KeyError: 'image'
return jsonify(...)
What is wrong?
SOLVED.
Solution by #v25:
request.files['image']
worked.

Populate textfield on page opening

I have simple form being opened clicking on tab
<form name="instructions" class="form form-horizontal" ng-controller="InstructionsPage">
<div class="form-group">
<label for="instruction">Instructions</label>
<textarea id="instruction" rows="5" class="form-control" ng-model="instructions">
</textarea>
</div>
<button class="btn btn-primary" data-ng-click="saveInstructions()">Save</button>
</form>
and related controller
angular.module('myApp.controllers')
.controller('InstructionsPage', ['$scope', function ($scope) {
use strict';
$scope.saveInstructions = function() {
var data = $scope.instructions;
// post request with data from textfield inside
}
}]);
How to receive data with GET-request to populate textfield with default/previously saved data? Thank you!
You can just update your $scope.instructions variable which is bound to the <textarea> ng-model from your controller like this:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.instructions = response;
}, function errorCallback(response) {
});

angular js: Error: $ is not defined in http post

I'm trying to post values from a form. Form has two fields- name and email. I have setup the controller as well but when i try to post, error is shown.
<form name="save" ng-submit="sap.saved(save.$valid)" novalidate>
<div class="form-group" >
<input type="text" name="name" id="name" ng-model="sap.name" />
</div>
<div class="form-group" >
<input type="email" name="email" id="email" ng-model="sap.email" />
</div>
<div class="form-actions">
<button type="submit" ng-disabled="save.$invalid || sap.dataLoading">Save</button>
</div>
</form>
My controller is:
(function() {
angular
.module('myApp.saved', [])
.controller('dataController', function($scope, $http) {
var sap = this;
$scope.post = {};
$scope.post.login = [];
$scope.sap = {};
$scope.index = '';
var url = 'save.php';
sap.saved = function(isValid)
{
if (isValid)
{
$http({
method: 'post',
url: url,
data: $.param({'user' : $scope.sap }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response)
{
// success
alert('success');
},
function(response)
{
// failed
alert('failed');
});
}
};
});
})();
When i submit, $ is not defined is shown. I'm pretty much new in angular. Can anyone tell what all mistakes I made?
$ is alias for jQuery and param is a jquery method.
Have you included jQuery?
data: $.param({'user' : $scope.sap }),
should be
data: {
'user': $scope.sap //POST parameters
}
data – {string|Object} – The response body transformed with the transform functions

How to replace or update existing content in textarea by using http.post method?

I plan to POST my text content to http://language.cs.usm.my/synthesis/read.php form's textarea which is third party web page, below is the form that i get from the URL.
<form method="post" action="">
<p>Key in sentences in Malay. </p>
<textarea name="malayText" rows="4" cols="100">Malaysia ialah sebuah negara raja berperlembagaan persekutuan di Asia Tenggara yang terdiri daripada 13 negeri dan tiga wilayah persekutuan. Ia menduduki bumi berkeluasan 329,847 kilometer persegi.</textarea>
<input type="submit" value="OK" name="submit" />
</form>
The method i use to post data as below:
$scope.AudioCont = function(){
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test:"Nama saya ialah Ali"
}
})
.then(
function (response) {
alert("The data has been posted");
console.log(response);
},
function () {
alert("Failed to post!");
})
}
How can i replace the content in the existing textarea with my data?
Thanks
you have to add ng-model on the input or textarea
<form method="post" action="">
<p>Key in sentences in Malay. </p>
<textarea name="malayText" rows="4" cols="100" ng-model="yourtextarea"></textarea>
<input type="submit" value="OK" name="submit" />
</form>
and in the controller get him with $scope.yourVarName
$scope.yourtextarea ;
$scope.AudioCont = function(){
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test:$scope.yourtextarea
}
})
.then(
function (response) {
alert("The data has been posted");
console.log(response);
},
function () {
alert("Failed to post!");
})
}
You need to use ng-model
<textarea name="malayText" rows="4" cols="100" ng-model="malayText">
and then you can readily access it in your controller
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test: $scope.malayText
}
I used ajax method to solve this problem with auto submit the form when i perform the POST action. Below is my code and solution:
$.ajax({
type: 'POST',
url: 'your url',
data: {'submit': 'submit', 'malayText' : "data that wish to POST"}, // you can use as much as data you want to send,
dataType: 'JSON' // so you can use the json_encode php function
});

Categories

Resources