passing multiple id into one ajax function - php

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);
}
});

Related

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.

Delete multiple records in laravel

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.

Pass input value to ajax get Laravel

I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that

Sending a global variable

I have a piece of Javascript that forwards a users' selected information to an external PHP file, and returns information. In the code below, you can see it sends {'report' : report} via POST to that file. That works fine.
Essentially I need to add another variable to be sent. It's called 'id', but it's in another function. Is there a way to make that variable global and then incorporate it so it's sent in my code snippet? (and when will the global variable be cleared?)I can also send it via the 'url' attribute, and use GET in my PHP...just not sure how to implement.
$('#adminSelectReport a').live("click", function () {
//Get id from clicked link:
var report = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': report
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
UPDATE: Here is the other snippet that sends 'id' to another page, getting information. I need to retain this ID, however, and use it on my original code.
$('#adminSelectCompany a').click(function() {
//Get id from clicked link:
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {'id': id},
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg);
$('#adminSelectReport').fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
So it sounds like they select a Company via a link, then they select a Report via another link, and you need to remember which Company was selected.
In order to avoid global variables, I'd probably just add a class to the selected Company link, and then fetch that element by the selected class, and grab its ID. You could use the class for styling as well if that's needed.
var companies = $('#adminSelectCompany a');
companies.click(function () {
// remove class from previously selected, and add to new one
companies.filter('.selected').removeClass('selected');
$(this).addClass('selected');
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {
'id': this.id
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg)
.fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
$('#adminSelectReport a').live("click", function () {
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': this.id,
'company': $('.selected')[0].id
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
You can achieve this by assigning the value as a property of JavaScripts "global" namespace called window. Simply assign the id you want to make global to window.my_id, then refer to it in the click callback.
Note: If you're setting the global variable in another function, remember to check for its existance in the function that will use the variable, ie: var my_id = null; if (window.my_id != undefined) { my_id = window.my_id; }
Here's an implementation:
$('#adminSelectReport a').live("click", function () {
//Get id from clicked link:
var report = $(this).attr('id');
var company = window.report_company_id != undefined ? window.report_company_id : null;
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': report,
'company': company
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
.
$('#adminSelectCompany a').click(function() {
//Get id from clicked link:
var id = $(this).attr('id');
window.report_company_id = id;
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {'id': id},
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg);
$('#adminSelectReport').fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
Lastly I would advise against global variables if possible, or at least minimize the usage by wrapping common function/purposes in objects and prefixing the names with the project name or something.
Change
data: { 'report': report },
To
data{ 'report': report, 'id': YOUR ID },
Why don't you send the second variable like that:
data: {'report': report, 'id': your_id },
edit: arf too slow!

Categories