In my laravel project, i want to refresh my page after an ajax success but my page would refresh after the success. I tried to refresh with laravel redirect in the controller and it didn't work, i have also tried to refresh in the ajax and nothing happened? How do i do this right? How do i do this right?
Controller
if(request()->ajax()) {
//do something
return ['success' => 'successfully done'];
return redirect('admin/all')->with('status','Successfully done!');
JS
<script type="text/javascript">
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.approve_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
location="/admin/all";
}
else if (data['error'])
{
alert(data['error']);
}
else
{
//alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
window.location.href="/your/url" ;
$.each(allVals, function( index, value )
{
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
location="/admin/all";
}
else if (data['error']) {
alert(data['error']);
}
else
{
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
</script>
You need to use javascript to refresh the page. You can use location.reload()
if ( data['success'] )
{
alert(data['success']);
location.reload();
}
For those of you still looking for a Solution, This is how you can resolve this issue.
First of all, just return a simple message in your controller.
class SettingsController extends Controller
{
public function __construct()
{
}
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
return 'Record successfully deleted';
}
}
Secondly, Add this code in your javascript file to refresh the page.
setTimeout(function () { document.location.reload(true); }, 5000);
<script type="text/javascript">
function deluser(id)
{
event.preventDefault();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url:"{{ route('settings.destroy','')}}/"+parseInt(id),
method: 'delete',
data:{
id: id,
},
success: function(data)
{
$('#validation-message').append('<div class="alert dark alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span> </button><b>'+data+'</b></div>');
setTimeout(function () { document.location.reload(true); }, 5000);
},
error: function(xhr)
{
$('#validation-message').html('');
$.each(xhr.responseJSON.errors, function(key,value) {
$('#validation-message').append('<div class="alert dark alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span> </button><b>'+value+'</b></div>');
});
}
});
}
</script>
Finally in your HTML.
<!DOCTYPE html>
<html>
<body>
<div class="col-xl-12 form-group" id="validation-message"></div>
<button onclick="deluser('ID_NUMBER_GOES_HERE')">Click me</button>
</body>
</html>
You can try something like this
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
}
Related
when i click delete all selected its saying undefined variable however when i check the database the post gets deleted and when i refresh the page the post gets removed from the page. I don't understand why its bringing an error when its working.
blade
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-confirmation/1.0.5/bootstrap-confirmation.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
Delete All Selected
post Name
post Details
Action
#foreach($posts as $key => $post)
id}}">
id}}">
{{ ++$key }}
{{ $post->about }}
{{ $post->image }}
id}}" class="btn btn-danger btn-sm"
data-tr="tr_{{$post->id}}"
data-toggle="confirmation"
data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
data-btn-ok-class="btn btn-sm btn-danger"
data-btn-cancel-label="Cancel"
data-btn-cancel-icon="fa fa-chevron-circle-left"
data-btn-cancel-class="btn btn-sm btn-default"
data-title="Are you sure you want to delete ?"
data-placement="left" data-singleton="true">
Delete
#endforeach
<script type="text/javascript">
$(document).ready(function () {
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
} else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success']) {
$(".sub_chk:checked").each(function() {
$(this).parents("tr").remove();
});
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success']) {
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
</script>
</html>
```
controller
public function showem(Post $post)
{
$posts = Post::get();
return view('users.registered', compact('posts'));
}
public function deleteAll(Request $request)
{
$ids = $request->ids;
$deleted = Post::whereIn('id',explode(",",$ids))->delete();
return view('users.registered');
}
After review your full question again and again, I found that you have got this error on detele method.
You need to send posts variable also on delete method :
public function showem(Post $post)
{
$posts = Post::get();
return view('users.registered', compact('posts'));
}
public function deleteAll(Request $request)
{
$ids = $request->ids;
$deleted = Post::whereIn('id',explode(",",$ids))->delete();
$posts = Post::get();
return view('users.registered', compact('posts')); // here send the posts variable
}
I'm trying to use AJAX to submit my form. It validates well but fails to redirect after successfully processing. I need it to redirect when response == "ok"
$('document').ready(function() {
function submitForm() {
var data = $("#login-form").serialize();
$.ajax({
type: 'POST',
url: 'loginprocess.php',
data: data,
beforeSend: function() {
$("#loginerror").fadeOut();
$("#login_button").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success: function(response) {
if (response == "ok") {
$("#login_button").html('<img src="ajax-loader.gif" /> Signing In ...');
window.location = 'welcome.php';
} else {
$("#loginerror").fadeIn(1000, function() {
$("#loginerror").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> ' + response + ' !</div>');
$("#login_button").html('<span class="glyphicon glyphicon-log-in"></span> Sign In');
});
}
}
});
return false;
}
});
It was fixed by changing the response to data, using console.log(data) i realised that there was an extra space before the ok, so i used trim as advised. below is the new code that worked.
Thanks to y'all for saving the day-night.
I want to delete records from a MySQL database table using AJAX. I have done it with PHP and work fine. But I've not been able to get it through with AJAX.
AJAX
$(document).ready(function() {
$(".confirm").click(function() {
var bid = $(this).closest("div.box2").find('input[name="dbid"]').val();
var dataString = 'id=' + bid;
$.ajax({
type: "POST",
url: "<?php echo site_url('user/delete_article')?>",
data: dataString,
cache: false,
success: function() {
$.alert('Confirmed!');
}
});
});
});
PHP
public function delete_article($id){
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->db->where('bid', $id);
$data['countEarticle'] = $this->db->count_all_results('blog');
if($data['countEarticle'] >= 1){
$this->db->where('bid',$id);
$this->db->delete('blog');
}
if($data['countEarticle'] <= 0){
}
}
HTML
<div class="box-footer box-comments box2" style="display: block;">
<input type="hidden" name="dbid" value="<?php echo $draftfull['bid']?>">
<p>
<btn class="btn btn-azure btn-sm confirm"><i class="fa fa-trash-o"></i>Delete Article</btn>
</p>
</div>
I need your help. What am I doing wrong?
try this code:-
public function delete_article(){
$id=$this->input->post('bid');
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->db->where('bid', $id);
$data['countEarticle'] = $this->db->count_all_results('blog');
if($data['countEarticle'] >= 1){
$this->db->where('bid',$id);
$this->db->delete('blog');
}
if($data['countEarticle'] <= 0){
}
}
try this:
<span class="fa fa-ban"></span>
//ajax
function delete(id) {
swal({
title: "Are you sure to delete?",
text: "Deleting will remove row from listing!",
type: "error",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
}, function (isConfirm) {
if (isConfirm) {
$.post(
base_url + "user/delete_article",
{bid: id},
function (data) {
if (data === "1") {
location.reload();
} else if (data === "0") {
swal("", "Error to deleting data.", "warning");
} else {
swal("", data[0], "error");
}
});
}
});
}
//Controller
function delete_article($id){
if ( $this->model_name->deleteDataById($this->input->post('bid') ) {
die('1');
}
die('0');
}
I have a chat application which works absolutely fine for sending and receiving texts only but I want to send images/videos/ files through it.
This is the main home page which display the chats.
<script>
$ = jQuery;
var currentID = null;
var chatTimer = null;
var oldhtml="";
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$("#chatbox").show();
$('#messages').html(data);
$("div.area").show();
if(oldhtml!==data) {
$('#messages').scrollTop($('#messages')[0].scrollHeight);
}
oldhtml=data;
}
});
}
$(document).ready(function() {
fetch_data();
setInterval(function() {
fetch_chat();
}, 500);
$(document).on('click', '.first_name', function() {
currentID = $(this).data("id1");
fetch_chat();
});
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
});
});
</script>
and below is the fetch_chat.php which fetches the chat from databases.
<?php
require("config.php");
$user_to = $_POST['id'];
$res1=$db->query("select * from chats where user_from='$_SESSION[id]' AND
user_to='$user_to' OR user_to='$_SESSION[id]' AND user_from='$user_to' order
by id");
if($res1->num_rows){
while($row=$res1->fetch_object()){
if($row->user_from === $_SESSION["id"] ) {
echo "<div class='chat self'>
<div class='user-photo'><img src='img/user1.jpg'></div>
<p class='chat-message'> $row->msg</p>
</div>";
} else {
echo "<div class='chat friend'>
<div class='user-photo'><img src='img/user2.jpg'></div>
<p class='chat-message'>$row->msg</p>
</div>";
}
}
} else
echo "No msgs <br />";
?>
Now I want to save the info of the uploaded file in the database and the files into a folder/directory. The sender and receiver should be able to send and view the files respectively.
Is there a way to update a database using 1 click?
i.e
echo "<a href='".$wpdb->query(" UPDATE partners SET active='no' WHERE partner_id='$active_partner->partner_id' ")."'>Disable</a>";
You need to react on a click with an ajax function.
i.e.
$('#your_button_id').bind('click', function () {
function_with_ajax();
})
function function_with_ajax() {
$.ajax({
here you could call the update.php script and transmit dynamic data
});
}
<button id="btn-save" type="button">
save
</button>
<script type="text/javascript">
jQuery(document.ready(function ($) {
$("#btn-save").click(
function () {
$.ajax({
type:"POST",
url:"/wp-admin/wp-ajax.php",
data:{
action:"save_data",
data:"data-update",
condition:"data-condition"
},
success:function (response) {
console.log(response);
},
error:function (error) {
console.log(error);
}
})
}
);
}))
</script>
and add to file function:
add_action("wp_ajax_save_data",function ()
{
global $wpdb;
$wpdb->update("your-table",
["your_field" => $_POST['data']]
,["condition-filed"=>$_POST['condition']]);
});