post html form in json format using ajax to Django - javascript

I have the below html form, which I would like to post to a url using ajax in JSON format,
I am unable to receive the response in Django (backend), please advise where I am going wrong.
Here is my html form.
<form id ="addressform" >
<input type="text" name="DoorNo" id="text-basic" value="" placeholder="Door no.">
<input type="text" name="BuildingName" id="text-basic" value="" placeholder="Building/Road Name">
<button type="submit" onclick="addressform()" >Submit</button>
</form>
Here is my jQuery
function addressform() {
var data = $('#addressform').serializeArray();
$.post('/suggestions', data);
}
Here is my function in views.py in Django (backend).
def suggestions(request):
data = json.loads(request.body)
#print data
return HttpResponse( json.dumps({"status" : 1}) )

Can you add the URL above that you direct to?
function addressform() {
$.ajax({
url : "{% url 'app:your_view' %}",
type: "POST",
data: { ... },
success : function(json) {
//success!
console.log(json);
},
error : function(xhr,errmsg,err) {
// what to do it there is an error
}
});
};
})
Also depending on the version of python you are using. You could use
return JsonResponse(data_you_want)
I'm a little confused as to what you're doing in your view...

Related

unable to send data from html div to flask server

I have a div element with data. I want to pass the div to flask but I'm getting Badrequestkeyerror:400 bad request: keyerror:'yourdiv'
Please find the below html code:
<div id="rightdiv">
item1,item2,item3,item4
<form action="{{ (url_for('get_div_info') }}">
<input type="submit" value="Submit">
</form>
</div>
<script>
let yourdiv = document.getElementById("rightdiv").innerHTML;
$.ajax({
type: 'post',
url: '/divinfo',
data: {'yourdiv': yourdiv},
success: function (data) {
console.log(data);
},
error{
alert('something went wrong')
}
});
</script>
Flask endpoint
#app.route('/divinfo', methods=['POST'])
def get_divinfo():
divinfo = request.form['yourdiv']
print(divinfo)
return ('', 200)

Update using AJAX returns error and going directly to the route shows "MethodNotAllowedHttpException No message"

I am trying to use ajax to update. It always return an error and I don't know where to look. What I'm trying to do is to update without having to reload the page.
VIEW:
<form id="view-int-form">
#csrf
<h1>ID Number:</h1>
<input type="text" name="id_number" value="{{$var1->id_number}}">
<h1>Name:</h1>
<input type="text" name="name" value="{{$var1->name}}">
<button type="button" id="clickme" value="Save">Save</button>
</form>
AJAX:
$(document).on("click", "#clickme", function(){
$.ajax({
url: '/updatename',
type: 'POST',
data: $("#view-int-form").serialize(),
success: function (data) {
alert("SAVED");
},
error: function (data) {
alert("ERROR");
}
});
});
ROUTE:
Route::post("/updatename","UsersController#UpdateName");
CONTROLLER:
public function UpdateName(Request $request){
$id = $request->input('id_number');
$update_name = $request->input('name');
users::where("id_number",$id)->update(['first_name'=>$update_name]);
}
Thank you to anyone that can help.
Its the error with the URL you provided. Its always better to provide URL like below,
url: '{{URL::to('updatename')}}',
Also, you can name your url in web.php like this,
Route::post("/updatename","UsersController#UpdateName")->name('update_name');
then use like this,
url:: '{{route('update_name')}}',
You are missing {{ csrf_field() }} in form and method="POST" in form tag.
Try replace #csrf from your view to {{ csrf_field() }}

Javascript post String with ajax to backend(java)

I'm programming a commentary box for a Web Client.
I have two tables, one for the Comments and one for the Users. I want to send Input Data from my <input> tags in HTML form to my Java Service. In this Service, I handle the received data. My Problem now is, that I get an HTTP-415 error and I don't know what to do Right now.
I am using AJAX in JavaScript to post the Data.
HTML
ID: <input type="text" name="id" value="1" readonly/> <br/>
Author: <input type="text" name="author"/> <br/>
comment: <input type="text" name="comment"/> <br/>
<button id="submit" type="Button" >Submit</button>
Javascript
function addPost(givenID){
var $author = $("#author");
var $comment= $("#comment");
var $id = $("#id")
$("#submit").on("click", function(){
var post = $author.val()+"*"+ $id.val()+"*"+ $comment.val();
$.ajax({
type: "POST",
url: "api/kommentar",
data: post,
success: function(){
console.log("SUCCESS");
},
error: function(){
console.log("FAILIURE");
}
});
});}
Java
#Path("/kommentar")
public class KommentarService {
#EJB
private KommentarManagement postMgmt;
public KommentarService() { }
#POST
#Consumes("text/plain")
public void addPostsAsJson(String income) {
System.out.println(income);
//CODE TO HANDLE...
}
jQuery's default content type for the Ajax function is 'application/x-www-form-urlencoded; charset=UTF-8'.
Because the service is expecting 'text/plain' the content type needs changed.
Add a content type:
data: post,
contentType: 'text/plain', //<--- insert
success: function(){

laravel pass data from controller to jquery using json

I want to pass data from controller to jquery using json don't know where is the problem but fro the jquery code I think its working fine as I tested the success code but can't get back the result from controller
home.blade
<form role="form" name="form_address" id="form_address" action="" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="text" id="postal_code" onFocus="geolocate()">
<input type="text" id="totaldistance" onFocus="geolocate()">
</form>
<button id="save_address">Save</button>
<script>
$("#save_address").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
e.preventDefault();
var form = document.forms.namedItem("form_address");
var formData = new FormData(form);
$.ajax({
type: "get",
url: 'Get_distance',
contentType: false,
data: formData,
processData: false,
success: function(data) {
$('#totaldistance').val(data.distance);
}
});
});
web.php
Route::post('Get_distance','HomeController#getdistance');
controller
public function getdistance(Request $request)
{
$distance =$request->postal_code;
return Response::json(array(
'distance' => $distance,
));
}
Change your ajax type to POST, because your route type is POST, not GET.
Your defined route in web.php is a POST request, but your Ajax method is set to GET request. Change web.php to a GET request for it to work. Make sure to provide an error function to catch any errors from server side.
Or vice versa, change Ajax request to POST since you already added the csrf setup.

Laravel csrf token mismatch on ajax post a second time

im trying to submit an ajax post in laravel but im having some problem regarding the form's csrf token. In my form, if the conditions i set in my ajax post url has been met the first time the form has been submitted. However if i submit the form and purposely failed the conditions i set in my ajax post url in the first try, If i submit the form again i get a token mismatch exception in my ajax error log. Do i need to refresh the csrf_token every ajax post?
Below is my code
JS
$(document).on('submit','.registration-form',function(e){
e.preventDefault();
var form = $(this);
var form_url = $(this).attr("action");
var form_values = $(this).serialize();
$.ajax({
url:form_url,
type:'POST',
data:form_values,
dataType: 'json',
async:false,
success: function(result){
console.log(result);
if(result['status']==true){
location.href = result['redirect'];
}
else{
form.find(".form-details").show().html(result['message']);
}
},
error: function(ts) {
console.log(ts.responseText)
}
});
});
HTML
<form action="{{ url('login') }}" method="POST" class="registration-form">
{{ csrf_field() }}
<input type="text" name="username" class="input" placeholder="Email">
<input type="password" name="password" class="input" placeholder="Password">
<button class="button is-redbox is-flat is-fullwidth">Login</button>
</form>
Are u sure that each time that is send in ajax?
data: {
"_token": "{{ csrf_token() }}",
}
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
public function regenerateToken(){
session()->regenerate();
return response()->json([
'msg'=>'success',
'token'=>csrf_token()
]);
}
$('#form').submit(funtion(event) {
event.preventDefault(event);
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
if (response.msg === 'success') {
$('#token').val(response.token);
console.log($('#token').val());
}
}
$('input[type="text"],input[type="email"] ,textarea, select').val(''); $(this).trigger('reset');
});

Categories