0

Never used ajax before and I'm quite new to Laravel as well. I'm running a function where it gets the information from the form and i have no idea how to do the request with the information that I need.

function myFunction() {
  var x = document.getElementById("frm1");
  //console.log(x.elements.personSearch.value);
var details = x.elements.personSearch.value;
document.getElementById("personValidation").innerHTML = "";

if (
        !details.match(
          /\b[a-zA-Z ]*\\[a-zA-Z ]*\\[0-3][0-9][0-1][0-9][0-9]{4}\b/g
        )
      ) {
        document.getElementById("personValidation").innerHTML =
          "Your search does not match the required format";
        return;
      }
      $.ajax({
        url: "/api/pnc/person",
        type: "POST",
        dataType: "json",
        success:function(amount) {
console.log(amount);
        }
    });
``` Javascript


public function person(Request $request) { $request->validate([ 'search' => 'required' ]);

return "test";

}


inkmoldy
  • 19
  • 2
  • 2
    Hi inkmoldy! I recommend you to read [how to ask a good question](https://stackoverflow.com/questions/71523205/how-to-install-multiple-versions-of-python-in-windows). – Ivanhercaz Jan 20 '23 at 23:52

1 Answers1

0

You need to Follow 3 steps for Ajax Request-

1. Setup Ajax Header bottom of your code. I mean before </html> add below code.

    <script>
                  $.ajaxSetup({
                 headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                           }
                  });
         </script>

2. If you don't use Header Then you can use.

    <script>
        $(document).ready(function () {
              $("#your_form_id").submit(function(e) {
              var details = $('#details_input_id').val();
              if(your_condition){
                $.ajax({
                   url: "api/url",
                   type: "post",
                   data: {"_token": "{{csrf_token()}}", 'details':details},
                   success:function(data){
                              //Your response 
                       if(data){
                           consol.log("Print what you want to print");
                        }
                     }
                });
              }else{
                    alert("Your search does not match the required format")
                }
            });
        });
    </script>

3. Your Route will be like ajax url

    Route::post('api/url', [YourController::class, 'functionName'])->name('functionName');