0

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.

UPDATE: ## Error according to the code of @SmitRaval

{"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...

UPDATE 2:

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();
}
2
  • Just something to mention: You define a jquery element with var $Htmlselector = $("#contenthtml"); and then you do $($Htmlselector).html(value); where $Htmlselector is already a jquery element. So you just need to use $Htmlselector.html(value); Commented Mar 28, 2018 at 12:13
  • Didn't know that, thanks for the heads-up! Will use that from now on. Commented Mar 28, 2018 at 12:16

3 Answers 3

3

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.

Edit

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;

Update

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[]

Update 2

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

Update 3

 $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.

Sign up to request clarification or add additional context in comments.

19 Comments

Ah, I might've overlooked the double encoding, applied your code in mine, it now logs the key and value, but it only displays the boolean: 0 : true.
Can you please show your JSON response? @RickJellema
in Firebug, the response returns: {"html":{"0":true}} or would you like an image?
Please check edit in my post. Let me know if it works? @RickJellema
Tried the edit you posted, didn't work; Response: {''html'':{''0'':true}} and in Firebug at the json tab it shows: html Object { 0=true } 0 true
|
1

in you php controller change return by echo

change this

 return response()->json(['html'=> $htmlObject]);

by this

 echo response()->json(['html'=> $htmlObject]);

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.