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
Related
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
I'm trying to post data on my HTML code to CI with Ajax. But I got no response?
Here is my JS Code
$(document).ready(function(){
$("#simpan").click(function(){
nama_pelanggan = $("#nama_pelanggan").val();
telp = $("#telp").val();
jQuery.ajax({
type: "POST",
url: "http://192.168.100.100/booking_dev/booking/addBookingViaWeb/",
dataType: 'json',
data : {
"nama_pelanggan":nama_pelanggan,
"telp":telp,
},
success: function(res) {
if (res){
alert(msg);
}
}
});
});
});
And here is my form
<form>
Nama Pelanggan <br>
<input type="text" name="nama_pelanggan" id="nama_pelanggan"><br>
Telepon<br>
<input type="text" name="telp" id="telp"><br>
<input type="button" name="simpan" id="submit" value="Simpan">
</form>
and here is my contoller function code
public function addBookingViaWeb(){
$data = array(
'nama_pelanggan' => $this->input->post('nama_pelanggan'),
'telp'=>$this->input->post('telp')
);
echo json_encode($data);
}
Here is my post param
But I got no response
any idea?
add method in from if you use post then
<form method="post" action ="" >
Try using JQuery form serialize() to declare which data you want to post. It automatically put your form input into ajax data. Example :
first set ID to your form tag
<form id="form">
then
$.ajax({
type:'POST',
url : 'http://192.168.100.100/booking_dev/booking/addBookingViaWeb/',
data:$('#form').serialize(),
dataType:'JSON',
success:function(data){
console.log(data);
}
});
First problem I see is in your ajax submission code. Change
$("#simpan").click(function(){
to
$("#submit").click(function(event){
Notice that I added the event parameter. You now need to prevent the default submission behavior. On the first line of your click method add
event.preventDefault();
Now I'm assuming that your url endpoint http://192.168.100.100/booking_dev/booking/addBookingViaWeb/ can handle POST requests. Usually this is done with something like PHP or Ruby on Rails. If I was doing this in PHP I would write something like the following:
<?php
$arg1 = $_POST["nama_pelanggan"];
$arg2 = $_POST["telp"];
// do something with the arguments
$response = array("a" => $a, "b" => $b);
echo json_encode($response);
?>
I personally don't know anything about handling POST requests with js (as a backend) but what I've given you should get the data over there correctly.
I got solution for my problem from my friend xD
just add header("Access-Control-Allow-Origin: *"); on controller function
Thank you for helping answer my problem.
I have an element for ex. <div>. and in that I have fetched dynamic contents from database, I am already performing some database operation using AJAX and I am able to load some part of my page from other php file, but on the same page I want my other div to be repopulate its data from database.
This is my manage_your_listing.php
<div class="col-sm-12 pd">
<ul class="nav nav-tabs notificationtabs">
<li class="active">Live On Site</li>
<li>Pending Review</li>
<li>Pause</li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane fade active in" id="live_on_site" >
<?php
include'manage_order/live_on_site.php';
?>
</div><!-- End tab1-->
<div class="tab-pane fade" id="pause" >
<?php
include'manage_order/pause_order.php';
?>
</div><!-- End tab2 -->
</div><!-- End tab-content -->
this is my live_on_site.php's AJAX function
function ConfirmPause(prod_id){
$.ajax({
type: "get",
url: "seller/manage_order/live_on_site_pause.php?prod_id="+prod_id.id,
cache: false,
dataType: "html",
asyc: false,
success: function (data) {
$("div#live_prod").html(data);
}
});
}
so finally my live_on_site.php's live_prod div is being repopulated with the contents of live_on_site_pause.php
but what I want is, there is div in pause_order.php which is accessible in every php file specified here, and that div is being populated with some database content by using select statement, and I want it just to refresh, Is it possible? or do I need to create a new php file and call it using ajax?
I solved it by using nested ajax function.
I wanted to refresh one div after processing of some database update using ajax, But later I found that there is no way ajax can refresh div, it just copies some data from source position and paste it into specified position. So while success of previous ajax function I typed one more ajax function which worked for me.
function ConfirmPause(prod_id)
{
if (confirm("Pause Product?"))
{
$.ajax({
type: "get",
url: "seller/manage_order/live_on_site_pause.php?prod_id=" + prod_id.id,
cache: false,
dataType: "html",
asyc: false,
success: function (data) {
$("div#live_prod").html(data);
//nested ajax to change pause products tab real time the moment user pauses a product it will get removed from live tab and will be added to pause products tab
$.ajax({
type: "get",
url: "seller/manage_order/pause_order_resume.php",
cache: false,
dataType: "html",
asyc: false,
success: function (data) {
$("div#pause_prod").html(data);
}
});
}
});
}
}
you cant just refresh an element with ajax, you can either process something in ajax or in other file and replace it with old contents using ajax.
I am trying to post using AJAX because I don't want to use a submit button and reload the page everytime I click it.
I am using this code for ajax:
<script language="JavaScript"><!--
function postit()
{
var frm = $('#pmconfirm');
$.ajax({
type: "POST",
url: "bitcin",
data: frm.serialize(),
success: function(msg){
$("#main").hide();
$("#main").html(msg).show();
},
error: function(msg){
$("#main").html("<font color='#ff0000'>Ajax loading error, please try again.</font>").show();
}
});
}
setTimeout("postit()",2000);
//--></script>
Next, I am using this form:
<form action="" name="fcaptcha" method="post">
<input type="hidden" id="bitcoin" name="bitcoin">
<input type="hidden" id="pmconfirm" name="pmconfirm" src="http://www.mvixusa.com/newsletter/2010/11/newsletter-membership-confirmation/images/confirm-button.png" alt="Submit Form" onclick=\"document.getElementById("fcaptcha").submit()\"/>
</form>
<div id="main">
</div>
This works it posts but I doesn't give me results ?
if (isset($_POST['bitcoin']))
{
// My code here works, because it works when i dont use ajax
// And I have some things to check like if it wasnt what i wanted
// it returns some message which is shown with php.
}
<div id="messaget">
<?php
if($failed == 1) echo $messages;
?>
</div>
This is the part where the messages should be displayed, I tried using a tag #messaget to display the HTML after post but it didn't work, I tried displaying the entire page in this page it still didn't work.
And the url: "bitcin", is entirely ok, i used htaccess.
Can somebody spot where the problem is ?
Add an id to the form :
<form id="pmform" action="" name="fcaptcha" method="post">
And change Js to:
var frm = $('#pmform');
When performing:
............
data: frm.serialize(), //this will take the form and make an array based on the names of the form elements thus having them accessible in the PHP script
..........
I currently have a dynamic number of these being generated with a foreach() loop:
<div id="<?php echo $data['id']; ?>" data-role="collapsible" data-theme="a">
<h1 style="white-space: normal"><?php echo $data['text']; ?></h1>
<center>
<p><?php echo $data['text']; ?></p>
</center>
</div>
What I want, is for an AJAX POST request to be dispatched to another resource with the parameters of $data['id'] when the collapsible <div> opens.
I tried using a .click method, but I was not able to make it work for a dynamic list of <div>s. I feel a method that waited until the animation was done (as to ensure the page is still responsive) is the best way.
Can someone please help with this?
For dynamically generated content, I would suggest you use the .on() method. Take for example the following code:
$('#container').on('click', 'div', function() {
var id = $(this).attr('id');
$(this).animate({
your animation
}, 5000, function() {
$.ajax({
url: "another_resource.php",
type: "POST",
data: {
id: id
}, //data to be sent
dataType: "text", //return data type
async: false,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
}
The first parameter is the event(s)(can be space delimited for multiple events), while the second can either be the targeted element, or the function to execute. The last, in this case, is of course the function to execute.
The ajax will execute when the animation is complete, as requested.