Refresh a div after an AJAX request - javascript

I have a notifications panel and when the user clicks the cross to delete a notification I want just the DIV to refresh so it will throw away the old notification and refresh with the current ones, here i what I have now, it refreshes but all the data disappears and shows nothing but the box.
Screenshots
Before:
After:
HTML
<div id="messageboxcon">
#php
$usersid2 = Auth::id();
$usersalert2 = DB::table('notifications')->where('userid', $usersid2)->orderBy('created_at', 'desc')->get();
#endphp
<h3 style="color: gray;
font-weight: 100;
float: left;
margin-left: 15px;
margin-top -50px;">
Notifications : {{count($usersalert2)}}
</h3>
<div class="notificationcontainer">
#php
$usersid = Auth::id();
$usersalert = DB::table('notifications')->where('userid', $usersid)->orderBy('created_at', 'desc')->get();
#endphp
#if(count($usersalert) > 0)
#foreach ($usersalert as $item)
<div class="notification">
<h2 class="notiftitle">{{$item->type}}</h2>
<h3>{{$item->message}}</h3>
<a class="removenotif" data-id="{{$item->id}}" data-token="{{ csrf_token() }}"><i class="crossnotif fas fa-times fa-sm"></i></a>
</div>
#endforeach
#endif
</div>
</div>
JavaScript
$(".removenotif").click(function(ev){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax({
url: 'deletenotif/'+id,
type: 'DELETE',
dataType: 'JSON',
data: {
"id":id,
"_method": 'DELETE',
"_token": token,
},
success: function (data) {
console.log("it worked");
$('#messageboxcon').load(document.URL + ' #messageboxcon');
},
error: function (data) {
alert(data);
}
});

In the success callback, I would make use of the jQuery .parents() function.
In the context of the click event handler function, $(this) represents the "close notification element".
You need to remove the <div> with the notification class.
So I would do something like $(this).parents('.notification').remove().
I'm not sure what you're trying to achieve with this:
$('#messageboxcon').load(document.URL + ' #messageboxcon');
It will load the entire webpage in the messageboxcon <div> which is not what you want to achieve.
If you want to refresh the content, perform an AJAX call getting just the HTML for the notifications.
Just create a page (notifications.php) on server side that does just what you do initially:
#php
$usersid = Auth::id();
$usersalert = DB::table('notifications')->where('userid', $usersid)->orderBy('created_at', 'desc')->get();
#endphp
#if(count($usersalert) > 0)
#foreach ($usersalert as $item)
<div class="notification">
<h2 class="notiftitle">{{$item->type}}</h2>
<h3>{{$item->message}}</h3>
<a class="removenotif" data-id="{{$item->id}}" data-token="{{ csrf_token() }}"><i class="crossnotif fas fa-times fa-sm"></i></a>
</div>
#endforeach
#endif
Then in the success callback you remove the notification the user wants to delete for immediate feedback. And then make an AJAX call to refresh the notifications with something like that:
$('#notificationcontainer').load('notifications.php')

in success do something like $("#item-"+id).remove();

change this line
$('#messageboxcon').load(document.URL + ' #messageboxcon');
to this :
$('#messageboxcon').load(document.URL + '#messageboxcon');
in your success code.you have a extra space

You need to create a new javascript function, in which, you'll get the data from notification table. The function should look like this:
function updateContent(){
$.ajax({
url: 'n.php',
type: 'GET',
success: function (data) {
console.log("get recent data in HTML");
$('.notificationcontainer').html(data);
},
error: function (data) {
console.log(data);
}
});
}
And, code which is in n.php file
#php
$usersid = Auth::id();
$usersalert = DB::table('notifications')->where('userid', $usersid)->orderBy('created_at', 'desc')->get();
#endphp
#if(count($usersalert) > 0)
#foreach ($usersalert as $item)
<div class="notification">
<h2 class="notiftitle">{{$item->type}}</h2>
<h3>{{$item->message}}</h3>
<a class="removenotif" data-id="{{$item->id}}" data-token="{{ csrf_token() }}"><i class="crossnotif fas fa-times fa-sm"></i></a>
</div>
#endforeach
#endif
Now, just call that javascript function in removenotif click success method like this -
updateContent();

Create a duplicate of the notification container in a different file, let's say not.php
Then Create a new Ajax with the URL as not.php
Then use the id of the notification container to get the data of the jquery. So it will be like a refresh.
Then create a button that will execute the new jQuery you have created on a click event.
So what you'll do is that, after your previous jQuery has deleted the notification, you'll make it cause a click even on the fresh button so that you wouldn't have to click it manually.
This will replace the old notification container with the new one.
Remember to link the jQuery file add aslo may want to add the jQuery code to the new file, that is not.php otherwise it will work only once since it won't get any ajax to use if you don't put it there as well

Related

Refresh a div after successful AJAX operation in Laravel

I want to refresh/update my div when a successful ajax operation occurs. But I've no exact idea how to do that.
Clearly, I can say that my div should show the inserted data after the successful insertion operation done by ajax. And it obviously should be done without loading page.
I'm attaching what I've tried so far.
Route(web.php)
Route::resource('posts', 'PostsController', ['only' => ['store']]);
Cotroller(PostsController)
public function store(Request $request)
{
$this->validate($request, array(
'post' => 'required|min:20',
));
$post=new Post();
$post->userId=Auth::user()->id;
$post->post=$request->post;
$post->save();
return redirect()->route('home');
}
Controller(PagesController)
public function getHome(){
$posts=Post::orderBy('id', 'DESC')->get();
return view('pages.home')->withPosts($posts);
}
JS
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response){
$('.all-posts-body').load(); //No idea how to do this
},
})
Views(home.blade)
<div class="all-posts-body">
#if($posts->isEmpty())
<div class="alert alert-warning">No post yet!</div>
#else
#foreach($posts as $post)
<div class="card">
<div class="card-body">
{!! nl2br($post->post) !!}
</div>
</div>
<br>
#endforeach
#endif
</div>
This .all-posts-body should be refreshed without reloading page whenever I insert a post by ajax.
I'm attaching a sample image for better explanation
You can send the HTML content that you want from the backend and replace the success with
success: function(response){
$('.all-posts-body').html(response);
},
you can make something like this (i prefer to use id not class)
$('#all-posts-body').load(location.href+(' #all-posts-body'));
and please add space before your id

How do I toggle content between tabs through ajax/php?

I have divided my content in two tabs and switching between two tabs with javascript.
<div class='tab-container'>
<div class='tab-1'>
<?php
$sql="SELECT * FROM posts WHERE status='tab1'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
<div class='tab-2'>
<?php
$sql="SELECT * FROM posts WHERE status='tab2'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
</div>
Php code divides content between tabs through WHERE clause select * from posts where status='tab1'; so to remove post from one tab ajax request given below triggers php code which updates status of content from tab1 to tab2.
<script type="text/javascript">
$(function() {
$(".restore").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Restore?"))
{
$.ajax({
type: "GET",
url: "restore.php",
data: info,
success: function(){
}
});
$(this).parents(".db").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
So that post is removed from tab1. Idea here is to move post from one tab to another through ajax. javascript works good on removing post from one tab however for making that post appear in another tab I have to reload page as I haven't used ajax for that. So problem is I don't get how to add that post dynamically to another tab through ajax without refreshing page.
To get content from ajax call, you have to echo it in server side.
May be something like this
echo "hi, this is new content";
Now in ajax success
success: function(data){
alert(data); this will alert what was echoed in php(hi, this is new content)
}
If you want to add the content to some div in view,
$("class or id for the div").html(data);
In restore.php, you should get the selected post and then then update the status of that post to tab2. And append that result in main php page. You can append the same via restore.php.
Try this
HTML
<div class="tabs" id="d-tab1"></div>
<div class="tabs" id="d-tab2"></div>
<a href="#" class="restore" id="tab1">
<a href="#" class="restore" id="tab2">
JS
$('.restore').click(function(e){
e.preventDefault();
var $tab = $(this);
$.post('restore.php',{id: $tab.attr('id')},function(html){
$('.tabs').hide();
$('#d-'+$tab.attr('id')).html(html).show();
})
})
Or use Jquery tabs https://jqueryui.com/tabs/
Agree with #Niranjan N Raju. But want to add some addition.
Use console.log(data) instead alert(data) as last don't shows object info.

securely passing sensitive data from PHP to javascript

My scenario looks like this, I'm showing database paginated grid on the screen.
I want add a button to download CSV spreadsheet .
so I coded something like this:
$(function(){
var file_complete = false;
var final_sql = $('.initiate_download').val();
var orderby = $('#search_submit').data('orderby');
var $posturl = $url + "index.php/Spawner/launch_spawner";
$('#downloadModal').modal('hide');
$('.initiate_download').on("click", function(e) {
e.preventDefault();
$('#pleaseWait').html($html);
setTimeout(function() {
$.ajax({ // initiate download
url: $posturl,
type: "POST",
data: {
final_sql: final_sql,
orderby: orderby,
report: $report
},
success: function(data) {
var download_id = data;
// console.log(download_id);
check_download_status(download_id);
}
})
}, 2000);
})
});
<div class="row top-buffer">
<button id="search_submit" class="btn btn-primary initiate_download" type="submit" value="<?php echo $sql; ?>" data-orderby="<?php echo $orderby;?>" name="final_sql_lic" >Download List</button>
<span id="pleaseWait"> </span>
</div>
it works fine, but the problem is that you can view SQL with view page option, is there a way around it ?
What most people do is they don't embed the SQL on page, but instead expose URLs that handle the SQL stuff behind the scenes.
In your example, you might create a page like this:
http://website.com/api/csv?select=col1,col2,col3&orderBy=someColumn&where=someCondition
Then your php will take those parameters and generate the sql based off of those and run the query. Make sure you securely handle the input to avoid SQL injection (See http://bobby-tables.com/php.html).
The problem with your current scenario is that someone viewing your source will plainly see that you're passing SQL directly to your server, meaning they can generate their own SQL like: DROP TABLE table1, table2; or worse.

Jquery or ajax to php function without reloading page

I have a php page that i call a calendar class function to show the calendar. which is just
$calendar->show(true);
It has another function that lets you call it by
$calendar->show('July 2015')
So what i am trying to do is create a header on top that shows next and previous and then have it be a link, but i am trying to figure out how i can click on the previous link that when i click on it, just reruns the function with the date specified instead of reloading the whole page again and using url parameters. I've been looking into ajax and jquery, it seems possible, but it only shows how to post to a php page. I can't find a way to just rerun a function if thats even possible.
you need code like this:
HTML:
<div id='next' class='year'></div>
<div id='next' class='month'></div>
<div id='prev' class='day'></div>
<div id='date'></div>
<div id='next' class='day'></div>
<div id='next' class='month'></div>
<div id='next' class='year'></div>
jQuery:
$('.day, .month, .year').click(function() {
var a = $(this).attr('id'); // find prev or next clicked
var b = $(this).attr('class'); // find day or month or year clicked
$.ajax({
type: 'post',
url: //your php url,
data: {act: a, which: b, /* your other data */},
cache: false,
success: function(c) {
$('#date').html(c);
}
}):
});
and PHP:
<?php
include //your class
echo $calendar->show('$_POST['data']')
?>

when loading a page content through ajax post and codeigniter load functions, some jquery functions are in the head section cannot be called

I know My question Title is not perfectly describe my question extremely sorry about that. I don't know how to tell this as a summery. anyway this is my question.
I am making a admin panel to change some of the content in my web page. this scenario is for change slideshow images.
ok then after someone logged into my page I am loading three pages. like this.
$this->load->view('admin/header');
$this->load->view('admin/menu');
$this->load->view('admin/table_and_editor_holder');
all the page contents I have mentioned below. so basic path is like this. once someone logged he can click the button [slide manage] to load the images and details of already inserted slides. these are getting from a database. so once he clicked the menu button. this jquery function is executing.
$('.menu-item > a').on('click', function() {...})
this function simply getting a html page. filled with previous slide details. this is the controller function handle the menu request.
function slider_edit_delete() {
$sdata['slide_imgs'] = $this->admin_basic_curd->get_all_items('sider_images');
$slide_manager = $this->load->view('admin/slider_manager', $sdata, TRUE);
echo $slide_manager;
}
so previous jquery function is then appending this page content to a div like this.
$('#table_container').html(data);
so inside this page content I have a buttons call edit for each slide already inserted. so by clicking on of this button I can edit that slide image or some test content of it. that button is like this.
<a class="onclick_post_by_a" href="<?php echo base_url() . 'adm_edit_this_slide/' . $sl->id; ?>">
<button class="btn btn-info"> Edit </button>
</a>
so by clicking this button must execute this function in the header section and this function must add a html form (in a separate page) to the #editor-form-container div as previously
$('.onclick_post_by_a').on('click', function() {...})
but the problem is once I click the edit button it couldn't find this function. so it is opening the content as a separate page
How can I make this to work? Thank you
the header page contains all the css and js file links. and some jquery functions. like this.
<script>
$(document).ready(function() {
$('.menu-item > a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#table_container').html(data);
});
return false;
});
$('#editor-form-container').css({
display: "none"
});
function posting_url(url, pdata) {
return $.ajax({
url: url,
data: pdata
});
}
$('.onclick_post_by_a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#editor-form-container').css({
display: "block"
});
$('#editor-form-container').html(data);
});
return false;
});
$('.post_with_image').on('submit', (function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("success");
console.log(data);
},
error: function(data) {
console.log("error");
console.log(data);
}
});
}));
});
</script>
</head>
then I have load menu page. it is like this.
<div class="admin-navi">
<div class="menu-item">
Home
</div>
<div class="menu-item">
Side Manage
</div>
</div>
<div class="clearfix"></div>
table_and_editor_holder.php page. it is like this.
<div class="col-lg-12">
<div class="col-lg-2"></div>
<div id="table_container" class="col-lg-8">
</div>
</div>
<div id="editor-form-container" class="col-lg-6">
</div>
Dynamically created element does not respond to direct call to events like below -
$('.onclick_post_by_a').on('click', function() {...})
So you have to write like this
$(document).on('click', '.onclick_post_by_a', function() {...})
Just try it out.

Categories