Laravel Ajax Response Return HTML Elements

laravel ajax response return html elements

I think it should look something like this

public function viewStudent(Request $request, $studentid = null)
{
if(!Auth::check())
{
return redirect('/');
}

if($request)
{
// echo outputs to the server, but you should really return something
// for the requester, thus we will return "YES" to the response
// and since we are returning, it will return and no further executions will made.
return 'yes';
}

if(!is_null($studentid))
{

$data['allstates'] = DB::table('tblstates')->get();
$data['alllga'] = DB::table('tbl_lga')->get();
$data['studentinfo'] = DB::table('tblstudents')
->where('id', $studentid)
->first();

return view('Students.viewstudents', $data);
}

return redirect('/all/students');
}

AJAX function always return html code in response on success

Try removing the middleware from your response.

Laravel - Return 2 views in AJAX response

If you need to return 2 views in an AJAX response, you can do that with the response()->json() method:

$dashboardIndicators = view('pages.dashboard.dashboardindicators', compact(...)->render();
$dashboard = view('pages.dashboard.dashboard', compact(...)->render();

return response()->json(['dashboardIndicators' => $dashboardIndicators, 'dashboard' => $dashboard]);

Then, in your success: function, access like so:

$("#dashboardindicators").html(data.dashboardIndicators);
$("#dashboard").html(data.dashboard);

Also, make sure to use the ->render() function to convert the view to HTML.

Ajax Request Return HTML Page

I don't think you're sending any data to your controller. Try this, check the data property of the AJAX call.

<script>
$("#getCategoryMae").blur(function(){
var cat_id = $(this).val();
console.log(cat_id);

var dataObject = {cat_id: cat_id};
$.ajax({
type: 'GET',
url: '{{route('getCategoryName')}}',
data: dataObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log(data.cat_id);
}
});

});
</script>

Also, I can tell you use Google Chrome, you can make sure you send something to the server, you can click on the Headers, go to the bottom to the Query String Prameters to see the parameters you're sending.
Here's a good resource: Chrome Dev Tools

Laravel return a view in an Ajax response

They are not working for you because they return a JSON response and not an html one. You should return the view directly, without the render method call.

Try this

return view('pages.your_page');

or

return view('pages.your_page')->render();

Undefined variable when returning view as HTML via AJAX

As described here in php doc, you should pass the name of the variable as a string in compact() method.

$returnHTML = view('categories.new', compact('category'))->render();

Or you can pass the variable to blade file using array.

$returnHTML = view('categories.new', ['category' => $category])->render();


Related Topics



Leave a reply



Submit