retrieve user from database from javascript - javascript

I am making an application in Laravel and I need to retrieve a user from the database from javascript, from its id.
Something like:
User :: find (id);
or:
DB :: table ('users') -> find (id);
but in javascript

I would consider using AJAX.
your other JS code
...
$.ajax({
type: "POST",
url: "to your controller",
data: {
'user_id' : user_id,
},
success: function (data) {
userdata1 = data.data1;
userdata2 = data.data2;
...something
}
});
And the controller would look something like this
class SomeController extends Controller
{
public function somefunction(Request $request)
{
$user = User::find($request->user_id);
... do other stuff
return response()->json([
'data1' => someValue1;
'data2' => someValue2;
]);
}
}
If you only need User's data, you can simply use route model binding and
class SomeController extends Controller
{
public function somefunction(User $user)
{
return response()->json([
'data1' => $user->name;
'data2' => $user->addr;
]);
}
}
There might be a better solution, but it works.
Don't know how exactly your code is, but if User's data has been already sent to view from controller, you can just do
var x = "<?php echo $user->somedata ?>"
in you JS code

Related

Vue js parameter can't get in route

I use VueJS and laravel but now I can't get parameter value, please help me to solve this problem.
my VueJS code:
getTestData:function () {
let config = {
params: {
id: 1
}
};
axios.post('{{ route('get_user_data') }}', config)
.then(function (response) {
console.log(response);
// app.posts=response.data;
})
.catch(error => {
})
},
My Controller code:
public function testData(Request $request)
{
// how to get this value?
}
My route
Route::post('get-user-data','TestController#testData')->name('get_user_data');
You don't actually need a post request to get some values out of database. A get request would be more suitable.
You need to have the param in the route definition
Route::get('get-user-data/{id}','TestController#testData')->name('get_user_data');
//If you want to use post route
Route::post('get-user-data/{id}','TestController#testData')->name('get_user_data');
Then in controller method you can get the value out of the request
public function testData(Request $request)
{
$id = $request->route('id');
}
params are the URL parameters to be sent with the request
You could retrieve input from query string in your controller as:
public function testData(Request $request)
{
$id = $request->query('id');
}

Laravel Jquery Ui Ajax Post to Controller and get value to blade

I built and basic Jquery Ui slider:
$("#sliderNumCh").slider({
range: "min",
min: 0,
max: 20,
step: 1,
value: 20,
change : function(e, slider){
$('#sliderAppendNumCh').empty();
var getSliderVal = document.getElementById('sliderValue').value = sliderValue;
$('#sliderAppendNumCh').append(
<div class=\"form-group\" style=\"width:100%;margin:0 auto;\">
...
</div>);
},
slide : function(e , slider){
$('#number_of_chapters').val(slider.value);
},
});
My question is now how to post the slider value on each slide to my Laravel Controller.
I tried this:
$.ajax({
type: 'POST',
url: "{{Route('getAjaxRequest')}}",
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {value: getSliderVal},
success: function (option) {
console.log(getSliderVal);
}
});
route:
Route::post('create', ['as' => 'getAjaxRequest', 'uses' => 'ProductController#getAjaxRequest']);
and in my controller I tried to call and return the value like this:
public function getAjaxRequest()
{
$value = Request::get('value');
return view('productRom.edit')->with('value', $value);
}
so basically I want to get the slider value and later on return the value to a php function, to use that value for example in a loop.
I am not used to Ajax and therefor not sure what I am doing wrong.
Edit
I tried Jose Rojas suggestion:
public function getAjaxRequest()
{
$value = Request::get('value');
//do your stuff
return $slideValue;
}
And I get following error in the console:
http://localhost/myapp/public/product/edit/%7BproductID%7D 500 (Internal Server Error)
the actual url is:
http://localhost/myapp/public/product/edit/51
Edit
this is my route:
Route::get('edit/{productID}', ['as' => 'editProduct', 'uses' => 'ProductController#editProduct']);
If I undestand well, you want to get the value for a slide so the method in your controller instead return a view should return the value for the slide, somthing like this:
public function getAjaxRequest($productID)
{
$value = Request::get('value');
//do your stuff
return $slideValue;
}
then, in your method that receives the value, you do what you want with this value. The goal of using AJAX is load parts of web page without reloading whole web page.

Symfony3 send AJAX POST request

I want to send two variables id and commentary through an AJAX POST request.
The problem is that I don't get the POST variable but the route is reached.
JS:
$.post(Routing.generate('ajax_savecommentary', { id:id, commentary:commentary }),
function(response)
{
}, "json");
Symfony:
public function saveCommentaryAction()
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$request = $this->container->get('request_stack')->getCurrentRequest();
$isAjax = $request->isXMLHttpRequest();
if ($isAjax)
{
$information = $this->getDoctrine()->getManager()->getRepository('CommonBundle:Information')->find($_POST['id']);
$information->setCommentaire(str_replace('\n', '\\n', $_POST['commentary']));
$this->getDoctrine()->getManager()->flush();
$response = array("code" => 100, "success" => true, 'commentary' => $_POST['commentary']);
return new Response(json_encode($response));
}
$response = array("code" => 0, "success" => false);
return new Response(json_encode($response));
}
The error:
http://localhost/MyProject/web/app_dev.php/ajax/save/commentary/?id=61&commentary=MyCommentary.
{"code":0,"success":false}
More Symfony error:
GET Parameters
Key/Value
commentary/MyCommentary
id/61
And the routing is case needed:
ajax_savecommentary:
defaults: { _controller: CommonBundle:Default:saveCommentary }
path: /ajax/save/commentary/
options:
expose: true
Try using the request passed to the Controller Action instead of retrieve it from the container. So try this:
use Symfony\Component\HttpFoundation\Request;
...
public function saveCommentaryAction(Request $request)
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$isAjax = $request->isXMLHttpRequest();
instead of this:
public function saveCommentaryAction()
{
if (!$this->get('session')->get('compte'))
return $this->redirect($this->generateUrl('accueil'));
$request = $this->container->get('request_stack')->getCurrentRequest();
$isAjax = $request->isXMLHttpRequest();
UPDATE:
You can restrict your routing with Customized Route Matching with Conditions, as example on your case as follow:
ajax_savecommentary:
defaults: { _controller: CommonBundle:Default:saveCommentary }
path: /ajax/save/commentary/
options:
expose: true
condition: "request.isXmlHttpRequest()"
methods: [POST]
UPDATE:
There is a typo in the routing generation in the JS side:
$.post(Routing.generate('ajax_savecommentary', { id:id, commentary:commentary }),
function(response)
{
}, "json");
you pass the data as argument of the routing.generate function so it concatenate the params as query string. so try this:
$.post(Routing.generate('ajax_savecommentary'), { id:id, commentary:commentary },
function(response)
{
}, "json");
Another advice is about to use the $request object for obtain the data instead of the superglobal PHP attribute, so use:
$request->request-get('commentary');
instead of:
$_POST['commentary']
More info here in the doc.
Hope this help

Laravel 4 can't get data from Angular Ajax

I am trying to develop my application in Laravel 4 and Angular JS, my application allows user to retrieve their Information through the system via Text Change.
Angular is used to pass data input from the user to Laravel which in turn retrieves the Information from the Database.
However Laravel is unable to retrieve the data passed from Angular.
View
<div data-ng-controller="ReservationController">
<input id='ERI' type='text' data-ng-model="scanRID" data-ng-change="queryRes()" name='exampleInput' maxlength='3' />
</div>
Angular Factory
app.factory('exampleFactory', function($http) {
var factory = {};
factory.getExample = function(scanRID) {
return $http({
method: 'GET',
url: LARAVEL_CONTROLLER + 'Example',
data: $.param(scanRID)
});
};
return factory;
});
Angular Controller
app.controller('exampleController', function($scope, $http, exampleFactory) {
$scope.queryRes = function() {
if($scope.scanRID.length == 3) {
exampleFactory.getExample($scope.scanRID)
.success(function (data) {
// Do Something Here
})
.error(function (data) {
console.log(data);
});
}
};
});
Laravel 4 Routes
Route::get('Example', 'ExampleController#show');
Laravel 4 ExampleController
class ExampleController extends \BaseController {
public function show()
{
$id = Input::get('scanRID'); // This here might be wrong. It's always empty!
$data = ExampleModel::find($id); // Able to query and retrieve.
return Response::JSON($data); // Returns empty.
}
}
Laravel 4 ExampleModel
class ExampleModel extends Eloquent {
// The id of this table is what I want, but I can't retrieve it.
protected $fillable = ['id', 'ExampleData1', 'ExampleData2'];
protected $table = 'exampleTable';
}
I have searched everywhere for a solution, it seems that everyone is able to successfully make the Ajax call. I think there is something that I am missing out that I am unaware about.
I have also tried setting CSRF Token, but however, I do not think that is an issue. So my last resort is to turn to the experts and hope someone is able to help me.
On a side note, I am fairly new to Laravel and Angular, so if you do post a solution, please explain to me the issue as I would like to learn more about Angular and Laravel.
Thank you for reviewing my issue.
You are not passing the value of scanRID by scanRID parameter instead pass only the value without parameter. So you are try to get the value from scanRID using Input::get('scanRID'); but without having scanRID parameter. that should be the case ur not getting the value :)
return $http({
method: 'GET',
url: LARAVEL_CONTROLLER + 'Example',
data: $.param({scanRID:scanRID}) //Change Here
});
OR
return $http({
method: "GET",
url: LARAVEL_CONTROLLER + 'Example',
params: {scanRID:scanRID} //Change Here
);
change like this

How to put data from a controller into a specfic div element in a view

How can I load data i.e $mytweets into a specific div within a specific template/view i.e footer.php?
I have twitteruserfeed.php as my Controller for getting the tweets, but I don't know how to present it within an already existing.
HTML:
<div id="fresh-tweetfeed"> $mytweets GOES HERE </div>
PHP:
class TwitterUserFeed extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function getTweets()
{
$params = array(
'userName' => 'RowlandBiznez',
'consumerKey' => 'hgfhhgffhg',
'consumerSecret' => 'hhffhfghfhf',
'accessToken' => 'hfhhhfhhf',
'accessTokenSecret' => 'hfhfhfhfhhfhfh',
'tweetLimit' => 5 // the no of tweets to be displayed
);
$this->load->library('twitter', $params);
$tweets = $this->twitter->getHomeTimeLine();
$this->load->helper('tweet_helper');
$mytweets = getTweetsHTML($tweets);
echo $mytweets;
}
}
I also have a helper file tweet_helper.php. Help me out with this presentation.
Solution #1:
If the tweets must be displayed on every page, extend the CI_Controller (create MY_Controller.php file inside application/core folder) and fetch/store the tweets on a property:
class MY_Controller extends CI_Controller
{
public $tweets = '';
public function __construct()
{
// Execute CI_Controller Constructor
parent::__construct();
// Store the tweets
$this->tweets = $this->getTweets();
}
public function getTweets()
{
$params = array(
'userName' => 'RowlandBiznez',
'consumerKey' => 'hgfhhgffhg',
'consumerSecret' => 'hhffhfghfhf',
'accessToken' => 'hfhhhfhhf',
'accessTokenSecret' => 'hfhfhfhfhhfhfh',
'tweetLimit' => 5 // the no of tweets to be displayed
);
$this->load->library('twitter', $params);
$tweets = $this->twitter->getHomeTimeLine();
$this->load->helper('tweet_helper');
$mytweets = getTweetsHTML($tweets);
return $mytweets;
}
}
Then in each controller use that property when you load a view:
$this->load->view('path/to/view', array('tweets', $this->tweets));
Solution #2:
You could also load the tweets by sending a XHR request from the client to Controller/Method (after serving the page), then insert the response into the page by Javascript.
Here is a jQuery sample:
$.ajax({
url : <?php echo base_url('controller/method'); ?>,
type : 'GET',
success : function (result) {
// Insert the result into a container
$('#fresh-tweetfeed').append(result);
}
});

Categories

Resources