How to make layout false in Laravel If request is ajax - laravel

I have trying to load a page using simple get request
<script>
$(document).ready(function(){
$("li").click(function(e){
e.preventDefault();
var href = $("a",this).attr('href');
$.ajax({
async: true,
type: "GET",
url: href,
success: function (response) {
$('#main-content').html(response);
}
})
});
});
</script>
In response I am getting content with full layout. But Here I am trying to get only content without layout. In controller I have written code like below
public function index()
{
if ($request->ajax())
{
$this->layout = null; //but same result
}
$tags = Tag::orderBy('id', 'desc')->paginate(10);
return view('admin.tags.index')->with('tags',$tags);
}
But I am getting same result with layout, how can I make layout false ? Or can change layout in controller ?

you can use the renderSections
return view('admin.tags.index')->renderSections()['content'];
https://laravel-tricks.com/tricks/render-view-without-layout

Well, you are still returning a view. Why not do:
return response()->json(["data"=>"some data"]);
after your Ajax check? This will return a JSON response to your frontend.

Related

Laravel ajax return whole HTML page instead data

I'm having this trouble with the ajax request. This code works on other pages, only on this not working.
I want to call ajax (from different controller - CalendarController) on "show" page from controller ClientController - (http://.../client/35) maybe is that wrong
Client.js
$(document).ready(function() {
$('#events-list').on('click', '.event-popup', function () {
var getEventId = $(this).data('id'); //this line is okay, return dynamic id as i want
$.ajax({
type: "GET",
url: "getEvent/" + getEventId,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json',
})
.done(function (data) {
console.log(data); //if i remove dataType: 'json' whole page will print in log instead data
})
.fail(function(data,jqXHR, textStatus, errorThrown) {
toastr.error("error");
console.log(data,jqXHR, textStatus, errorThrown);
})
});
});
Error message from ajax
parsererror" SyntaxError: Unexpected token < in JSON at position
...
responseText: "<!DOCTYPE html><html lang="sr"><head>... - WHOLE PAGE
web.php
Route::get('/getEvent/{id}', 'CalendarController#getEventData');
CalendarController
public function getEventData($id)
{
$event = Event::findOrFail($id);
return Response::json($event);
}
I added how to Controller looks but does not return data, this ajax call does not come to the controller
I think the problem is somewhere in the URL or because I want to add data with another controller to the show page, but I can't figure
Thanks in advance
EDIT
Ajax request is redirected for some reason
Instead of findOrFail() (it returns HTML if the object doesn't exist), use find() method. Then you can check if the object exists or not and return json as per the condition.
Example:
public function getEventData($id)
{
$event = Event::find($id);
if(!$event) {
return response()->json([
'success' => false,
'message' => 'Not Found'
], 404);
}
return response()->json($event);
}

ajax query without passing page data laravel 5.6

I have a button and when it's clicked, I basically want to load the Auth::user()->name and a date into the database. I can't figure out how to do an ajax call without passing in some sort of data. This is my ajax query.
var url2 = "/application-background-sent/{{$application->id}}";
$(document).ready(function(){
$('#bgSubmit').click(function(e){
$.ajax({
url: url2,
success: function(data) {
alert(data);
},
type: 'GET'
});
});
});
My route:
Route::get('/application-background-sent/{id}', 'ApplicationsController#backgroundSent');
My controller:
public function backgroundSent($id)
{
$application = Application::findOrFail($id);
$application->bg_check_submitted_by = Auth::user()->name;
$application->save();
return response()->json(['success'=>'Data is successfully added']);
}

Laravel 5.2 post route returns plain html text

whenever I send a post request to 'tasks/add' i want the user to return to a new page, but all I get is plain html text in a popup.
Route.php code
Route::post('tasks/add', function() {
return view('secrets');
});
this is my ajax request :
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=customer]").val();
var details = $("input[name=details]").val();
var dataString = 'customer='+customer+'&details='+details;
$.ajax({
url: "tasks/add",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data : dataString,
success:function(data){
console.log(dataString);
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
});
Anybody has had this issue before?
You are using Ajax to call your Route method. So when Route::post(...) returns the view 'secrets', it returns it to the Ajax method and becomes held by the data variable. Saying return in your Routes file doesn't magically mean redirect to a certain view, it is just like any other function that returns a value.
You currently have alert(data) which just says make an alert with whatever is held by data which in this case is the html text of your view.
Instead, take out the alert() and put
window.location.replace('<path/to/secrets>')
to redirect to the page you want upon success.
Assuming your Routes file has something like :
Route::get('/secrets', function() {
return view('secrets');
});
You could say
window.location.replace('/secrets')

how to access a controller function from outside of controller in codeigniter

I have a folder (suppose it's name is "test") outside of controller folder which contains a file name "error404.php" and my controller name is "test_controller.php" which has a method name "tst()". error404.php is a view page in where i want to access data from test_controller.php via ajax.
<script>
$(document).ready(function(e) {
$('#search_items_err').keyup(function(e) {
if($('#search_items_err').val().trim()==''){$('#sugglist').html(''); return false;}
search_key=$(this).val().trim();
var data = {
search_key: search_key
};
alert(search_key);
$.ajax({
data: data,
type: "post",
url: "test_controller/tst",
success: function(response) {
var options = JSON.parse(response);
alert(options);
}
});
});
});
</script>
My tst function is:
public function tst(){
$search_key = $_POST['search_key'];
echo "success";
}
But my ajax doesn't work. I suspect that it may contain some problems in the (url: "test_controller/tst",). So how can i solve it? What is the syntax of accessing test_controller's method from error404.php page?How do i access base url?
Take a look at this ajax concept
in your ajax function :
url : baseURL+'test_controller/search', //Make sure this url is working properly
data : {'search_key' : search_key},
in you test_controller/search
public function search()
{
//generate data and load your view
$data = "Generated Data array";
$this->load->view('test_folder/search', $data); //Load your view from application/view/ not from outside the controller
}

Ember Put and Post Request without Ember-Data

I have built a model from GET request and display the content that I need into a form, mainly dropdown options. User then completes the form and 'POST' back to the api. The API that I am using isn't formatted in a way that I can use for ember-data so I have opted to render my model with Ember.Object
var Prequalification = Ember.Object.extend();
Prequalification.reopenClass({
template: function(){
return Ember.$.ajax({
url: "/prequalification",
dataType: 'json'
}).then(function(response){
var template = response.collection.template.data;
return template;
});
}
});
export default Prequalification;
My controller decorates the view:
var IndexController = Ember.ArrayController.extend({
businessType: function(){
var content = this.get('content');
console.log(this);
return content.get(10);
}.property('content'),
loanType: function(){
var content = this.get('content');
return content.get(5);
}.property('content')
});
export default IndexController;
So on form submit, what are my options for Posting back to the API?
Thanks!
Use an action and associate it with a button.
actions: {
save: function(){
alert('ajax save here');
}
}
http://emberjs.jsbin.com/jositowa/1/edit

Resources