Home > Blockchain >  $request->ajax is false in insert
$request->ajax is false in insert

Time:01-16

I would like to insert data into a database, but in controller is $request->ajax() false. Can anybody help me? I spent a whole day on Google, but nothing helped me. I am using laravel 8. I used ajax for filter books. It works fine. But here I don't know where the error is. When I use dd($request) before if the result is:

This is .js file:

$(document).ready(function () {
    $("#review-form").submit(function (e) {
        e.preventDefault();

        let reviewText = $("#reviewText").val();
        let bookID = $("#bookID").val();
        let userID = $("#userID").val();

        $.ajax({
            type: "POST",
            url: "catalog/singleBook/"   bookID,
            dataType: "json",
            data: {
                reviewText: reviewText,
                bookID: bookID,
                userID: userID,
                _token: $('meta[name="csrf-token"]').attr("content"),
            },
            success: function (response) {
                alert("X");
                console.log("X");
                $("#review-container").prepend(
                    "<div id='review'>"   response.reviewText   "</div>"
                );
                $("#review-form")[0].reset();
            },
            error: function (error) {
                console.log(error);
                console.log("RREEER");
            },
        });
    });
});

Controller:

 public function storeReview(Request $request) {
      
      dd($request->ajax());
      
      if($request->ajax()) {
      $review = new Review;
      $review->bookID = $request->bookID;
      $review->userID = $request->userID;
      $review->reviewText = $request->reviewArea;
      $review->save();
      
      return response()->json($review);   
      }   
   }

view:

@extends('layouts.main')

@section('title', 'Detail')

@section('content')
<div >
    <div >
        <div >
            <div >
                <div >
                    <img  src="{{ $book->img }}" alt=" {{ $book->title }}">
                </div>
                <div >
                    <ul >
                        <li>
                            <div > Nazov:</div>
                            <p>{{ $book->title }}</p>
                        </li>
                        <li>
                            <div > Autor: </div>
                            <p>{{ $book->firstname }} {{ $book->lastname }}</p>
                        </li>
                        <li>
                            <div > Rating:</div>
                            <p>{{ $book->rating }}</p>
                        </li>
                        <li>
                            <div > ISBN: </div>
                            <p>{{ $book->ISBN }}</p>
                        </li>
                    </ul>
                </div>
                <div >
                    <p>{{ $book->description }}</p>
                </div>
            </div>
        </div>

        <div >
            <form id="review-form" method="Post">
                @csrf
                <div >
                    <input type="hidden" value="{{ $book->id }}" id="bookID" name="bookID" readonly />
                    <input type="hidden" value="{{ auth()->user()->id }}" id="userID" name="userID" readonly>
                    <textarea  name="reviewArea" id="reviewText exampleFormControlTextarea1"
                        rows="3" placeholder="Napíš recenziu.." required></textarea>
                </div>
                <button id="submitBTN" type="submit" >Odoslať</button>
            </form>
        </div>

        <div >
            <h2 >Recenzie:</h2>
            <div id="review-container">
            </div>
        </div>
    </div>
</div>
@endsection

web.php:

Route::post('catalog/singleBook/{id}', [CatalogController::class, 'storeReview'])->middleware('auth');

enter image description here

CodePudding user response:

By default, enter image description here

a). Load the HTML view/page where your form resides.

b). Open the browser console (Ctrl Shift J).

c). Click on the "Network" tab. Then click on the "Fetch/XHR" tab found right below the "Network" tab.

d). Fill the HTML form on your page and attempt/try submitting it while looking at the "Network" tab section. You should see a request sent in the "Network" tab section with a URL similar to your Ajax URL value.

e). Click on the request in the "Network" tab. In your case, you may only see the "book id". I.e: "1" as the request name. But when you hover over the request name, you will be able to see the full path. I.e: "http://base_url_here/catalog/singleBook/1" in the "Network" tab section.

f). Once you've clicked/selected the request, select the "Headers" tab.

g). In the "Headers" tab section, scroll down until you reach the "Request Headers" portion of the list.

h). Look at the headers list in the "Request Headers" portion and check to confirm if the header X-Requested-With: XMLHttpRequest exists.

If you're having a hard time following these steps, try learning how to inspect network activity.

Addendum:

To know why this header is important when making ajax requests and how it relates to Laravel's request()->ajax() method, check out:

Laravel 4 Ajax check to include XMLHttpRequest (from Magnific Popup)

Detect Ajax Request-Php And Frameworks

Edit:

  1. Make sure that the Request $request object you're injecting in the storeReview(...) method comes from Illuminate\Http\Request.

  2. This isn't mandatory, but you may want to add "_method" : "POST" to your request body:

$.ajax({
  type: "POST",
  data: {
  // ...
  _method: "POST" 
  },
    // ...
});
  1. If you fail to receive any success with jQuery's $.ajax(...) method, try using jQuery's $.post(...) method.
$.post("catalog/singleBook/"   bookID,
    {
        reviewText: reviewText,
        bookID: bookID,
        userID: userID,
        _token: $('meta[name="csrf-token"]').attr("content"),
        _method: "POST"
    }, function (response) {
        alert("X");
        console.log("X");
        $("#review-container").prepend(
            "<div id='review'>"   response.reviewText   "</div>"
        );
        $("#review-form")[0].reset();
    },
    "json"
).fail(function () {
    console.log(error);
    console.log("RREEER");
});
  1. I strongly believe your jQuery Ajax URL doesn't match the web.php file route definition shared in your question.

Ajax POST request URL.

url: "catalog/singleBook/" bookID,`

web.php Route.

Route::post('missingbook', [MissingBookController::class, 'storeBook'])->middleware('auth');

The route endpoint in your web.php file points to /missingbook yet your jQuery Ajax method URL setting points to catalog/singleBook/{id}. You may want to cross-check/confirm if you forgot and shared the wrong web.php file route definition in your question.

  1. This isn't related to the issue at hand, but I thought you may find it helpful.

5a). In your HTML markup/view, you refer to the <textarea> tag with id="reviewText exampleFormControlTextarea1"

   <textarea  name="reviewArea" id="reviewText exampleFormControlTextarea1" rows="3" placeholder="Napíš recenziu.."
    required></textarea>

Yet you refer to that element in your .js JavaScript file using the "#reviewText" selector:

let reviewText = $("#reviewText").val();

Those two don't match in my humble opinion.

I would suggest you look into jQuery's .serializeArray() to allow you to construct the request body automatically instead of having to do it manually.

Note that an id attribute value must not contain whitespace (spaces, tabs etc.).

5b). Secondly, you send the <textarea> element value with the request parameter key as reviewText in your jQuery's Ajax request body:

   $.ajax({
    // ...
    data: {
        reviewText: reviewText,
        // ...
    }
    // ... 
   });

Yet in your controller's storeReview(...) method you try accessing it using $request->reviewArea

    public function storeReview(Request $request) { 
    // ...
    if($request->ajax()) {
        // ...
        $review->reviewText = $request->reviewArea;
        // ...
    } }

Those two don't match either. $request->reviewArea will most certainly always return null.

CodePudding user response:

I fixed it .... there was missing '/' in the route.

  •  Tags:  
  • Related