how to get url value from arduino using ajax and laravel? - javascript

this is my url value from arduino
request_string = "http://127.0.0.1:8000/monitoring/x/?x=1";
i have problem when try to catching the value using url in ajax
$.ajax({
type:'get',
url:'http://127.0.0.1:8000/monitoring/x/',
dataType: "json",
success:function(response){
if (response.data==0) {
var img = document.getElementById("kursi7");
img.src="{{asset('/assets/images/kursi.jpg')}}";
document.getElementById('lokasi'+1).innerHTML=("TIDAK ADA ORANG");
}else {
// location.reload();
var img = document.getElementById("kursi7");
img.src="{{asset('/assets/images/kursi_booked.jpg')}}";
document.getElementById('lokasi'+1).innerHTML=("ADA ORANG");
}
}
});
and processing in php (laravel)
i have some error undefined variable x when try to get the data $_GET['x'] from passing value url in arduino
public function data(Request $req, $x)
{
$x=$_GET['x'];
return response()->json($x);
}
i hope someone can help and give me an information abt this.
thanks a lot mate

For the PHP side of things you should be doing something like this instead:
public function data(Request $request)
{
$x = $request->input('x')
return response()->json($x);
}
As per https://laravel.com/docs/8.x/requests#accessing-the-request

Related

Laravel download xls file with AJAX

I can't download my XLS file via Ajax
function downloadFile(response) {
var blob = new Blob([response], {type: 'application/vnd.ms-excel'})
var url = URL.createObjectURL(blob);
location.assign(url);
}
$('#export').click(function () {
$.ajax({
type: 'POST',
url : 'factures/engagements/selected/export',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
dataType: "json",
data : {
checkboxes : checkboxValues
}
}).done(downloadFile);
});
my controller :
public function exportFacturesEngagementSelected(Request $request){
$checkboxes = $request->input('checkboxes');
$collection = collect($checkboxes);
$engagements = EngagementOrder::whereIn('id' , $collection)->get();
$date = Carbon::now('Europe/Paris')->format('d-m-Y H:i:s');
$output = Excel::create('factures_engagements' . $date. '', function($excel) use ($engagements) {
$excel->sheet('Excel', function($sheet) use ($engagements) {
$sheet->loadView('engagements.exportExcelSelected')->with("engagements", $engagements);
});
})->export('xls');
return $output;
}
I only get the output preview of the file in my console network, but nothing happens in my browser; no file is downloaded. What am I doing wrong?
UPDATE #matticustard solution :
my checkboxValues is a json for exemple the result is
{920: "920", 927: "927", 931: "931", 939: "939"}
when i console log query i get :
undefinedcheckboxes=920&checkboxes=927&checkboxes=931&checkboxes=939&
When i try to get the values to my controller i made a $request->all() and i get :
array:2 [
"undefinedcheckboxes" => "920"
"checkboxes" => "939"
]
why i get undefinedcheckboxes and why i don't get the other ids ?
Try this
if your ajax success
location.href = path/to/file/property_title.xls
change this line
->export($type);
with
->store($type, 'public/reports/', true);
These days I've used this package
(my recommendation) for converting my model's collections to XLS and export that.
As I understand, you want to download the file via AJAX. I didn't got you at all, but I just can share my experience for helping you. This working with a normal POST request, but it will not refresh your page anyway.
So this is a working example:
In Controller
public function export(Request $request)
{
$data = $request->get('data'); // get incoming data field
return \Excel::download(new ExcelService($data), "custom-file-name-with-extension.xls");
}
In Service (or you can implement this in controller too)
namespace App\Services;
use App\Models\Item;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExcelService implements FromCollection
{
protected $data = null;
public function __construct($data)
{
$this->data = $data;
}
public function collection()
{
$items = Item::where('data', $data)->get(); // some query using incoming $data
return $items;
}
}
Route
Route::post('export', 'ItemController#export')->name('export');
There's really no reason to use AJAX or store the file. You can pass the checkbox data as parameters in the URL with a GET request and use an <iframe> to download the file. I guessed at the controller name, so adjust as necessary.
web.php
Change the route to GET.
Route::get('factures/engagements/selected/export', 'FactureController#exportFacturesEngagementSelected')->name('export');
JavaScript function and handler
Serialize the data as expected by your controller and make the request.
I guessed that checkboxValues was an array of values based on the actions taken in your controller. But you could serialize the form directly var query = $('form').serialize(); and adjust the controller to match the input.
function downloadFile() {
var query;
$.each(checkboxValues, function(index,value) {
query += 'checkboxes=' + value + '&';
});
$('<iframe />')
.attr('src', '/factures/engagements/selected/export?' + query)
.hide()
.appendTo('body');
}
$('#export').click(function () {
downloadFile();
});
FactureController.php
And use the download method in your controller.
// ...
->download('xls');

How to access a javascript variable inside a php query?

I want to access a javascript variable inside a php query
function myFunction2(){
Total=parseInt(point2)
<?php
$con->query("UPDATE eventlist SET P2 = $this.Total WHERE Eid=$PID");
?>
}
I want the query to set p2=value of total
I understand that php is a serverside script and I cant do this like this. What is an alternative to this.?
EDIT
ok i got this on the JS side
function myFunction2(){
var Total = parseInt(point1)+parseInt(point2);
$.ajax({ url: 'ajax.php',
data: {'total' : Total},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error");
}
and if i put
echo $_POST['total']
in ajax.php i get an alert with the value passed. So i think the value is being passed properly.
But what i need to do is a Mysql Query.
$con->query("UPDATE eventlist SET P2 = $_POST['total']; WHERE Eid=1");
Something like this. How do i do this
Try send javascript value to another php page which contain your query
function myFunction () {
var param = "value";
$.post('query.php', { postvalue: param}, function(data) {
//do what you want with returned data
//postvalue should be the name of post parameter in your query page
})
}
Change your PHP in this way:
$total = $_POST['total'];
$con->query("UPDATE eventlist SET P2 = $total WHERE Eid=1");

Returning html as ajax response

I have web page that submits a form via AJAX in codeigniter, submission works great, and the php script works as well, but when php is done it return an HTML view as a response to Ajax so it repopulates a div but instead of repopulating it try's to download the file. Chrome console shows
Resource interpreted as Document but transferred with MIME type application/text/HTML
has me confused because I use the same code in another page and it works fine.
This is my Jquery script
$("#addpaymentform").submit(function (event) {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
data: formdata,
url: baseurl + 'sales/add_payment',
success: function (data, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
$('#paymets').html();
$('#payments').html(data);
$('#addpaymentform').each(function() { this.reset() });
}
if (ct.indexOf('json') > -1) {
$("#Mynavbar").notify(
data,
{position: "bottom center"}
);
$('#addpaymentform').each(function() { this.reset() });
}
}
});
event.preventDefault(); // this will prevent from submitting the form.
});
and this is my controller
function add_payment()
{
$this->form_validation->set_rules('fpay', 'Type of payment', 'trim|required|alpha');
$this->form_validation->set_rules('payment', 'Payment', 'trim|numeric');
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
header('Content-type: application/json');
echo json_encode(validation_errors());
} else {
$fpay = filter_var($this->input->post('fpay'), FILTER_SANITIZE_STRING);
$payment = filter_var($this->input->post('payment'), FILTER_SANITIZE_STRING);
if(isset($_SESSION['payments'][$fpay]))
{
$temp = $_SESSION['payments'][$fpay] + $payment;
$_SESSION['payments'][$fpay] = $temp;
header('Content-type: application/html');
echo $this->_loadpaymentcontent();
}
}
}
function _loadpaymentcontent() {
$this->load->view('payment_content');
}
Hope someone can point me in the right direction I've been stuck on this for 2 days.
Thanks everyone.
I had the same problem and i successfully solved it by putting an exit; after the value which is returned to the ajax call in the controller method.
In your case it will be:
echo $this->_loadpaymentcontent();
exit;
What exit does here is it limits the returned value to the value which should be returned to the ajax call and exits before the html is appended to the returned value.
This is what is obvious per the effect it produces.
Yo need to set up your AJAX.
$.ajax({
type : 'POST',
url : baseurl + 'sales/add_payment',
dataType : 'html', // Will set the return type of the response as AJAX.
... Keep rest of the code same.

Ajax request return empty array

I am trying to get the id, where the user clicked, and pass it to my controller via AJAX.
For some reason, when i try to show what i am receiving in my controller, it show an empty array.
Any idea why my alert return an empty Array?
JS Function:
function categorySelected(elem) {
$.ajax({
url: "/newgallery/creative-fields-click",
type: "POST",
data: elem.id
}).done(function (response) {
alert(response);
});
}
PHP:
public function creativeFieldsClickAction()
{
$idSelected = $this->_request->getPost();
print_r( $idSelected );
exit();
}
Data should be JSON, not integer.
data: { elemid : elem.id }
Then in PHP data can be found from $_POST['elemid']. In your code it could be like
$this->_request->getPost()['elemid'];
Or something like that.
Try by changing
In ajax
data: { id : elem.id }
And in action of controller
$ids = $_POST;
print_r($ids);

Make page refresh if successful login with ajax/jquery

Ajax code
$("#login_btn").click(function() {
var url = "core/login.php";
$.ajax({
type: "POST",
url: url,
data: $("#sr").serialize(),
success: function(data) {
var responseData = jQuery.parseJSON(data);
$('.oops').html('<div class="error">'+responseData.oops+'</div>');
alert(responseData.good);
if(responseData.good === 1) {
alert(good)
location.reload();
}
}
});
});
Php code if everything passes
else {
$_SESSION['id'] = $login;
$good = 1;
exit();
}
How come it's not freshing the page with location.reload? Should I be using .done .try?
Dont refresh, the whole idea of using ajax is that you dont need to.
You can set your sessions in the ajax php script and pull new content based on the change in session.
That being said, you are missing a ';' at
alert(good);

Categories