Delete multiple records in laravel - php

To remove only one record I realize this ajax
var borrar = confirm("¿Realmente desea eliminarlo?");
if (borrar)
{
var token = document.getElementById('token').value;
$.ajax({
headers: {'X-CSRF-TOKEN': token},
dataType: "json",
data: {radicado: radicado},
url: ip+'/eliminarRadicado/delete/'+radicado,
type: 'get',
beforeSend: function(){
},
success: function(respuesta){
alert(respuesta);
},
error: function(xhr,err){
alert("Error");
}
});
}
which sends by $get the id of the record that I delete the file and run this route :
Route::get('eliminarRadicado/delete/{id}', 'RadicadoController#destroy');
which ultimately goes to the driver and performs the function of removing
public function destroy($id)
{
\App\Radicado::destroy($id);
return response()->json(['Documento eliminado']);
}
What is not like removing more than one record (id ) I send. Any ideas ?

You shouldn't send delete requests using a GET verb. Instead you should use the DELETE verb which is semantically correct.
With your current approach, sending the X-CSRF-TOKEN header doesn't do anything, as Laravel doesn't check the CSRF token for read requests (GET and HEAD). Instead you should pass all the IDs you want to deleted as parameters with a DELETE request like so:
var ids = [1, 10, 17]; // Use your own logic to set the array of the IDs here
$.ajax({
headers : {'X-CSRF-TOKEN': token },
dataType: "json",
data : { ids: ids }, // Pass IDs array
url : ip + '/eliminarRadicado/delete',
type : 'delete', // Send a delete request
beforeSend: function () {
},
success: function (respuesta) {
alert(respuesta);
},
error: function (xhr, err) {
alert("Error");
}
});
Then change your route definition to this:
Route::delete('eliminarRadicado/delete', 'RadicadoController#destroy');
And in your destroy controller method use the array of IDs received via the request:
use Illuminate\Http\Request;
...
public function destroy(Request $request)
{
\App\Radicado::destroy($request->input('ids'));
return response()->json(['Documento eliminado']);
}
Now you can pass an array of one or more IDs to be deleted using the same request.

Related

passing multiple id into one ajax function

I want to run the same js ajax function on multiples id, so I could return the specific information from my database. Here it did run through "id="test" but it returns them to all of it. How do I make them return to its own "id"
html
<div>
<p class="postbutton" id="test_1" > </p> \\supposed to return 1, but it returns 3//
<p class="postbutton" id="test_2" > </p> \\supposed to return 2, but it returns 3//
<p class="postbutton" id="test_3" > </p> \\supposed to return 3, but it returns 3//
</div>
my scripting function
$(".postbutton").each(function () {
x = $(this).prop('id').replace(/[^\d.]/g, '') // converting it to a set of ID to be passed to my controller
$.ajax({
/* the route pointing to the post function */
url: '/postajax',
type: 'POST',
/* send the csrf-token and the input to the controller, Laravel stuff */
data: {_token: CSRF_TOKEN, message: x},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data)
{
$(" p[id^='test']").html(data.msg);
}
});
});
Use $(this).html() otherwise, for each ajax call, $(" p[id^='test']").html(data.msg) will be call even the last ajax call. So the last call has 3 as answer. So it updates the two first ajax call.
$(".postbutton").each(function () {
var context = this
x = $(context).prop('id').replace(/[^\d.]/g, '') // converting it to a set of ID to be passed to my controller
$.ajax({
/* the route pointing to the post function */
url: '/postajax',
type: 'POST',
/* send the csrf-token and the input to the controller, Laravel stuff */
data: {_token: CSRF_TOKEN, message: x},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data)
{
$(context).html(data.msg);
}
});
});
Since ID is attribute which wont be changes in your case - try replace .prop with .attr() to get the value of ID.
Also matching that you inside success function will return all possible matches - in this case 3
Also it will be good if you use already founded ID for matching element in success function like
$(`#test_${x}`).html(data.msg);
First to store your all id in array.
after pass this array in your ajax function.
like this:-
var id_list=[];
$(".postbutton").each(function () {
x = $(this).prop('id').replace(/[^\d.]/g, '') // converting it to a set of ID to be passed to my controller
id_list.push(x);
});
$.ajax({
/* the route pointing to the post function */
url: '/postajax',
type: 'POST',
/* send the csrf-token and the input to the controller, Laravel stuff */
data: {_token: CSRF_TOKEN, message: id_list},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data)
{
$(" p[id^='test']").html(data.msg);
}
});

Problem reposting data periodically using AJAX to Laravel backend

Am working on a PHP Laravel project whereby when a user clicks on a button on the website I perform some background task using AJAX to a PHP backend whreby I trigger a call to a payment gateway, when the user pays via his/her phone,,, I check the payment status (where 1 means paid, 0 means not paid) and if status is equal to 1, I redirect the user to a success page.
Currently am using AJAX to post data from the frontend to the backend and I want to post the data periodically after 5 seconds (where I give the user some time to pay before reaching out to the API to see if the status has changed to 1 then redirect the user).
Am trying to use setTimeout method in JavaScript and dd() the data from the controller which only dumps the data once but doesnt dump after 5 seconds
AJAX code to post data to the backend after 5 seconds
$('.mpesa').on('click', function () {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
function executeQuery() {
alert('clicked');
//Adds Class to the page when it loads
$('.PAY').addClass("loading");
//Gets the MPESA type
var type = $('.mpesa').prop('id');
var quote = $('#quote').val();
var phone = $('#phone').val();
//Converts to a JSON object
var type ={
'type': type,
'quote' : quote,
'phone' : phone,
};
console.log(type);
$.ajax({
//Contains controller of payment
type: 'POST',
url: 'paymentFinal',
data: JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function success(response) {
console.log(response);
},
error: function error(data) {
console.log(data);
}
});
}
//End AJAX call
Controller file being called
public
function payFinal(Request $request)
{
dd($request->all());
}
Updated AJAX code
$('.mpesa').on('click', function () {
setInterval(function() {
alert('clicked');
//Gets the MPESA type
var type = $('.mpesa').prop('id');
var quote = $('#quote').val();
var phone = $('#phone').val();
//Converts to a JSON object
var type ={
'type': type,
'quote' : quote,
'phone' : phone,
};
console.log(type);
$.ajax({
//Contains controller of payment
type: 'POST',
url: 'paymentFinal',
data: JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function success(response) {
if(response) {
window.location.href="success";
}
},
error: function error(data) {
console.log(data);
}
});
}, 15000); // Execute every 15 seconds
});
setTimeout only executes the specified function once after the delay you set. Use setInterval instead so your function get called periodically.
=========================================================================
Update:
You want your function to execute immediately when the user clicks and after that calls itself every 15 secs. To achieve that, you can just use the following code:
$('.mpesa').on('click', executeQuery);
function executeQuery() {
alert('clicked');
//Adds Class to the page when it loads
$('.PAY').addClass("loading");
//Gets the MPESA type
var type = $('.mpesa').prop('id');
var quote = $('#quote').val();
var phone = $('#phone').val();
//Converts to a JSON object
var type ={
'type': type,
'quote' : quote,
'phone' : phone,
};
console.log(type);
$.ajax({
//Contains controller of payment
type: 'POST',
url: 'paymentFinal',
data: JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function success(response) {
console.log(response);
},
error: function error(data) {
console.log(data);
}
});
//use setTimeout here
setTimeout(executeQuery, 15000);
}
Use setTimeout in your function to call itself would solve your problem.
=========================================================================
[To answer OP's question on how to stop the timer]
In your function, say you want the function to stop execution after 5 times.
Set up a variable outside of the function:
var counter = 0;
Then in executeQuery:
if (counter <= 5) { //or use your own logic
counter++;
setTimeout(executeQuery, 15000);
}
Remember that setTimeout is a one-time-thing, so you can just control when to stop calling it.

AJAX call is not working as expected

I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.

Laravel: Send Data to Controller via AJAX Without Form

I need to send data via JS to a Laravel controller on a button click. I'm not using any form because the data is being created dynamically.
Every time i try to send the data, i get an Internal Server Error (500), but unable to catch that exception in the controller or the laravel.log file.
Here's what i'm doing:
Route:
Route::post('section/saveContactItems', 'SectionController#saveContactItems');
Controller:
public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }
JS:
$('button').on("click", function (evt) {
evt.preventDefault();
var items = [];
var id = $("#id").val();
var languageID = $("#languageID").val();
var data = { id: id, type: type, items: JSON.stringify(items), languageID: languageID };
$.ajax({
url: "/section/saveContactItems",
type: "POST",
data: data,
cache: false,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response)
{
console.log(response);
}
});
});
What am i doing wrong? How can i accomplish this?
UPDATE: Thanks to #ShaktiPhartiyal's answer (and #Sanchit's help) i was able to solve my issue. In case some else comes into a similar problem, after following #Shakti's answer i wasn't able to access the data in the controller. So, i had to stringify the data before sending it to the server:
data: JSON.stringify(data),
You do not need to use
public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }
You have to do the following:
public function saveContactItems()
{
$id = Input::get('id');
$type = Input::get('type');
$items = Input::get('items');
$languageID = Input::get('languageID');
}
and yes as #Sanchit Gupta suggested you need to send the CSRF token with the request:
Methods to send CSRF token in AJAX:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you use this approach you need to set a meta tag like so:
<meta name="csrf-token" content="{{csrf_token()}}">
or
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
UPDATE
as #Sanchit Gupta pointed out use the Input facade like so:
use Input;

Reading a very simple ajax request in Laravel

I lately managed to get a simple ajax post to work but can't get any of the data in the controller :
Ajax :
function verify(event) {
var title = event.title;
var start = event.start.format("h:m");
$.ajax({
url: "/admin/timetable/verify",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
contentType: "application/json; charset=utf-8",
data: {type : 'hi',titles : title},
dataType: "json",
success: function(response){
if (response['state']==='0')
toastr.error('Are you the 6 fingered man?'+response['msg']);
if (response['state']==='1')
toastr.info('Are you the 6 fingered man?');
},
error : function(e){
console.log(e.responseText);
}
});
}
Controller :
$d = Request::all();
dd($d);
return response()->json(['state'=>'0','msg'=>$d['titles']],200);
I tried Request all, Input all, Input::json()->all() .. nothing works always null or empty array [] ! I'm just trying to read the data sent from the ajax form !
I faced this lately. The problem (I don't know why) was about Get and POST.
Just transform route to a GET, make the ajax type as GET, and try with a very simple Input::all.
public function verifyClassroom(){
$Data = Input::all();
dd($Data);
}
This is my tested code and it works
function verify(event) {
$.ajax({
url: "/test",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
data: {type : 'hi',titles : "title"},
success: function(data){
alert(data);
},
error : function(e){
console.log(e.responseText);
}
});
}
and in my route closure
Route::post('test', function(\Illuminate\Http\Request $request){
$type = ($request->input('type'));
return $type;//returns type->hi
});
in the php controller you need to have something like this.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourcontrollernameController extends Controller {
public function test(Request $request) {
echo $request->input('type');
echo '/';
echo $request->input('titles');
die;
}
}
you can access the type and title by $request->input('type') and $request->input('titles')
ALso try using get method and
in yourproject/routes/web.phpweb.php
Route::get('/test', 'YourcontrollernameController#test');

Categories