On success, div is loading only once through AJAX - ajax

I am trying to reload the table on every successful quantity change and row deletion in add to cart using ajax. But the table is getting reloaded only once after that no change is being observed.
Here is the code:
<script type="text/javascript">
$(".update-cart").change(function (e) {
e.preventDefault();
var ele = $(this);
$.ajax({
url: '{{ route('update.cart') }}',
method: "patch",
data: {
_token: '{{ csrf_token() }}',
id: ele.parents("tr").attr("data-id"),
quantity: ele.parents("tr").find(".quantity").val()
},
success: function (response) {
$("#cart").load(" #cart");
//alert("This is working");
}
});
});
$(".remove-from-cart").click(function (e) {
e.preventDefault();
var ele = $(this);
if(confirm("Are you sure want to remove?")) {
$.ajax({
url: '{{ route('remove.from.cart') }}',
method: "DELETE",
data: {
_token: '{{ csrf_token() }}',
id: ele.parents("tr").attr("data-id")
},
success: function (response) {
$("#cart").load(" #cart");
}
});
}
});

Button id b1 can be clicked only once, id b2 can be live clicked.
function why(e) {
e.preventDefault();
alert("You clicked " + e.target.id);
$("#myDiv").html('<button id="b1" type="button">Click Me!</button><button id="b2" class="button" type="button">Click Me!</button>');
}
$("#b1").click(why);
$(document).on("click", ".button", why);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv">
<button id="b1" type="button">Click Me!</button><button id="b2" class="button" type="button">Click Me!</button>
</div>

Related

The GET method is not supported for this route. Supported methods: POST. Laravel Ajax

I'm using ajax to send comments. This is the route
Route::post('/users/add/comment/', 'UsersController#AddComment')->name('AddComment');
The ajax call
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
type: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
and the controller
public function AddComment(Request $request){
dd($request);
}
It always throws that error. I changed the route and the func name a lot of times. but it does the same thing and the dd(); request is always empty.
Thanks in advance!
You have to set the ajax method to post with the attribute 'method', not 'type'.
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
I was trying to send the same data using <form> I tried AJAX to have more control over the request.
my form tag goes like <form method="POST" action="/users/add/comment/">
I removed the last / in the URL and it does work. I don't know how or why.
But It works !!!
Form
<form id="YourForm">
...
your inputs
...
</form>
Button
<button type="button" class="btn btn-success SendButton">Save This</button>
JS
<script type="text/javascript">
$(document).on('click', '.SendButton', function (e) {
e.preventDefault();
var data = $("#YourForm").serialize();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method : "POST",
url : "{{ url('users/add/comment/') }}",
data : data,
dataType : "JSON",
})
.done(function(response) {
alert('Success!');
location.reload();
.fail(function(response) {
console.log("Error: ", response);
});
return false;
});
</script>
You need to change type to method, you use the wrong keyword. Now it is a default GET
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post', // it should be method: 'post'
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});

Print automatically on form close

I have a button that prints something and it works well.
I would like to print automatically when the form is closed.
At the moment the form sends an email to my customers with order details (it works very well) but now I would like to print automatically without requiring the user to push a button.
Please help me. I am a beginner here.
Relevant code:
<a
href="#!"
target="_blank"
id="save-and-print"
type="submit"
title="Speichern & Drucken">
<i class="fa fa-print"></i>
</a>
<script type="text/javascript" src="/js/summernote.js?v=0.72"></script>
<script>
$( function() {
$('#save-and-print').on('click', function (e) {
e.preventDefault();
var url = 'myOrders/replacement/' + '{{ $data->id }}';
}
});
$.ajax({
type: "PATCH",
url: '/myOrders/replacement/' + '{{ $data->id }}',
data: $("form").serialize(),
dataType: 'json',
success: function (data) {
window.location.reload();
location.href = '{{ route('print', [$data->id, 'option' => 'advance']) }}';
},
error: function (data) {
$('body').pgNotification({
style: 'flip',
message: 'Error',
position: 'top-right',
type: 'danger',
timeout: 4000
})
},
});
</script>
If you want the same action to take place on the submit event of your form as what happens when your id="save-and-print" button is being pressed, you could do something like this:
function printSomething(event) {
var url = 'myOrders/replacement/' + '{{ $data->id }}';
}
const form = document.getElementById('form');
form.addEventListener('submit', printSomething);

How to send data from ajax to controller

I want to transfer data to the controller using ajax. Here is the ajax code
$(document).on("click", '#bt1', function(e)
{
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:{
name2:"admin",
_token: $("input[name='_token']").val()
}
})
});
Here is the code in the controller
public function insert_db(Request $request)
{
dd($request->all());
}
Here is the layout code
<form action="/insert_" method="post">
#csrf
<input type="submit" id="bt1" value="do it">
</form>
Here is code в web.php
Route::post('/insert_',"StudentController#insert_db");
Displays this
Why does display this? Please help
Your jquery ajax request should look like below:
$(document).on("click", '#bt1', function(e)
{
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:{
"name":"test",
_token: $("input[name='_token']").val()
}
})
});
or
$(document).on("click", '#bt1', function(e)
{
var payload = JSON.stringify({
'name': 'test',
'_token': $("input[name='_token']").val()
});
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:payload
})
});
There is nothing wrong with your code, but i will love to get the string part by coding it like this
$(document).on("click", '#bt1', function(e)
{
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:{
"name2":"admin",
_token: $("input[name='_token']").val()
}
})
});
noticed that i changed name2:"admin" to "name2":"admin"

passing model from view to controller using jquery

I have a view
#using staffInfoDetails.Models
#model staffInfo
<link href="../../Content/myOwn.css" rel="stylesheet" type="text/css" />
#{staffInfo stf = Model;
}
<div id="education1">
#using (Html.BeginForm("addNewEdu","Home",FormMethod.Post))
{
#Html.HiddenFor(x=>x.StaffId)
<table>
<tr>
<th>Country</th>
<th>Board</th>
<th>Level</th>
<th>PassedYear</th>
<th>Division</th>
</tr>
<tr>
#Html.EditorFor(x => x.eduList)
</tr>
<tr>
#*<td><input type="submit" value="create Another" id="addedu"/> </td>*#
#*<td>#Html.ActionLink("Add New", "addNewEdu", new { Model })</td>*#
</tr>
</table>
}
<button id="addedu">Add Another</button>
</div>
I want to pass the model staffInfo to controller using jquery as below
<script type="text/javascript">
$(document).ready(function () {
$("#addedu").live('click', function (e) {
// e.preventDefault();
$.ajax({
url: "Home/addNewEdu",
type: "Post",
data: { model: stf },//pass model
success: function (fk) {
// alert("value passed");
$("#education").html(fk);
}
});
});
});
</script>
the jquery seems to pass only elements not whole model so how can I pass model from the view to the controller so that I don't have to write the whole parameters list in jquery
u can give ID to the form by using this
#using (Html.BeginForm("addNewEdu", "Home", FormMethod.Post, new { id = "addNewEduForm" }))
{
}
Then in the script
<script type="text/javascript">
$('#addedu').click(function(e) {
e.preventDefault();
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: $("#addNewEduForm").serialize(),
success: function(data) {
}
});
}
});
</script>
As I can see you trying to submit form with AJAX? Look at serialize function.
$('#addedu').click(function(e) {
e.preventDefault();
var form = $('form');
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(r) {
}
});
}
});
You can get your values with getElementById then send your action:
$(document).ready(function () {
var select = document.getElementById('...');
$.ajax({
type: "get",
url: "get_street_name",
data: { a: select },
success: function (data) {
$('#result').html(data);
}
});
}

Why Ajax Jquery form click not working vs div that works?

Ajax Jquery form not working vs div why its happen and how can i fix my error?
view.html-Code with form
not working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<form id="parse-form" action="#" method="post">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</form>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
view.html -form replaced by div
working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<div id="parse-form">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</div>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
controller.php -simple php file that return json array:
<?php
$arr=array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Thanks
The form has a default action with a type="submit" button, which is submitting, so you'll need to stop that from happening by adding return false or event.preventDefault() , like this:
$(document).ready(function() {
$('#submit-html').click(function(e) {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
return false;
//or e.preventDefault();
});
});
Without this, the form is submitting as it normally would with no JavaScript, leaving the page. So effectively it's doing a refresh, instead of AJAX submitting your form (which doesn't have time to complete...because you left :)
An element of type=submit inside a <form> will perform the form request when clicked on.
You need to abort the default behavior by running event.preventDefault() inside the click callback.
My guess is that the form is submitting and refreshing the page before the ajax has a chance to respond.
Try putting return false; at the end of the click handler.
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Of course you'll have the same issue if the user hits Enter in one of the fields. Unless you're preventing the Enter key from submitting the form, you may want to the handle the event using the submit() handler.
$('#parse-form').submit(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Try using submit() http://api.jquery.com/submit/ , this should work with keyboard events as well as clicks. You can use serialize() to get any form data into the ajax objects data variable.

Resources