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.
Related
BLADE FILE
<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
</td>
AJAX
$(document).ready( function () {
$(".deleteuser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
});
CONTROLLER
public function destroyuser($id){
$this->authorize('Admin');
User::find($id)->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
return view('viewuser');
}
If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance
I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.
$(document).ready( function () {console.log("document is ready")
$(".deleteuser").click(function(){
Refresh the page and check if "document is ready" is logged to the console.
If it isn't then the javascript is not loading
Check if the route is properly defined
You can replace your url as this and check:
var id = data.id;
var url = "{{route('your_route',":id") }}";
url = url.replace(':id', id);
pass url in your ajax url param
Or make above changes:
BLADE FILE
<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>
SCRIPT
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function ()
{
var obj = $(this);
var id=$(this).closest('td').find(".delete_id").val();
var result = confirm("Are you sure want to delete?");
if(result)
{
$.ajax(
{
type: "POST",
url: "{{route('delete_method')}}",
data: {
'_token': $('input[name="_token"]').val(),
'id': id
},
cache: false,
success: function (data)
{
if (data.status === 'success')
{
window.location = "{{route('redirect_route')}}";
toastr["success"]("Deleted Successfully", "Success");
}
else if (data.status === 'error')
{
location.reload();
toastr["error"]("Something went wrong", "Opps");
}
}
});
}
});
});
</script>
Controller
public function delete_method(Request $request)
{
$del = ModelName::findOrFail($request->id)->delete();
if($del)
{
return response()->json(['status' => 'success']);
}
else{
return response()->json(['status' => 'error']);
}
}
Route
Route::post('/test/delete','TestController#delete_method')->name('delete_method');
In your ajax codes, change this:
url: "user/delete/"+id,
To:
url: "{{ url('user/delete') }}/" + id
If your ajax codes are inside of your blade file also you can use this way:
url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"
You incorrectly define delete function!
change
User::find($id)->delete($id);
To
User::find($id)->delete();
I want to update active and inactive status in laravel with toggle. Status show perfectly. But controller doesn't work. Here
is my code.
blade file
#foreach($data as $srial => $row)
<tr>
<td>{{$row->name}}</td>
<td>
<input data-id="{{$row->id}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $row->status ? 'checked' : '' }}>
</td>
</tr>
#endforeach
<script>
$(document).ready(function(){
$('.toggle-class').change(function () {
let status = $(this).prop('checked') === true ? 1 : 0;
let userId = $(this).data('id');
$.ajax({
type: "GET",
dataType: "json",
url: '{{ route('/changeStatus') }}',
data: {'status': status, 'user_id': userId},
success: function (data) {
console.log(data.message);
}
});
});
});
</script>
Controller
public function changeUserStatus(Request $request)
{
$file=DB::table('students')->where('id',$id)->first();
$user=$file->status;
$task ['status']= $request->user_id;
$data=DB::table('students')->where('id',$request)->update($task);
}
Route
Route::get('/changeStatus', 'AdminController#ChangeUserStatus')->name('/changeStatus');
Try bellow query:
public function changeUserStatus(Request $request)
{
DB::table('students')->where('id', $request->user_id)->update(['status' => $request->status]);
}
Where condition is wrong, need to pass user id and status in update.
and in view, ajax type must be post
$(document).ready(function(){
$('.toggle-class').change(function () {
let status = $(this).prop('checked') === true ? 1 : 0;
let userId = $(this).data('id');
$.ajax({
type: "POST",
dataType: "json",
url: "{{ route('/changeStatus') }}",
data: {'status': status, 'user_id': userId},
success: function (data) {
console.log(data.message);
}
});
});
});
Route must be post type
Route::post('/changeStatus', 'AdminController#ChangeUserStatus')->name('/changeStatus');
I have a list of manufacturers with checkbox when i checkbox is checked ajax is called and hit the controller but not return anything
I am using laravel 5.1
#foreach($manufacturers as $leedsManufacturer) {{-- #foreach($leedManufacturers as $leedsManufacturer) --}}
<div class="post" id="post{{$leedsManufacturer['mfgg_id']}}">
<label class=" my-checkbox gry2" id="manufacturer">{{str_limit($leedsManufacturer['mfgg_name'], 300)}}
<input type="checkbox" class="manufacturer common_selector" name="manufacturer[]" value="{{$leedsManufacturer['mfgg_id']}}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<span class="checkmark"></span>
</label>
</div>
#endforeach
#endif
script
$(document).ready(function() {
filter_data();
function filter_data() {
var manufacturer = get_filter('manufacturer');
// var products = get_filter('products');
// var chps_approved = get_filter('chps_approved');
$.ajax({
url: "{{url('ajax1')}}",
method: 'POST',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data:{manufacturer:manufacturer} ,
success:function(data){
console.log(data);
}
});
// alert(manufacturers);
}
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
alert(filter);
// return filter
}
$('.common_selector').click(function(){
filter_data();
});
});
controller
public function ajax1(Request $request){
$data= $request->manufacturer;
return response()->json($data);
}
On checkbox select, it should return the ID so i can use it in controller. but $request->manufacturer show this on console.
try this lets see if you are getting the id from the form. i use javascript alert
$(document).ready(function() {
filter_data();
function filter_data() {
var manufacturer = get_filter('manufacturer');
alert(manufacturer);
// var products = get_filter('products');
// var chps_approved = get_filter('chps_approved');
$.ajax({
url: "{{url('ajax1')}}",
method: 'POST',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data:{manufacturer:manufacturer} ,
success:function(data){
console.log(data);
}
});
// alert(manufacturers);
}
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
alert(filter);
// return filter
}
$('.common_selector').click(function(){
filter_data();
});
});
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%'
});
I'm trying to get the value of the option in my template below called exampleid. I've followed several examples I found online, but nothing seems to work. My template below has the ajax and jquery to get the value but when I try to print it returns None. I've exhausted my resources and my professor doesn't seem to know, he's "looking into it".
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title ="accesslevelid" class="form-control" id="accesslevelid" onchange="accesslevelid" title="">
<option value="7"> Option 1</option>
<option value="5"> Option 2</option>
<option value = "3"> Option 3</option>
</select>
<script>
$(document).ready(function () {
$('#accesslevelid').on('change', function () {
var accesslevelid = $(this).val();
$.ajax({ url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
alert(result);
},
});
});
});
</script>
my view attempting to retrieve the value of the post.
exampleidpost = request.POST.get('accesslevelid', False)
print (exampleidpost)
My desired result is for the POST to return a 7,5, or 3.
You should add csrf token to you ajax request,
Try this way.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title="accesslevelid" class="form-control" id="accesslevelid" >
<option value="1"> Option1</option>
<option value="2"> Option2</option>
<option value="3"> Option3</option>
</select>
<script>
$(document).ready(function () {
$('#accesslevelid').on('change', function () {
var accesslevelid= $(this).val();
$.ajax({
url: "{% url 'submitted' %}",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: {
accesslevelid: accesslevelid
},
type: 'POST',
success: function (result) {
alert(result);
},
});
});
});
</script>
And you no longer need a form.