Yii2, send AJAX request with link - ajax

I need to send AJAX request using link.
<a href="#" class="messages_close">
<i class="far fa-window-close"></i>
</a>
May be construction like this?
<?php
$js = <<<JS
$(".messages_close").click(function () {
var id = 8;
$.ajax({
url: "'.\yii\helpers\Url::toRoute(['messages/exclude','id'=>8]).'",
type: "get",
data: "id="+this.id,
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR :: ' + 'id=' + this.id);
}
});
});
JS;
$this->registerJs($js);
Is it possible? Thank you
UPDATE 1
Thanks for #vvpanchev and #Serghei Leonenco
I did some changes:
added use yii\helpers\Url and changed url:;
removed data: "id="+this.id
removed var id = 8 it used in URL
I still get ERROR alert! ((
How can I get SUCCESS, or better return message from controller?
Here is my code looks like:
view\messages.php
<?php
use yii\helpers\Url;
?>
...
<a href="#" class="messages_close">
<i class="far fa-window-close"></i>
</a>
...
<?php
$js = <<<JS
$(".messages_close").click(function () {
$.ajax({
url: "' . Url::toRoute(['messages/exclude','id'=>8]) . '",
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);
MessageController.php (it opens in browser without problem)
<?php
namespace app\controllers;
use Yii;
use app\models\MessagesUsers;
use yii\web\Controller;
class MessagesController extends Controller
{
public function actionExclude($id)
{
return 'Success ID=' . $id;
}
}
Thank you for your help!
SOLUTION
<?php
$url = Url::toRoute(['messages/exclude']);
$js = <<<JS
$(".messages_close").on('click', function () {
$.ajax({
url: "{$url}",
data: {id: 8},
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);

<?php
$url = Url::toRoute(['messages/exclude']);
$js = <<<JS
$(".messages_close").on('click', function () {
$.ajax({
url: "{$url}",
data: {id: 8},
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);

Related

How can I delete using ajax in laravel?

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 delete data without refreshing whole page using ajax

I am new at Laravel, I am trying to delete data with ajax, when I click to delete button, the page is refreshing but data is deleting perfectly but that should not be reloaded.
Controller
public function destroy($id)
{
$delete = Digitizing::where('id', $id)->delete();
return back();
}
HTML view
<a href="{{route('digitizing.delete',$digitizing->id)}}"
class="btn btn-danger" onclick="deleteConfirmation({{$digitizing->id}})">Delete</a>
<script type="text/javascript">
function deleteConfirmation(id) {
Swal.fire({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('digitizing/delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
**Delete wants a get method because you have to give only ID to delete.**
**WEB.PHP**
Route::get('digitizing/delete/{id}','YourController#destroy');
**SCRIPT**
let id = $('#my_id').val();
$.ajax({
type: 'GET',
url: "{{url('digitizing/delete')}}/" + id,
data: {
_token: '{{csrf_token()}}',
},
success: function () {
alert('Successfully Deleted');
}
}).fail(function(){
console.log('problem with route = digitizing/delete');
});

Laravel : can't read data from my Ajax jQuery code in my controller

i'm sending the section id in my ajax function,but i can't receive this data in my controller function.need your help please.
This is my jQuery:
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getGroupe').change(function(){
var section = jQuery('#getGroupe').val();
$.ajax({
url: "/ajax",
type: "POST",
data: {
section:section,
},
success: function(){
alert(section);
},
error: function(){
alert("error");
}
});
$.post("{{URL::to('/ajax')}} ",function(data){
$('#groupe').empty().html(data);
});
});
});
Web:
Route::post('ajax' , 'SeanceController#ajaxfct');
My function in the controller:
public function ajaxfct(Request $request){
$id = $request->section;
$groupes = \DB::table('groupes')
->where('section_id','=',$id)
->get();
return view('seance.groupe')->with([
'groupes' => $groupes
]);
}
The code is close to working perfectly, the following setup passes the data correctly:
HTML:
<select id="getGroupe">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getGroupe').change(function(){
var section = jQuery('#getGroupe').val();
$.ajax({
url: "/ajax",
type: "POST",
data: {
section:section,
}
}).done(function( msg ) {
console.log('response: ', msg)
});
});
});
</script>
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SeanceController
{
public function ajaxfct(Request $request)
{
return ['received' => $request->section];
}
}
Route:
Route::post('/ajax', 'SeanceController#ajaxfct');

Opencart cart.add() with option

I'm looking for solution in opencart.
Need to rebuild cart.add function for adding product with option value.
By default:
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('#cart > button').button('reset');
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
}
});
checkout/cart/add php side for option:
if (isset($this->request->post['option'])) {
$option = array_filter($this->request->post['option']);
} else {
$option = array();
}
Any solutions?
You can do this in the following way. Create a simple Javascript object.
var productData = {'product_id' : PRODUCT_IDS.CARD, 'quantity': 1,'option':{'229':"Some option value"}};
And send the request as follows. Converting the object to post params using the param function.
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $.param(productData),
dataType: 'json',
beforeSend: function () {
},
complete: function () {
},
success: function (json) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Also there are some other ways to do this, you can see possible payload formats in the /controller/checkout/cart.php file.

Ajax retrieve data from success function

I am submitting a form via Ajax, and I want to prepend the project name to a list item when the form is submitted. Everything works fine except for pulling the information needed inside the success function. Data[Project][project_name] is being posted. How do I get the project name inside the success function? Right now "data" is being displayed in the list. I only have the one textbox in my form.
<script type="text/javascript">
$(document).ready(function () {
var frm = $('#ProjectAddForm');
frm.submit(function() {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function(data) {
$('#ProjectProjectName').val('');
$('#ProjectList').prepend("<li style='color: green;'>data</li>");
}
})
});
return false;
});
</script>
HTML:
<ul id="ProjectList">
<?php foreach ($projects as $project): ?>
<li><?php echo $project['Project']['project_name']; ?></li>
<?php endforeach; ?>
<?php unset($project); ?>
</ul>
<form accept-charset="utf-8" method="post" onsubmit="event.returnValue = false; return false;" id="ProjectAddForm" action="/callLog/projects/add">
I needed to add a dataType: 'json' to the request.
<script type="text/javascript">
$(document).ready(function () {
var frm = $('#ProjectAddForm');
frm.submit(function() {
$.ajax({
type: frm.attr('method'),
url: "<?php echo $this->Html->Url(array('controller' => 'projects', 'action' => 'add.json')); ?>",
data: frm.serialize(),
dataType: 'json',
success: function(data) {
$('#ProjectProjectName').val('');
$('#ProjectList').prepend("<li class='icon-remove', style='color: green;'>" + data.projectName + "</li>");
$('#modalProject').modal('hide');
}
})
});
return false;
});
</script>

Resources