Ajax page is reloading after storing data - ajax

i am triyng to save data but my page is reloading with json message on next page, how can i stop reloading page.
Ajax Code:
jQuery(document).ready(function($) {
$("#add-data").submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Submit Button:
<button type="submit" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
Store Controller:
after saving which is working fine:
return response()->json([
'status' => 'success',
'msg' => 'New esecond has been saved'
]);

It is because of you are trying to post the data to form .
If you use button type = "submit" it will redirect you to somewhere .
You should avoid using type = "submit" .
Instead use the type = "button"
<button type = "button" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
And achieve it by using click event of the button .
then get it in jquery .
$("#add-data").click(function (event) {
//Your code here
}

You can try this instead of prevent default. The reload happen, because you use form submit event.
$('#add-data').submit(false);
If you want to use prevent default, then use click event of the submit button to perform the action.
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
}

Remove dataType: 'json' as you're already returning JSON otherwise your button seems perfect.
Try this
jQuery(document).ready(function($) {
$("#add-data").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});

Add "return false;" in the end of your submit callback..
As "add-data" is ID of your button, for your example it couldn't retrieve a submit event. That's because it submitted and didn't prevented.
So you can write something like this:
$("form").submit(function (event) {
event.preventDefault();
$.ajax({ ... });
return false; // <<< THE THING
});
Or just do that with binding an click event on button (not for submit event on button)
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({ ... });
});
With this you can leave button type, and don't need to change that to type="button".

Related

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"

Laravel 5.7 9 Yajra Datatable delete button

My button in the table is created by:
return Datatables::of($members)
->addColumn('action', function ($id) {
return 'Edit
<button class="btn btn-primary btn-delete" data-remote="/admin/members/' . $id->id . '">Delete</button>
'; })->make(true);
The js function:
$('#datatable-member').on('click', '.btn-delete[data-remote]', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = $(this).data('remote');
alert(url);
$.ajax({
url: url,
type: 'DELETE',
dataType: 'json',
data: {method: '_DELETE', submit: true}
}).always(function (data) {
$('#datatable-member').DataTable().draw(false);
});
});
the return of the debugging alert is (for example): /admin/members/2
The route is this one:
DELETE | admin/members/{member} | members.destroy | App\Http\Controllers\Admin\MemberController#destroy | web
I have this error in the JS console:
jquery-3.3.1.min.js:2 DELETE http://127.0.0.1:8000/admin/members/2 404 (Not Found)
...and of course, the delete doesn't work...

Confirm Before Deleting with Sweet Alert Laravel 5.5

I want the sweet alert box to go out without deleting.
But id not found for ajax
Route
Route::get('room/delete/{id}', 'RoomList#destroy')->name('roomdelete');
View File rooms-list.blade.php
#foreach($rooms as $room)
<tr>
<td>{!! $room->room_id !!}</td>
<td>{!! $room->hotel_id !!}</td>
<td>{!! $room->room_name !!}</td>
<td>
<i class="fa fa-close text-danger"></i> </td>
</tr>
#endforeach
SweetAlert Js Code above
<script>
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "POST",
url: "{{url('room/delete')}}",
data: {id:id},
success: function (data) {
}
});
});
});
</script>
Controller File RoomList.php
public function destroy($id) {
$rooms = Room::find($id);
$rooms->delete();
return redirect()->back()->with('deleted', 'Delete Success!');
}
Clicking on the delete button does not work
Best Regards
First thing first, you have a GET route and you are sending a POST request here so first change your ajax method to GET like this:
<script>
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "GET",
url: "{{url('room/delete/')}}+id", // since your route has /{id}
data: {id:id},
success: function (data) {
}
});
});
});
</script>
Also I'm not sure about $(document).on('click', '.button', function (e) I guess it should be like this:
$('.button').on('click', '.button', function (e)
Let me know If you still have any issue.

Pass ASP MVC3 textbox value to Ajax call

I have a simple ASP MVC3 #Html.TextBox that I'm using to input search criteria. However, I need to append the value to the URL in an Ajax call as a query string. How would I go about this? Below is the HTML in the view:
<div class="editor-field">
#Html.TextBox("searchString")
<span onclick='GetCompName(searchString);'>
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
And here is the Ajax
function GetCompName(searchString) {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + searchString + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}
I will also want to output the returned value into another text box. If anyone knows how to do that that would be really helpful as well. Thanks!
the basic problem with your code is the searchString in onclick='GetCompName(searchString); always gonna be literally "serchString", you must specified the parameter in base the value in the input, like this $('.searchbox').val()
keep your javascript unobstructive.
HTML code
<div class="editor-field">
#Html.TextBox("searchString", null, new { #class = "serachbox" })
<span class="searchbox-trigger">
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
Set de handler for the event span click
$(document).ready(function() {
$('.searchbox-trigger').click(GetProgramDetails);
});
and your ajax request
function GetProgramDetails() {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + $('.searchbox').val() + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}

Resources