Reputation: 166
I'm trying to create a dynamic view with laravel, php and jquery ajax. When a navbar button is clicked, it will send an ajax request to the controller which will verify the id send, get the data and return this in html format.
Since there might be multiple values send back which need their own html div's. So I've tried this using an object.
buttonclicked => ajax request to controller => Get data => format data with html => put it in an object => return object to the ajax request succes: .
The problem I'm having now is that The object does return, but instead of the html formatted data, it has a boolean set to true as shown in firebug.
I'm fairly new to Ajax and Jquery, and I'm sorry if this question has been asked many times before.
Ajax:
function onclickNavbar(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:'/controller/AjaxController',
type: "POST",
dataType: "json",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: {identifier: id},
success: function(data){
var $Htmlselector = $("#contenthtml");
console.log('succes');
jQuery.each(data.html, function(key, value){
console.log(key + ' : ' + value);
$($Htmlselector).html(value);
});
},
error: function(data){
console.log('Error something went wrong. See response output:');
console.log(data);
}
});
}
Controller:
public function processor(){
if(isset($_POST['identifier'])){
$id = $_POST['identifier'];
$db = new DatabaseController();
$diensten = $db->GetAllDiensten()->where('parentcategory_id', '=', $id);
$htmlObject = array();
$counter = 0;
foreach($diensten as $dienst){
$htmlObject[$counter++] = "
<div class='col-xs-2half card-column'>
<div class='article-list header-card'>
<a href='/dienst/" . $dienst->shortname . "'>
<img src=" . asset( 'assets/img' . $dienst->image ) . "/>
</a>
</div>
<div class=".'article-list'." class=".'body-card'.">
<hr class=".'hr-card'." >
@if(" . strlen($dienst->name) <= 20 . ")
<h3 class='name text-card'>" . $dienst->name . "</h3>
@else
<h3 class='name text-card'>" . $dienst->name . "</h3>
@endif
<hr>
<p class='description idtagA text-card'>" . $dienst->shortdesc . "</p>
</div>
<div class='article-list footer-card'>
<a href='/dienst/". $dienst->shortname ."'>
<button class='btn btn-danger btn-card' type='button' style='padding-bottom:10px;'>
<span>". $dienst->shortname ."</span>
</button>
</a>
</div>
</div>";
}
$htmlObject = json_encode((object)$htmlObject);
return response()->json(['html'=> $htmlObject]);
//return json_encode($html, true);
}else{
return 'Value Identifier not set!';
}
}
note: I am using Laravel 5.6.3, The @if @foreach etc is syntax for blade.
{"html":[true]}Array{
"message": "Array to string conversion",
"exception": "ErrorException",
"file": "C:\\xampp\\htdocs\\Development Entric\\Entric_website\\app\\Http\\Controllers\\AJAXController.php",
"line": 49,
"trace": [
{
"file": "C:\\xampp\\htdocs\\Development Entric\\Entric_website\\app\\Http\\Controllers\\AJAXController.php",
"line": 49,
"function": "handleError",
"class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions",
"type": "->"
},
{
"function": "processor",
"class": "App\\Http\\Controllers\\AJAXController",
"type": "->"
},
{
.... It goes on for a while...
The are more functions like this, they're there now, so when some queries are used more often with the ->where or ->find I can expand these functions with different parameters. Dienstencontroller:
use App\diensten; // This is the model.
class DatabaseController extends Controller
{
function GetAllDiensten(){
return $diensten = diensten::all();
}
Upvotes: 0
Views: 308
Reputation: 166
I've been rebuilding the ajax request and controller function step by step and testing every bit of the code to check where it breaks. Everything works great, until the creation of the object where the data is set with the with the Html.
I used Blade syntax in the Html, thinking this would work. Well it sort of did, PHP Recognized the if statements, but ignoring the Html with the data in the string. So it would just check if the Blade @if()
statement was true or false,and since this block of code is used in a foreach, it would check every @if()
in the object parsed, and the booleans would be set in the object.
So by removing blade syntax:
@if(" . strlen($dienst->name) <= 20 . ")
<h3 class='name text-card'>" . $dienst->name . "</h3>
@else
<h3 class='name text-card'>" . $dienst->name . "</h3>
@endif
and just writing:
<h3 class='name text-card'>" . $dienst->name . "</h3>
The object will contain the html with the data from the database.
Should've known the @if()
would create problems, since it wouldn't be do-able with php if statements.
Upvotes: 0
Reputation: 3496
Why you are encoding json twice?
$htmlObject = json_encode((object)$htmlObject);
return response()->json(['html'=> $htmlObject]);
You can directly use
return response()->json(['html'=> (object)$htmlObject]);
Please try this in your code.
The ajax call reads the response from the server, and that response must be rendered as some type of readable data, such as application/json
or text/html
.
In order to write that data, you need to echo it from the server with PHP.
The return statement doesn't write data, it simply returns at the server level.
Try this
echo json_encode(['html'=> (object)$htmlObject]);
die;
foreach($diensten as $dienst){
$htmlObject[] = "
<div class='col-xs-2half card-column'>
<div class='article-list header-card'>
<a href='/dienst/" . $dienst->shortname . "'>
<img src=" . asset( 'assets/img' . $dienst->image ) . "/>
</a>
</div>
<div class=".'article-list'." class=".'body-card'.">
<hr class=".'hr-card'." >
@if(" . strlen($dienst->name) <= 20 . ")
<h3 class='name text-card'>" . $dienst->name . "</h3>
@else
<h3 class='name text-card'>" . $dienst->name . "</h3>
@endif
<hr>
<p class='description idtagA text-card'>" . $dienst->shortdesc . "</p>
</div>
<div class='article-list footer-card'>
<a href='/dienst/". $dienst->shortname ."'>
<button class='btn btn-danger btn-card' type='button' style='padding-bottom:10px;'>
<span>". $dienst->shortname ."</span>
</button>
</a>
</div>
</div>";
}
No need to give key $counter++
you can simply use $htmlObject[]
You are not really fetching data from db.
$diensten = $db->GetAllDiensten()->where('parentcategory_id', '=', $id)->get();
Use get()
to fetch the rows and store in $diensten
$diensten = diensten::where('parentcategory_id', '=', $id)->get();
Add App/diensten in your controller and use the model directly. It should give you the desired result.
Upvotes: 3
Reputation: 750
in you php controller change return by echo
change this
return response()->json(['html'=> $htmlObject]);
by this
echo response()->json(['html'=> $htmlObject]);
Upvotes: 1