ajax is not working in Laravel showing page not found - javascript

I want to send OTP with Laravel and ajax but when i'm calling ajax it shows error page not found...
HTML:
`
<div id="first_step">
<div class="col-md-4">
<input value="+91" type="text" placeholder="+1" id="country_code" name="country_code" />
</div>
<div class="col-md-8">
<input type="text" autofocus id="phone_number" class="form-control" placeholder="Enter Phone Number" name="phone_number" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-4">
</div>
<div class="col-md-8 " id="otp_input">
<input type="text" autofocus id="user_otp" class="form-control" placeholder="Enter OTP" name="otp" id="result" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication1"> </div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication">
<input type="button" class="log-teal-btn small" id="send_otp_button" value="Verify Phone Number"/>
</div>
</div>
`
script:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
var host = "{{URL::to('/')}}";
alert(host);
$.ajax({
type: "POST",
url: host+"/send_otp",
data: {name:phone_number},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
}); });
Route in web.php:
Route::post('/send_otp', 'AccountAuth\RegisterController#send_otp_function');
//Route::post('/send_otp', 'AccountAuth\RegisterController#send_otp_function'); also try this
Controllers:
public function send_otp_function(Request $request)
{
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return Response::json($response);
}

Welcome to SO. As far as I understand and according to jQuery.ajax documentation you have forgotten to set datatype='json' in your ajax request. Your request should be:
$.ajax({
type: "POST",
url: host + "/send_otp",
datatype: 'json',
data: {
name: phone_number
},
success: function(msg) {
alert(msg);
},
error: function(request, status, error) {
alert(request.responseText);
}
});

I see a few things that could be throwing the error.
You are prepending the ajax url to post to with the variable host. It's not needed, you should try it this way:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
$.ajax({
type: "POST",
url: "/send_otp", //remove the host variable here
data: {name:phone_number},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
As per Laravel documentation (https://laravel.com/docs/5.8/responses), you can return json responses like the below:
public function send_otp_function(Request $request)
{
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return response()->json($response);
}
You should be sending the csrf token with your post:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
$.ajax({
type: "POST",
url: "/send_otp", //remove the host variable here
data: {
_token: {{ csrf_token() }}, //csrf token
name:phone_number
},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});

HTML :
<!DOCTYPE html>
<html>
<head>
<title>Ajax Dynamic Dependent Dropdown in Laravel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
.box{
width:600px;
margin:0 auto;
border:1px solid #ccc;
}
</style>
</head>
<body>
<div id="first_step">
<div class="col-md-8">
<input type="text" autofocus id="phone_number" class="form-control" placeholder="Enter Phone Number" id="phone_number" name="phone_number" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-4">
</div>
<div class="col-md-8 " id="otp_input">
<input type="text" autofocus id="user_otp" class="form-control" placeholder="Enter OTP" name="otp" id="result" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication1"> </div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication">
<input type="button" class="log-teal-btn small" id="send_otp_button" value="Verify Phone Number"/>
</div>
</div>
{{ csrf_field() }}
</body>
</html>
<script>
$(document).ready(function(){
$('#send_otp_button').on('click', function(e) {
var select = $('#phone_number').val();
alert(select);
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('dynamicdependent.fetch') }}",
method:"POST",
data:{select:select, _token:_token},
success:function(result)
{
alert(result);
}
})
});
});
</script>
Web.php(Route File)
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/dynamic_dependent', 'DynamicDependent#index');
Route::post('dynamic_dependent/fetch', 'DynamicDependent#fetch')->name('dynamicdependent.fetch');
?>
//DynamicDepdendent.php (Controller)
<?php
//DynamicDepdendent.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class DynamicDependent extends Controller
{
function fetch(Request $request)
{
$response = $request->get('select');
echo $response;
}
}
?>

Related

What's the problem with my Wordpress ajax request

I want to add have a form in my Wordpress dashboard that work with ajax but my request response is 400 Bad request
add_action('admin_footer', 'vitrin_admin_ajax');
function vitrin_admin_ajax() {
?>
<script>
(function($) {
$('.vitrin-private-message-form').submit(function(event) {
event.preventDefault();
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: {
action: 'submit_vitrin_pm',
ppmcontent: jQuery('#pmcontent').val(),
ppmusers: jQuery('#pmusers').val(),
},
success: function(data) {
// jQuery('#datafetch').html(data);
alert(data)
}
});
})
})(jQuery);
</script>
<?php
}
?>
I also add:
add_action('wp_ajax_submit_vitrin_pm', 'submit_vitrin_pm');
add_action('wp_ajax_nopriv_submit_vitrin_pm', 'submit_vitrin_pm');
and
function submit_vitrin_pm() {
echo 'ssss';
die();
}
I checked, your ajax response is working, you didn't share your html form, i added a form for check.
add_action('admin_footer', 'vitrin_admin_ajax');
function vitrin_admin_ajax() {
?>
<form action="#" method="POST" class="vitrin-private-message-form">
<div id="name-group" class="form-group">
<label for="name">Name</label>
<input
type="text"
class="form-control"
id="pmcontent"
name="name"
placeholder="Full Name"
/>
</div>
<div id="email-group" class="form-group">
<label for="email">Email</label>
<input
type="text"
class="form-control"
id="pmusers"
name="email"
placeholder="email#example.com"
/>
</div>
<button type="submit" class="btn btn-success">
Submit
</button>
</form>
<script>
(function($) {
$('.vitrin-private-message-form').submit(function(event) {
event.preventDefault();
console.log('working')
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: {
action: 'submit_vitrin_pm',
ppmcontent: jQuery('#pmcontent').val(),
ppmusers: jQuery('#pmusers').val(),
},
success: function(data) {
// jQuery('#datafetch').html(data);
alert(data)
}
});
})
})(jQuery);
</script>
<?php
}
add_action('wp_ajax_submit_vitrin_pm', 'submit_vitrin_pm');
add_action('wp_ajax_nopriv_submit_vitrin_pm', 'submit_vitrin_pm');
function submit_vitrin_pm() {
echo 'ssss';
die();
}

How to submit a form request using ajax without page refresh and return a message in laravel?

I'm trying to submit a form request and store data without page refresh or redirect. And send success message to
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
,I get white page after clicking submit button with the following response
{
"msg": "Setting created successfully"
}
The html Form:
<form method="POST" action="/mail/store" id="contactForm">
#csrf
<div style="display: flex;" class="name-email">
<div class="form-group col-sm-6 fl_wrap">
<input type="text" name="name" value="{{ old('name') }}" id="name"
class="form-control fl_input" placeholder="Name"
required>
</div>
<div class="form-group col-sm-6 fl_wrap">
<input type="text" name="email" value="{{ old('email') }}" id="email"
placeholder="Email"
class="form-control fl_input" required>
</div>
</div>
<div class="form-group col-sm-12 fl_wrap mt-2">
<textarea type="text" name="message" rows="7" value="{{ old('message') }}" id="message"
class="form-control fl_input" placeholder="message"
required></textarea>
</div>
<div class="form-group text-center mt-5">
<button type="submit" value="save" id="submit" class="btn btn-warning submit"
style="color: white;background: rgb(59, 199, 246); border-color: rgb(59, 199, 246); width: 140px;">
send
</button>
</div>
</form>
Js Code:
I think there's something wrong or missing with ajax code but I don't know where
<script src="/js/jquery.min.js"></script>
<script !src="" type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#contactForm').on('submit',function (e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
$.ajax({
type: "POST",
url: host+'/mail/store',
data: { name:name ,email:email,message:message},
success: function( msg ) {
$("body").append("<div>"+msg+"</div>");
}
});
$.post('contactForm', { name:name, email:email, message:message }, function () {
console.log(data);
$('#postRequestData').html(data);
});
});
});
store function in controller
public function store(Request $request)
{
$mail = new Mail();
$mail->name = $request->name;
$mail->mail = $request->email;
$mail->message = $request->message;
$mail->save();
$result = array(
'msg' => 'Setting created successfully' );
return Response::json($result);
}
Routes
Route::get('/mail','MailsController#create');
Route::post('/mail/store','MailsController#store');
Try this one:
$.post("{{ url('mail/store') }}", {
name, email, message, '_token': "{{ csrf_token() }}"
}, function(data) {
$('#postRequestData').html(data.message);
});

customize sweetalert2 outputting raw json

I want to display a sweetalert message if registration is successful or fail (I wrote the sweetalert code in a jquery file) and included it inside the registration view page (it is included in the master.blade.php which all pages extend) but instead of displaying the sweetalert error or success message, it keeps displaying parsed json format message.
These are the files created.
custom_file.js
$(document).ready(function () {
var form = $('#registration');
form.submit(function (e) {
e.preventDefault();
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
dataType: "json"
})
.done(function (response) {
if (response.success) {
swal({
title: "Hi " + response.name,
text: response.success,
timer: 5000,
showConfirmButton: false,
type: "success"
});
window.location.replace(response.url);
} else {
swal("Oops!", response.errors, 'error');
}
})
.fail(function () {
swal("Fail!", "Cannot register now!", 'error');
});
});
the registraion.blade.php file
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">AJAX Register</div>
<div class="panel-body">
<form class="form-horizontal" id="registration" method="POST" action="{{ url('users/register') }}" data-parsley-validate="">
{!! csrf_field() !!}
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="name" id="name" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" id="email" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password" id="password" required="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation" id="password_confirmation" data-parsley-equalto="#password" required="">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary ladda-button" data-style="expand-left" data-size="s" data-color="green">
<i class="fa fa-btn fa-user"></i> Register
</button>
<div class="btn btn-md btn-primary ladda-button" data-style="expand-left" data-size="s" data-color="blue"> <i class="fa fa-facebook"></i> Login with Facebook </div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
and this is the RegisterController.php script
public function postRegister(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|unique:users,email',
'name' => 'required|min:2',
'password' => 'required|alphaNum|min:6|same:password_confirmation',
]);
if ($validator->fails()) {
$message = ['errors' => $validator->messages()->all()];
$response = Response::json($message, 202);
} else {
// Create a new user
$user = new User([
'name' => $request->name,
'email' => $request->email,
'password' => $request->password,
'facebook_id' => $request->email
]);
$user->save();
Auth::login($user);
$message = ['success' => 'Thank you for joining us!', 'url' => '/', 'name' => $request->name];
$response = Response::json($message, 200);
}
return $response;
}
}
Here's some test code:
index.php
<!DOCTYPE html>
<html>
<head>
<title>SweetAlert2 test</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.css">
</head>
<body>
<form id="myForm" method="post" action="ajax.php">
<input type="text" name="uname">
<input type="submit" value="Submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.5/sweetalert2.min.js"></script>
<script>
$(document).ready(function () {
var form = $('#myForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
dataType: "json"
})
.done(function (response) {
if (response.data) {
swal({
title: "Message",
text: response.data,
timer: 5000,
showConfirmButton: false,
type: "success"
})
.then(function() {}, function() {
// redirect after alert has been displayed
window.location.replace("https://google.com");
});
} else {
swal("Oops!", "Registration error!", 'error');
}
})
.fail(function () {
swal("Fail!", "Network/Server error!", 'error');
});
});
});
</script>
</body>
</html>
ajax.php
<?php
$user = isset($_POST['uname']) ? $_POST['uname'] : "Anonymous";
$myJson = ["data" => "Hi " . $user . "! Thank you for joining us!"];
echo(json_encode($myJson));
This works fine! Compare it with your code to see if there's an error somewhere.

Ajax form submit without page refresh

I simply want to submit my form to the same page with ajax without page refresh. So my below code submits the form but $_POST values are not picked ... Am I submitting it properly. I don't get any error but I think my form is not submitting.
html form
<form action="" id="fixeddonation" name="fixeddonation" method="post">
<input type="hidden" class="donerProject" name="donerProject" value="test">
<input type="hidden" class="donersubProject" id="donersubProject" name="donersubProject" value="general">
<input type="hidden" class="donerLocations" id="donerLocations" name="donerLocations" value="general">
<input type="hidden" class="donationpagetype" name="donationpagetype" value="general">
<input type="hidden" class="projectadded" id="projectadded" name="projectadded" value="1">
<input type="hidden" value="302" id="pageid" name="pageid">
<div class="classsetrepet generalfixshow fullrow row fixed-page">
<div class="col-6 text-right">
<div class="prize">Fixed Amount £</div>
</div>
<div class="col-6">
<input type="text" id="oneoffamt" name="oneoffamt" class="oneoffamt validatenumber">
<span class="amt_error"></span>
</div>
</div>
<br>
<div class="row">
<div class="col-6"></div>
<div class="col-6">
<input type="submit" id="submit_gen_one" class="btn-block" value="submit" name="submit_gen_one">
</div>
</div>
</form>
Ajax code
jQuery('#fixeddonation').on('submit', function (e) {
e.preventDefault();
jQuery.ajax({
type: 'post',
url: 'wp-admin/admin-ajax.php',
data: jQuery('#fixeddonation').serialize(),
success: function (data) {
alert(data);
alert('form was submitted');
jQuery('#collapse2').addClass('in').removeAttr('aria-expanded').removeAttr('style'); jQuery('#collapse1').removeClass('in').removeAttr('aria-expanded').removeAttr('style');
}
});
return false;
});
Add a correct value to the action tag of your form and try this:
<script>
$(document).ready(function() {
var form = $('#fixeddonation');
form.submit(function(ev) {
ev.preventDefault();
var formData = form.serialize();
$.ajax({
method: 'POST',
url: form.attr('action'),
data: formData
}) .done(function(data) {
alert(data);
});
});
}); // end .ready()
</script>
Don't need return false as you already called preventDefault() first thing
First create Template
<?php
/* Template Name: Test */
get_header();
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<p class="register-message" style="display:none"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must Be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register" >
</fieldset>
</form>
<script type="text/javascript">
jQuery('#test').on('click',function(e){
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") { jQuery('#email-error').show(); return false; }
else { jQuery('#email-error').hide(); }
jQuery.ajax({
type:"POST",
url:"<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test",
firstname : firstname,
email : email
},
success: function(results){
console.log(results);
jQuery('.register-message').text(results).show();
},
error: function(results) {
}
});
});
</script>
</main><!-- #main -->
</div><!-- #primary -->
after that create a function (function.php in wordpress)
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test() {
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='".$email."' ");
$res = $wpdb->get_results($q);
if(count($res)>0)
{
echo "Email Allready Register ";
}
else
{
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix.'test'; // if use wordpress
$user_id= $wpdb->insert( $tablename,$user_data );
echo 'we have Created an account for you';
die;
}
}

Laravel 5.2 : How to post and delete data Using Ajax?

I want to post some data using Ajax and I also want to delete some data using Ajax.
But the problem is while inputting the data, data posted in database. But My UI faces some problem, after saving the data, my save Button always clicked. But as I'm using Ajax, it shouldn't load or previous data should automatically vanish.
Same as for deleting also, while deleting data get deleted, but it's redirecting to another page?
How do I solve the problem?
Here is my UserController code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Http\Response;
use App\User;
use App\Post;
use Illuminate\Support\Facades\Storage;
class UserController extends Controller {
public function postSignUp(Request $request) {
$this->validate($request, [
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'password' => 'required|min:4'
]);
$user = new User();
$user->name = $request['name'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->save();
if ($request->ajax()) {
return response()->json();
}
}
public function delete(Request $request, $id) {
$user = User::find($id);
$user->delete($request->all());
}
}
?>
Here is my Post data View page:
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity = "sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin = "anonymous">
</head>
<body>
<script src = "https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div class="container">
<h2>Register Form</h2>
<div class="row col-lg-5">
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="Email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" onclick="send(event)" class="btn btn-default" >Submit</button>
</div>
</div>
<script type="text/javascript">
function send(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "{{route('signup')}}",
data: {name: $("#name").val(),
email: $("#email").val(),
password: $("#password").val(),
_token: '{!! csrf_token() !!}'
}
});
}
</script>
</body>
</html>
Here is my delete data view page:
<html>
<head>
<title> User Details </title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<div class="container">
<h3> User Details </h3>
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>User Name</td>
<td>User Email</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
#foreach($user as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->name }}</td>
<td>{{$row->email}}</td>
<td>
Edit
<div id="deleteTheProduct">
{!! Form::open([
'method' => 'POST',
'action' => ['UserController#delete',$row->id],
'style'=>'display:inline'
]) !!}
{!! Form::hidden('id',$row->id)!!}
{!! Form::submit('Delete',['class'=>'btn btn-danger deleteUser','id' => 'btnDeleteUser', 'data-id' => $row->id]) !!}
{!!Form::close()!!}
</div>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$('.deleteUser').on('click', function (e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url(' / delete') }}'
+ '/' + dataId,
method: 'POST',
data: inputData,
success: function (data) {
console.log(data);
}
});
});
</script>
</body>
</html>
to prevent redirect problem just make .delete button as button not submit, I think this will fix your problem, if not please inform me,
to delete row please make following changes on your script code... first is yours code
$('.deleteUser').on('click', function(e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
$.ajaxSetup({
headers: {
' X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url('/delete') }}' + '/' + dataId,
method: 'POST',
data: inputData,
success : function(data){
console.log(data);
}
});
});
have some changes in above code
$('.deleteUser').on('click', function(e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
// added code is
$object=$(this);
$.ajaxSetup({
headers: {
' X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url('/delete') }}' + '/' + dataId,
method: 'POST',
data: inputData,
success : function(data){
console.log(data);
//if success status is successful and below code removes the parent row from the table
$($object).parents('tr').remove();
}
});
});
But as I'm using Ajax, it shouldn't load or previous data should automatically vanish
You will have to control that yourself, ajax is like a request to web server without reloading the page (or navigating) but the browser doesn't know what action to make after the ajax request. as you are using jQuery you can update your UI after Ajax request in success callback.
try for example returning the id of deleted object and in ajax success function.
success: function(data) {
jQuery('#'+data.id).remove();
}

Categories

Resources