Ad

How To Append Large Html Block To Blade File With Javascript/jquery?

By clicking on a button, I want to append a large chunk of HTML (form for example) to my blade file with javascript/jquery. What is the best way to do so?

Something like this (just a part):

            <div class="form-group col-md-3  ">
                <input placeholder="Váha (kg)" id="package-weight" type="text"
                       class="form-control required {{ $errors->has('package-weight') ? ' is-invalid' : '' }}"
                       name="package-weight" value="{{ old('package-weight') }}">

                @if ($errors->has('package-weight'))
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $errors->first('package-weight') }}</strong>
                    </span>
                @endif
            </div>
Ad

Answer

This can be done with an AJAX request, something like below:

$.get("/example", function(data){
  $("body").append(data.html);
}

Your route /example, would need to have a Controller or basic function associated that returns a JSON response containing the HTML you want to render:

Route::get("/example", "[email protected]");

public function example(){
  $view = view("example")->render();
  return response()->json(["html" => $view], 200);
}

// OR

Route::get("/example", function(){
  ... // Same $view/return as example()
});

Then, your .blade file (example.blade.php) would need to contain your HTML.

The ->render() function of view() immediately returns the generated HTML of a .blade file, and returning it via response()->json() allows for your JS function to manipulate the html returned from the server.

Ad
source: stackoverflow.com
Ad