I have created an ajax.php file on my server and send id to the file using ajax with jquery.
I want to run db queries in that ajax.php file to get the result.
I am unable to do this.
Can you please help me.
Jquery Code:
$('.invitebyemail').click(function(){
var email = $('#add-members-event-email').val();
var eventid = $('.eventid').val();
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
var APP_URL = {!! json_encode(url('/')) !!};
alert(APP_URL);
alert(url);
$.ajax({
url: APP_URL+'/ajax.php',
type: 'POST',
data: { id: eventid },
success: function (data) {
alert(data);
},
error: function () {
alert('error');
}
});
return false;
});
Ajax File Code:
use DB;
$eventid = $_POST['id'];
echo $eventid;
$users = DB::table('users')->get();
print_r($users);
Thanks
If you're using laravel I don't belive that using .php files like that would be the correct way of doing it... it's not really following the MVC patterns.
I recomend creating a controler php artisan make:controller MyController
creating a function as this on the controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Session;
use Auth;
use Response;
use DB;
use App\User;
class MyController extends Controller{
public function getUsers(Request $request){
$users = DB::table('users')->get();
// If you need access to request parameters use this ( $request->id ) being id the parameter name
return response()->json(["users" =>$users]);
}
}
creating a route in ProjectFolder/routes/web.php like this
Route::post('/getUsersAjax',[
'uses'=>'MyController#getUsers',
'as'=>'getUsers'
]);
And in your jquery dont forget to add the _token to your data data: { id: eventid , _token : token},
(if you need this token you can in a .blade.php file, your view, make this
<script>
var token = "{{Session::token()}}";
var urlRequest = "{{route('getUsers')}}";
</script>
)
https://laravel.com/docs/5.4/controllers
https://laravel.com/docs/5.4/routing
Related
The string is over 612,000 characters long. I'm using a Laravel framework to generate markers on a google map so they all have to be loaded. json_encode is a very convenient way to do it but the string is ridiculously long.
Within a Laravel framework, instead of using json_encode I used ajax to retrieve the data so that it didn't get exposed to the browser.
blade file snippit:
function initMap() {
// Ajax call to load entire database to a Jquery array
AjaxGet = function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content')
}
});
var result = $.ajax({
url: "{{url('/ajaxgetter')}}",
method: 'post',
async: false, //obsolete flag, but necessary so that the array does not try to set before data is retrieved
success: function (result) {}
}).responseText;
return result;
}
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class AjaxController extends Controller
{
public function index () {return View('ajax');}
public function ajaxgetter() {
return response()->json(DB::select('select * from workorders'), 200);
}
}
I am working on Symfony 4.4.
To refresh a table, users select three options with an input:
InProgress
Finished
All
Then they must press a validate button.
I want to improve the use of this page by automating the refresh of the table.
Currently on my model I have AJX which allows me to retrieve the value of my entry:
<script>
$(document).on('change', '#campagnes_tel_isAttending', function () {
$('#flash').remove();
let $field = $(this)
let $preselect = $('#campagnes_tel_isAttending')
let $form = $field.closest('form')
let data = {}
data[$field.attr('name')] = $field.val()
console.log(data)
// On soumet les données
// $.post($form.attr('action'), data).then(function (data) {
// // On récupère le nouveau <select>
// $('#planningsms_client_label').val($(data).find('#planningsms_client option:selected').text());
// let $input = $(data).find(target)
// // On remplace notre <select> actuel
// $(target).replaceWith($input)
// })
});
</script>
I am now stuck because I cannot figure out how to get information back to my Controller, allowing me to modify a PreSelect variable with the value of the input and change the structure of the SQL query.
Create a route? Call a route in an Ajax POST?
Use this route in my Controller?
I think it's more or less that, but on the other hand I have no idea how to implement it.
EDIT :
It has moved forward a bit.
I manage to recover the data of the change of the input in my controller.
On the other hand I try to recall the function which will allow me to make a new SQL query with the selected filter, but that does not seem to work.
Ajax :
<script>
$(document).on('change', '#campagnes_tel_isAttending', function () {
$('#flash').remove();
let $field = $(this)
let $preselect = $('#campagnes_tel_isAttending')
let $form = $field.closest('form')
let data = {}
data['isAttending'] = $field.val()
console.log(data)
$.ajax({
type: "POST",
url: "/campagnestel/ajax",
data: data,
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
</script>
And function in my controller :
/**
* #Route("/ajax", methods={"GET", "POST"})
*/
public function testAjax(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array(
'status' => 'Error',
'message' => 'Error'),
400);
}
if(isset($request->request)) {
$preSelect = $request->request->get('isAttending');
return $this->queryFollowingFilter($preSelect);
}
// return $this->queryFollowingFilter($preSelect);
return new JsonResponse(array(
'status' => 'OK'),
200);
}
Error :
The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned an array
As the error message states:
The controller must return a "Symfony\Component\HttpFoundation\Response" object
A JsonResponse meets that requirement and suits your needs. Try this:
if($request->request->has('isAttending')) {
$preSelect = $request->request->get('isAttending');
return new JsonResponse(
$this->queryFollowingFilter($preSelect),
200
);
}
Before this, I was getting 405 methods not allowed error in live server
ajax call to upload files:
$('#form-repeater').on('submit',function(e){
e.preventDefault();
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
let thiss=$(this);
let form = document.getElementById('form-repeater');
let data =new FormData(form);
$.ajax({
type:thiss.attr('method'),
url:thiss.attr('action'),
data:data,
dataType:'JSON',
// ContentType:'application/json',
cache: false,
processData: false,
success:function(response){
if(response.message=='1'){
Swal.fire(
'Product Added Successfully',
'',
'success'
)
setTimeout(function(){
window.location.href="/banner";
}, 2000);//wait 2 seconds
}
else{
error = response.errors;
if(error.staff){
$('#form-repeater .invalid-staff').html(error.staff);
}else{
$('#form-repeater .invalid-staff').html('');
}
if(error.customerNumber){
$('#form-repeater .invalid-cust_numb').html(error.customerNumber);
}else{
$('#form-repeater .invalid-cust_numb').html('');
}}});
This is my response from ajax call:enter image description here
normally I can't retrieve data in my controller:
I debug using dd($request->all());
When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig into JSON arrays: $name = $request->input('user.name');
Then on your controller you could do something like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Store a new user.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$name = $request->input('user.name');
// Manage your data the way you want
}
}
I have laravel project and I want to retrieve data from database and send it to ajax function
this is the code of show ($ip) function
public function show($id)
{
$result = DB::table('radcheck')get();
return ( $result);
//
}
this is the code of ajax which is trying to retrieve data from that function but it can not
$('.edit-user').on('click', function() {
var id=$(this).data('id');
$.ajax({
type: 'GET',
url: '/users/' + id,
data: {
'_token': $('input[name=_token]').val(),
},
success: function(hr_request) {
alert(hr_request['username']);
},
error: function(hr_request) {
alert(hr_request['username']);
}
});
});
there is no data can be retrieving, I think I must send data from controller to ajax using json data, but how can I send it as json data and how can I process this json data into ajax function
It is simple .. you can do it like following :
public function show($id)
{
$result = DB::table('radcheck')->get();
return response()->json(['data' => $result]); // here 'data' is key to access $result in ajax response , it is optional.
}
In the ajax response you can console it using console.log(hr_request.data) and check your data result. Additionally , to access property you need to do hr_request.data.property
Hope it helps , Thanks.
I have a view file that is rendered from the default SiteController. This view file makes an ajax call to an action getdetails in a different controller called A1Controller. I want to know how to write the url in the ajax call and if there is anything that has to be changed in the UrlManager in web.php configuration file.
This is my ajax call :
ajaxCall = function () {
$.get('how/to/write/this/url?', function (data) {
var jsondata=JSON.parse(data);
GenerateTable(data);
setTimeout('ajaxCall()', 5000);
});
};
Can someone help me out please. Thanks in advance.
Inside the view file:
<?php
$ajaxUrl = \yii\helpers\Url::to(['controller/action-name']);
$this->registerJs("
ajaxCall = function () {
$.get('$ajaxUrl', function (data) {
var jsondata=JSON.parse(data);
GenerateTable(data);
setTimeout('ajaxCall()', 5000);
});
};
");