ID received from post - send via ajax - ajax

I would like to read the post id from html and send it via AJAX to the controller. How can I get the post ID ($post->id) and transfer it via AJAX? Or is there a better solution to save the post seen by the user?
#foreach ($posts as $post)
<div id="post_container_{{$post->id}}" class="row waypoint">
</div>
#endforeach
This is my AJAX code:
$('.waypoint').waypoint(function() {
$.ajax({
url: '/posts/view',
type: "post",
data:
success: function(request){
console.log(request);
},
error: function(response){
console.log(response);
},
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}, {
offset: '100%'
});

Get the id from the focused waypoint.
let waypoint_id = this.getAttribute('id'); // something like 'post_container_1'
Get only the string after the _
let post_id = waypoint_id.split("_").pop(); // something like '1'
in ajax() function
data: {
post_id: post_id
}

You could add a data-id attribute like so:
#foreach ($posts as $post)
<div id="post_container_{{$post->id}}" data-id="{{$post->id}}" class="row waypoint">
</div>
#endforeach
And then access it using the attr()
$('.waypoint').waypoint(function() {
let post_id = $(this).attr('data-id'); //this specifies the particular post row in focus.
$.ajax({
url: '/posts/view',
type: "post",
data: {post_id: post_id}
//and so on.
});
}, {
offset: '100%'
});

Related

how send id in ajax for laravel

i want to run my ajax after click on one of the options in select tag. and send id of option to ajax url.
please help me . these are my codes.
#foreach($emails as $mail)
<option id="{{$mail->id}}">{{$mail->email}}</option>
#endforeach
</select>
my ajax
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.select option').on('click',function () {
var id=$('.select option:selected').attr("id");
$.ajax({
url:'/mailactive',
type:'get',
dataType:'json',
data:{id:id}
})
})
})
try to use this:
give to your select an id, for example id_select
use #id_select > option:selected in your jQuery selector instead of .select option:selected
then tell me if you still can't get the id
In Your Laravel Blade
<select id="email">
#foreach($emails as $mail)
<option id="{{ $mail->id }}"> {{ $mail->email }} </option>
#endforeach
</select>
If your Route is POST method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.post('{{ url('your_POST_route_url') }}', {
'_token': "{{ csrf_token() }}", id:id,
}, function (data) {
console.log(data); // Print your response into your console
});
});
If your Route is GET method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.get('{{ url('your_GET_route_url') }}', {
id:id,
}, function (data) {
console.log(data); // Print your response to your console
});
});
You should have return data from your GET or POST method.

post id with url using ajax

im write ajax code in post url and my userid bt not respond that code
<script>
function InviteLink( id, url ){
console.log(id);
$.ajax({
url: https://abc.hrm.com/auth/login
data: { 'id' : id },
success: function(data) {
}
});
}
</script>
<button onclick="InviteLink('<?php echo $employees->fldUserID; ?>','<?php echo base_url($employee_url); ?>');" style="background-color:#00C292; color:white; font-weight: bold; margin:5px 0px;" title="Invite New Employee" data-toggle="modal" data-target="#invitelink" type="button" class="btn btn-teal btn-circle"><i class="notika-icon notika-mail"></i></button>
**front UI in button i write onclick function and get id and url.... but there are not post in my url please help me solve my problem **
You Have to add method type = "POST" in ajax Like Below
<script>
function InviteLink( id, url ){
console.log(id);
$.ajax({
type: "POST",
url: https://abc.hrm.com/auth/login,
data: { 'id' : id },
success: function(data) {
}
});
}
</script>

Laravel Ajax delete record with button

I do not understand why it does not work:
Route
Route::delete('/dashboard/booking/deletebooking/{id}','ResourceController#deletebooking')->name('works.deletebooking');
ResourceController
public function deletebooking($id){
$booking = Booking::where('id','=',$id)->get();
$booking->delete();
return response()->json(['success' => true],200);
}
Table
<tr id="{{$booking->id}}">
<td class="roomId">{{$booking->room_id}}</td>
<td class="roomName">{{$booking->name}}</td>
<td class="roomLocation">{{$booking->sede}}</td>
<td class="start">{{$booking->start_date}}</td>
<td class="end">{{$booking->end_date}}</td>
<td>
<input type="hidden" name="_method" value="delete" />
<button class="btn btn-danger btn-xs" id="destroy" data-id="{{$booking->id}}" data-token="{{ csrf_token() }}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
Request Ajax
$(".btn").click(function(){
var id = $(this).data('id');
// var $tr = $(this).closest('tr');
$.ajax({
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
I have this error:
Request URL: http://pickbooking.local/dashboard/booking/deletebooking/1
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: 192.168.10.10:80
The issue is in the method used for the ajax call post
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
the data will be sent in the body of the request, and in a DELETE request, there is no body. so laravel wont see the _method, or the _token. Either you send them in a GET request and let the _method do it's job (it will be in the url, not in the body), Or use the DELETE method in the ajax call
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'DELETE',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
},
success: function ()
{
console.log("it Work");
}
});
Because I think you have an error something like
Method Illuminate\Database\Eloquent\Collection::delete does not exist.
Instead try something like this
$booking = Booking::where('id', '=', $id)->first();
$booking->delete();
so that $booking can have method delete()

Jquery .ajax() function not returning values from codeigniter controller

I have a site i'm working on and i'm trying to make an ajax request to a controller (codeigniter framework). I see in firebug that my controller is receiving my post value just fine but for some reason it is not sending back a response. I've set it up to be VERY simple without a database call at this point just for testing and its still not working. Any ideas?
Here is my form in my view:
<div class="purchaseState">
<input type="text" name="city" id="city" class="grayGrad"/>
</div>
<div>
<ul id="cityResults">
<!-- AJAX results here -->
</ul>
</div>
Here is my controller returning the value:
function citySearch() {
echo '<li>test</li>';
}
Here is my Jquery ajax
//New City Search
$('#city').keyup( function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
}).done(function( data ) {
$('ul#cityResults').append(data);
});
});
you should use ajax success callback:
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});
Please change the url in the AJAX function in the following way.
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "<?php echo base_url; ?>page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});

Issues posting comment with ajax through django

I am relatively new to this, but I'm working through things. I want to get solid understanding of how things work.
That being said, I have been attempting to get Django to post comments with an ajax hook.
I thought I was close to accomplishing this but, nothing so far. I was able to write a view that would save a posted comment then redirect me to my main page. I want to be able to use ajax so that the comment would post in a facebook style.
def add_comment(request, pk):
if request.method == 'POST' and request.is_ajax():
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = comment_form.save(commit=True)
comment.save()
json = simplejson.dumps(comment, ensure_ascii=False)
return HttpResponse(json, mimetype='application/json')
return render_to_response(simplejson.dumps('{{ post.id }}', {'comment': comment,}), context_instance=RequestContext(request), mimetype='application/json')
This view is pretty rough right now. I don't have any calls to json but, read this might be the way to go.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
$(document).click(function()
{
$('#comment_form').submit(function()
{
var dataString = $('#comment_form').serialize();
$.ajax({
type: 'POST',
url: '{{ post.id }}',
data: dataString,
success: function(data){
$('{{ post.id }}').html(data);
},
});
return false;
});
});
</script>
<form action="" method="POST" id="comment_form">{% csrf_token %}
<div id="cform">
Name: {{ form.author }}
<p>{{ form.body|linebreaks }}</p>
</div>
<div id="submit"><input type="submit" value="Submit"></div>
</form>
Thanks for the response, next time I will definitely leave a more detailed post. My problem was in the jquery script. I was trying to pass dataString as form data to the view, when it was a DOM object not the actual form data. Here's the final working script.
$(document).ready(function() {
$('#comment_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url art.views.post %}',
data: $('#comment_form').serialize(),
dataType: 'json',
success: function() {
location.reload();
$('#comment_form').get(0).reset();
},
});
return false;
});
});

Resources