laravel 5 ajax request - ajax

i had a user list form in laravel. so i want when i click the table row, it automatically load the user details from database without redirecting. i've heard about ajax. but i have no idea how to use it in laravel..
i want to make like this
but without redirecting page..
$("tr").click(function()
{
$.ajax({
type: "GET",
url: $(this).data("href"),
dataType: "text",
success : function(data) {
$('#details-container').load(data)
}
});
});
does it supposed to be like this? but how did i get the data from database? i have no idea. please help me..

Its the same in Laravel as in "native" PHP. With your Ajax request your are able to send and asynchronous request, and refresh just a little part of your website, so you dont need to reload your whole page.
If you want to make it work with laravel, you should:
create a route for your requests
Route::get('user/{id}', function($id)
{
// So all your GET requests with any user id goes to this script (in routes.php)
// here you should load your user information, maybe with ORM
$user = User::where('id','=',$id)->get();
// Build any HTML snippet, or build JSON data (and build the information in Javascript on your page)
//return here JSON / or html
$data = array() -> containts information for the blade template
return view('users.information', $data);
});
Your AJAX request returns now JSON / or HTML, append it to your site where you would like to show it.

Your page structure will be like this:
<table>
<thead>
...
</thead>
<tbody>
<tr data-details-link="http://your-domain/user/{user-id}/details">
...
</tr>
</tbody>
</table>
The page with the table, should have this jQuery codes:
$('table tr').on('click', function (event)
{
event.preventDefault();
var $this = $(this);
// not necessary but you should show a loading here
$.ajax({
url: $this.data('details-link')
})
.success(function (response)
{
// the `response` variable is HTML code. Insert it into a modal.
});
});
Your route:
...
Route::get('user/{id}/details', [ 'uses' => 'UserController#details' ]);
...
Your UserController method:
public function details($id)
{
$user = \App\User::find($id);
if (!$user)
abort(404);
return view('user.details')->with('user', $user);
}
**Your user/details.blade.php should have the HTML that will be send as the AJAX response.

Related

How to pass variables from Controller to View without refreshing the Web Page in Laravel?

Whenever there is a call to Controller inside View, I want the Controller to return some variables to the View and do not refresh the View.
Already know:
return view("webpage" , compact('variable1', 'variable2') );
What I expect to achieve:
return compact('variable1', 'variable2');
This will not return the Webpage but only some of the variables.
Edit:
Thinking it from a complete different perspective, The question maybe rephrased as such
Is there a way to manipulate REQUEST variables of a web page from the controller? This way, i would be able to get new variables from the Controller without the web page being Refreshed.
With out much to work with, here is an example:
Ajax call:
$.ajax({
url: '/your/route/',
type: 'GET',
data: {getVariable: formInputValue},
})
.done(function (data) {
console.log(data);
})
.fail(function () {
console.log('Failed');
});
Controller Function:
public function getVariable(Request $request){
$resault = $request->getVariable;
return response()->json($results);
}
Update: as per comments on this answer try this and see if it works for you.
In your controller where you fetch records instead of using a ->get();
change it to paginate(5); this will return 5 records per page. and on your view at the bottom of your </table> add {{ $variable->links() }}

Ajax data not being sent to controller function (CodeIgniter)

I have an anchor tag and would like its data-id to be sent to a function in the controller which would in turn retrieved data from the database through the model.
However the data is not getting past the controller. The ajax response is showing that the data was sent but controller shows otherwise.
Here is my ajax code:
$(document).on("click",".learn-more",function(){
var sub_item_id = $(this).data("id");
$.ajax({
url:"<?php echo base_url();?>Designs/business_cards",
type:"POST",
data:{sub_item_id:sub_item_id},
success:function(data){
console.log(data);
},
error: function(error){
throw new Error('Did not work');
}
})
});
I had set datatype:"json" but the data was not being sent so I removed the datatype and it worked,the ajax part that is.Or atleast the response showed that data was sent.
My controller code is:
function business_cards(){
$id = $this->input->post('sub_item_id');
$data['quantity'] = $this->subproduct_model->get_quantities($id);
$this->load->view('category/business-cards',$data);
}
My model code is:
public function get_quantities($sub_item_id){
$this->db->select('quantities');
$this->db->where('id',$sub_item_id);
$query = $this->db->get('sub_products');
return $query->result_array();
}
HTML Code which includes the anchor tag
<?php foreach ($results as $object):?>
View Prices
<?php endforeach?>
The data-id is displaying the correct value as per the iteration.
When I check the result array of the model code it is an empty array showing that the $sub_item_id was not passed in the controller. What could be the problem?
I just copied your code and I was able to get the value in the controller.
In your controller function do var_dump($id). Then in your developer tools (F12) check the console. Since you have console.log(data) that var_dump should be in the console. It won't show on the screen.
Some other things to check:
Does your db have records with that ID? Could your db result array be empty because it actually should be?
Are you sure that the data-id actually has a value when you click the tag?
it is not passed to the controller because you forgot to put a parameter inside the function of your controller.
Note: you cannot use input post because you're not using form.
function business_cards($id){ //put a parameter here, serve as container of your passed variable from **ajax**
//$id = $this->input->post('sub_item_id');
$data['quantity'] = $this->subproduct_model->get_quantities($id); //pass the id to your model
$this->load->view('category/business-cards',$data);
}
change your ajax code to this..
$(document).on("click",".learn-more",function(){
var sub_item_id = $(this).data("id");
$.ajax({
url:"<?php echo base_url('Designs/business_cards/"+sub_item_id+"');?>", //pass the id here
type:"POST",
success:function(data){
console.log(data);
},
error: function(error){
throw new Error('Did not work');
}
})
});

View returning in popup laravel 5.4

I am returning a view from controller, but instead of opening new page, the view is opening in popup which i assume is error message popup,. i am new in laravel.
Controller Code
public function postRegister () {
return view('front.member.registerpayment')->with('amountUSD', $data['btc_withcom']);
}
You can do this using AJAX request.
In your controller…
public function postRegister () {
// do something to get your data
return response()->json(
[
'data'=>$your_data
]
);
}
Then make a ajax request
First import jquery.
Then
$.ajax({
url: ‘your url’,
method: ‘POST’
data: ‘pass any data to controller’
success: function(data){
// invoke popup with data
// you can easily do this with jquery UI library
}
})
Here is the complete example to open dialog box.
Hint: append your data to html before invoking

AngularJS : ng-selectize is not initializing selctize options after AJAX call

I'm using ng-selectize directive to a select box using angularJS. Options to the slectbox are retrieved from an AJAX call. AJAX call response is coming in proper format.If do inspect element, select box options are populated properly. But in the UI, options are not rendered. Is there any specific reason for this behaviour? The same code is working fine in another place.
Here is my code:
HTML:
<select multiple="multiple"
ng-model="email.existing"
ng-options="obj.email for obj in emailLists track by obj.email"
placeholder="Choose from existing email address"
selectize>
Javascript
angular.module('myApp', [
'myApp.controllers',
'myApp.services',
'ngDialog',
'angular-selectize'
]);
angular.module('myApp.services', []).
factory('myAPIservice', function($http) {
var myAPI = {};
myAPI.getAllEmail = function( data ) {
return $http.post(APP_BASE_URL + "director/getallemail", data );
}
return myAPI;
});
angular.module('myApp.controllers', [])
.controller('myCntrl', function($scope, myAPIservice, ngDialog) {
myAPIservice.getAllDirectorsEmail({}).success(function (response) {
$scope.emailLists = response;
});
});
The above code retrieves email list from url. Sample response will look like this.
AJAX Response
If I change the javascript code to
angular.module('myApp.controllers', [])
.controller('myCntrl', function($scope, myAPIservice, ngDialog) {
$scope.emailLists = new Array({email:'abc#def.com'},{email:'lmn#opqr.com'})
});
and the response will be
Without AJAX call
Can anyone help me resolve this issue?

Loading files via AJAX with CodeIgniter/MVC

I'm currently in the process of rewriting an entire site of mine so that it's compatible with CI. I'm fairly new with CI and the MVC pattern in general. I followed this tutorial and have made a pretty decent template for the view part of the MVC pattern. The thing is, a lot of my site uses jQuery/AJAX to make it more dynamic. For example, on all of my pages on my site, I have an input field that uses jQuery to load a PHP file upon keyup.
<script type="text/javascript">
$("#search_bar").keyup(function(){
var search = $("#search_bar").val();
var url = "search_bar.php";
var data = "q="+ search;
$('#livesearch').load(url, data);
$("#livesearch").slideDown("fast");
});
</script>
<input type='text' maxlength='30' id='search_bar' autocomplete='off' placeholder='Browse Teams' />
<div id='livesearch' style='display:none;'></div>
All of the backend work that's required to load the results happens in the PHP file that loaded via jQuery (search_bar.php). So, should "search_bar" be its own View that's triggered by its own Controller and then Modeled by a model called "search_bar"? Again, I'm very new to the MVC pattern and am not quite sure how properly integrate AJAX with a object oriented framework like CI.
Thanks
Directly calling the view in ajax request is not a good practice call the controller which loads the view or directly do the stuff in the controller's function
<script type='text/javascript'>
$('#search_bar').keyup(function(){
$.ajax({
url: 'yourcontrollername/search_bar_yourfunction',
type:'POST',
data: {q: search,
success: function(result){
$("#livesearch").html(result);
$("#livesearch").slideDown("fast");
}
});
});
</script>
Your controller code
class yourcontrollername extends My_Controller {
public function search_bar_yourfunction() {
//do your stuff and store in the $data[] array
$this->load->view("search_bar",$data); //search_bar.php
die();
}
}
}
You should go from your View to the Controller:
<script type='text/javascript' language='javascript'>
$('#search_bar').keyup(function(){
$.ajax({
url: 'search_bar.php',
type:'GET',
data: {q: search,
success: function(result){
//Insert code here
} // End of success function of ajax form
}); // End of ajax call
});
</script>
Then in your controller, load a model if necessary:
public function weigeren() {
$user = $this->CI->authex->getUserInfo();
$data['title'] = "Test";
$this->load->model('search_model');
$query = $this->input->get('q');
if (isset($user)) {
echo $this->search_model->search($query);
}
}
I find one way to load ajax (jquery) in CodeIgniter 3. Example,
structure of folder:
controllers/Upload.php
view/admin/ajax_view/ajax_images.php
controllers/upload:
public function process()
{
$data['my_picture'] = array(
'pic_id' => '1',
'pic_path' => 'http://example.com/images',
);
$this->load->view('admin/ajax_view/ajax_images', $data);
}
view/admin/ajax_view/ajax_images:
<?php foreach($my_picture as $key => $row): ?>
<td><?php echo $my_picture['pic_path']; ?></td>
<?php endforeach; ?>
view/admin/form_upload:
<tbody>
<tr class="trbody">
<th scope="row">1</th>
<!-- <td></td> --> <!--comments this because appends element jquery-->
</tr>
</tbody>
<script type="text/javascript">
$(document).ready(function(){
$('#my_button').click(function(e){
e.preventDefault;
$.ajax({
url: 'upload/process',
dataType: 'text',
type: 'post',
success: function(data){
$('.trbody')
.append(
'<td>'+ data + '</td>'
);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});
</script>
To this way, I separated view of ajax of whole pages and load ajax view when
event trigger.

Resources