Request with Ajax from java script not working - javascript

I have this button in my HTML code :
<button type="submit" id="post-form" class="btn btn-primary" onclick="send()">Send</button>
And the java script code with function send() :
function send() {
$.ajax({
type: 'POST',
url: "http://app.localhost/feedback",
dataType: "json",
data : {
feedback: $('#feedback').val(),
email: $('#email').val(),
},
success : function(json) {
$('Backdrop').hide();
console.log("requested access complete");
}
});
}
And in my views from django project I have the function related to entry-point /feedback. But the execution never arrives at the success step.
And also from postman I can send the request but from js it is not working.
The view related to my entry point is :
#csrf_exempt
def feedback(request):
if request.method == 'POST':
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
fromField = body['email']
subject = 'New FeedBack from {}'.format(fromField)
body = body['feedback']
sendEmail("ex#ex.co", subject, body,
replyTo=['ex#ex.co', 'ex.ex#gmail.com'])
return redirect('/')

Is that button a form submit button?
If so, you don't need the button's onclick event.
Try the following.
<form id="yourForm">
<button type="submit" id="post-form" class="btn btn-primary">Send</button>
</form>
$("#yourForm" ).submit(function() {
$.ajax({
type: 'POST',
url: "http://app.localhost/feedback",
dataType: "json",
data : {
feedback: $('#feedback').val(),
email: $('#email').val(),
},
success : function(json) {
$('Backdrop').hide();
console.log("requested access complete");
}
});
});
Hope this helps.

Related

html form in Django returns none

I am trying to save this HTML form in my table in the database, but I am getting "None" error. I have been on this for some hour. Please any help will be appreciated
Please, how do i fix this
The is the HTML order.html i created
<form action="" method="post" id="payment-form">
<input type="text" class="form-control" id="first_name"
name="first_name"
value="{{request.user.first_name}}">
<textarea type="text" class="form-control" id="address" name="address"
placeholder="1234 Main St" required></textarea>
<button id="submit" class="btn btn-success lg w-100 fw-bold" >
Proceed to Payment
</button>
</form>
Here is my views.py
def add(request):
basket = Basket(request)
if request.POST.get("action") == "post":
order_key = request.POST.get("order_key")
user_id = request.user.id
baskettotal = basket.get_total_price()
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
address = request.POST.get("address")
print(first_name, last_name, address)
order = Order.objects.create(
first_name = first_name,
address=address,
total_paid=baskettotal,
)
order_id = order.pk
response = JsonResponse({"success": "Order created"})
return response
The js file
<script type="text/javascript">
function makePayment(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "order:add" %}',
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
action: "post",
},
success: function (json) {
console.log(json.success)
},
error: function (xhr, errmsg, err) {},
});
}
</script>
First of all you don't have to post extra value action to determine post request you just have to use request.method it will return you all available method you can check for specific method by adding check like this
if request.method == "POST":
note : allways use capitalized method while adding this check
and I'm not sure where you're calling makePayment() function and whatever data you're trying to access in your python script you've to pass it through ajax{data:{}} like this
function makePayment(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "order:add" %}',
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
order_key : "your order key",
first_name : $('#first_name').val(),
last_name : $('#last_name').val(),
address : $('#address').val()
},
success: function (json) {
console.log(json.success)
},
error: function (xhr, errmsg, err) {},
});
}
and than access it like this
def add(request):
basket = Basket(request)
if request.method == "POST":
order_key = request.POST.get("order_key")
#....all other fields

How to pass double variable through laravel jquery? No response is shown on button click

I am trying to send a jquery request to update the table, that route requires two variables id, Receive_id. I tried this code below but the button on-click does not show any response. Plz review my code or suggest me if there are any other ways to send route.
here is my blade code
<button data-url="{{ route('repairs.updateCylinder',['id'=> $cylinder->id, 'receive_id' => $data->id]) }}" class="btn btn-primary submit" id='update-cylinder'>Update</button>
Here is Jquery code,
<script>
$(document).ready(function(){
$(document).on("click", "#update-cylinder", function() {
// e.preventDefault();
var url = current.data('url')
var id=
$.ajax({
url: url,
type: "PATCH",
cache: false,
data:{
_token:'{{ csrf_token() }}',
body_leak: $('#body-leak').val(),
nozzle_change: $('#nozzle-change').val(),
nozzle_repair: $('#nozzle-repair').val(),
cap_change: $('#cap-change').val(),
washer_change:$('#washer-change').val(),
wash:$('#wash').val(),
refill:$('#refill').val(),
remarks:$('#remarks').val()
},
success: function(dataResult){
dataResult = JSON.parse(dataResult);
if(dataResult.statusCode)
{
window.location = "/repairs/updateCylinder";
}
else{
alert("Internal Server Error");
}
}
});
});
});
</script>
You can add a data-id on your button :
<button data-id="{{$cilinder->id}}" data-receive-id="{{ $data->id }}" class="btn btn-primary submit" id='update-cylinder'>Update</button>
and on your script section :
$("#update-cylinder").on("click", function(e) {
e.preventDefault();
let id = $(this).data("id");
let receive_id = $(this).data("receive-id");
let url = "repairs/updateCylinder/"+ id;
let data = new FormData($('#id_form')[0]);
$.ajax({
url: url,
type: "PATCH",
cache: false,
data : data,
datatype:'json',
success: function(response){
if(response.success == true){
window.location "/repairs/cylinderlist";
}else{
alert("Error to update...");
}
});
}

Why is my ajax not passing in my parameter (always empty) via POST in Razor Page application?

I need this ajax call to run my onpost handler PassPart. It successfully calls it, but my parameter "searchedpart" is always empty. I've also tried passing the parameter directly in my url, like: "?handler=passPart" + "&searchedpart=" + searchedpart , but it's still empty. Lastly, I've tried using "Request.Form[SearchedPart]" in my method to pull the value in, also empty. I've tested that this element is not empty by adding an alert message to my js to confirm, and I see the value being found.
ps. I'm using an EmptyResult because I don't need anything posted back. I simply need it to run through my handler using the parameter.
<form method="post">
<input class="form-control" name="searchedpart" asp-for="PostData.SearchedPart" value="#Model.PostData.SearchedPart" id="searchedpart" />
<button type="submit" id="searchpartbtn" class="btn btn-success btn-sm">Find</button>
</form>
document.getElementById('searchpartbtn').addEventListener('click', PassPart);
var searchedpart = document.getElementById('searchedpart').value;
function PassPart() {
$.ajax({
type: "POST",
url: "?handler=passPart",
dataType: "json",
data: JSON.stringify({ searchedpart: searchedpart }),
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
}
});
}
public ActionResult OnPostPassPart(string searchedpart = "")
{
if (searchedpart != "") {
// Do Things
}
return new EmptyResult();
}
Because searchedpart is already a string type, there is no need to JSON.stringify.And you should write your var searchedpart = document.getElementById('searchedpart').value;code inside your function.
Just change your code as below:
document.getElementById('searchpartbtn').addEventListener('click', PassPart);
function PassPart() {
var searchedpart = document.getElementById('searchedpart').value;
$.ajax({
type: "POST",
url: "?handler=PassPart",
dataType: "json",
data: { "searchedpart": searchedpart },
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
}
});
}
In your background:
public ActionResult OnPostPassPart(string searchedpart)
{
//...
}
Result:
I ended up using the following in my method to get this working:
string part = Request.Form["SearchedPart"];
remove dataType: "json"
Add header token

Laravel ajax delete request

so here is my delete button
<button class="btn btn-danger btn-xs btn-delete delete" value="{{$post->id}}">Delete</button>
then the ajax request
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "DELETE",
url: "{{route('delete_post')}}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
the route
Route::get('delete_post','PostController#getDeletePost');
then the controller:
public function getDeletePost($post_id)
{
$post = Post::where('id', $post_id)->first();
$post->delete();
return redirect()->route('dashboard')->with(['message' => 'Successfully deleted!']);
}
so please help me identfy why nothing really happens when i press the delete button
I have modified you javascript, first issue in your code is,you must either use get request or post request, second issue you are not using named route in order call url for ajax like {{ route() }} , it should be {{ url('path') }} or name your route..
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "get",
url: "{{ url('/') }}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
You are sending a DELETE request type in your Ajax call, which would require a _method parameter with a value of DELETE added to your AJAX data. Your route is a GET route, so that is why you are seeing no action
Another problem is in your blade syntax you are referencing a named route 'delete_post', but that is your URL, not the route name. You have not named the route from what you have posted
Try updating this line in your routes file and that should allow the request to make it to your controller method.
Route::post('delete_post','PostController#getDeletePost')->name('delete_post');
Now you have to change your Ajax request type to
type: "POST"

how to prevent redirect on form submit

i am getting a form with user parameters when i make an AJAX call to a page which later on is submiited to a url so that i can create a session for the same user in advance and when
that person goes to that site he sees his name there.
i created one div tag with id "abc_session", assign that form (whose id is fm1) to it,and submitted the form.
now as per the requirement session is created but page automatically gets redirected to that site url to which form is submitted.i just don't wan't that to happen.
can anyone please suggest something..or some workaround
the form that AJAX returns looks something like this:
<html>
<body onload="document.fm1.submit();return false">
<form name = "fm1" method="post" action = "https://abcd.com/abc ">
<input type=hidden name ="name" value="xyz">
<input type=hidden name ="login_parameters" value="CDF5D71C5BDB942EE2FB6C285B8DEBFE4C5675137B615CD2276571813AAC872AC8942E26B71026414BED1FEA09427D0B20A50FE2F70032D2E5B382598EC3C71D73EAB4ECBF7273A73BEB98ACEA4A0B775E7772BDC7C6746C355">
</form></body>
</html>
and the script goes like this
$(document).ready(function() {
function callwebsite()
{
$.ajax({
url: "/NASApp/benemain/website",
data: {},
type:"POST",
dataType: 'text',
cache: false,
success: function (data) {
alert("Call made to website.. ");
console.log(data);
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit();
},
error : function(response){
console.log('ERROR');
},
statusCode : {
500 : function() {
console.log('500 error');
window.location.reload(true);
},
401 : function() {
console.log('401 error');
window.location.reload(true);
},
404 : function(){
console.log('400 error');
}
}
});
}
callwebsite();
tried extracting the data and maiking another ajax call as suggested by quentin but getting this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource.This can be fixed by moving the resource to the same domain or enabling CORS."
$.ajax({
url: lcAction,
data: {partner_id:lcPartner,login_parameters:lcLP },
type:"POST",
headers:{'Access-Control-Allow-Origin': '*'},
dataType: 'text',
//crossDomain: true,
//cache: false,
success: function(data)
{
alert("success");
},
error:function(response)
{
//alert("error");
console.log(response);
}
});
You are submitting the form:
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit(); // Here
Don't do that.
Extract the data from it and make another Ajax request.
You should use e.preventDefault() as soon as you submit the form.

Categories

Resources