1

I am trying to insert data to database through Ajax And Laravel. But when I click the submit button, nothing happens at all. I tried to see if the javascript is reachable at the first using "Alert" and yes it is. But the part of $ajax is not reachable at all.

Here is the code:

Html:

  <div class="form-group">
    <input type="hidden" name="_token" id="csrf" value="{{Session::token()}}">
    <label for="email">Name:</label>
    <input type="text" class="form-control" id="name" placeholder="Enter Name" name="name">
  </div>
  <div class="form-group">
    <label for="email">Email:</label>
    <input type="email" class="form-control" id="email" placeholder="Enter Email" 
   name="email">
  </div>
  <div class="form-group">
       <label for="email">Phone:</label>
        <input type="text" class="form-control" id="phone" placeholder="Enter Phone" 
        name="phone">
  </div>
   <div class="form-group">
      <label for="email">City:</label>
      <input type="text" class="form-control" id="city" placeholder="Enter City" name="city">
    </div>
   <button type="submit" class="btn btn-primary" id="butsave">Submit</button>
   </div>

Javascript:

$(document).ready(function() {

$('#butsave').on('click', function() {
    alert("hello");
  var name = $('#name').val();
  var email = $('#email').val();
  var phone = $('#phone').val();
  var city = $('#city').val();
  var password = $('#password').val();
  if(name!="" && email!="" && phone!="" && city!=""){
    /*  $("#butsave").attr("disabled", "disabled"); */
      $.ajax({
          url: "/userData",
          type: "POST",
          data: {
              _token: $("#csrf").val(),
              type: 1,
              name: name,
              email: email,
              phone: phone,
              city: city
          },
          cache: false,
          success: function(dataResult){
              console.log(dataResult);
              var dataResult = JSON.parse(dataResult);
              if(dataResult.statusCode==200){
                window.location = "/userData";              
              }
              else if(dataResult.statusCode==201){
                 alert("Error occured !");
              }
              
          }
      });
  }
  else{
      alert('Please fill all the field !');
  }
   });
   });

for the controller code:

 public function create()
     {
    return view('userData');
     }
  
 public function store(Request $request)
  {
    $request->validate([
        'name' => 'required',
        'email' => 'required',
    ]);
    UserData::create($request->all());
    return json_encode(array(
        "statusCode"=>200
    ));
   }

The browser debugging shows this error:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

7
  • 2
    Check your browser's debugging tools. Are there any errors on the console? On the network tab, is the AJAX request made? What is the server's response? In the script debugger, when you place breakpoints to step through functions, what specifically happens? Commented Jul 27, 2022 at 16:20
  • The HTML shown above has a spare closing div tag at the end...The AJAX request works fine as tested in a snippet so the problem must lie in the PHP Commented Jul 27, 2022 at 16:25
  • can you provide the route? Is it a get or post request? This can be many things including a bad middleware call, we need more info on this. Commented Jul 27, 2022 at 16:29
  • Welcome to SO ... check your server logs to see what is causing the 500 error Commented Jul 27, 2022 at 17:06
  • The GET method is not supported for this route. Supported methods: POST. This is what is shown what I clicked the error. The problem is that I am actually using POST method... Commented Jul 27, 2022 at 17:09

3 Answers 3

1

Try this one...

First of all set meta tag in your blade file's html head tag.

<head>
  <meta name="csrf-token" content="{{ csrf_token() }}">
</head>

Define ROUTES like this

Route::get('/userData', [YourControllerHere::class, 'create'])->name('userData.get');
Route::post('/userData', [YourControllerHere::class, 'store'])->name('userData.post');

Then change your button type if you are not using FORM to submit the data.

<button type="button" class="btn btn-primary" id="butsave">Submit</button>

Then add this script.

<script>
  $(document).ready(function () {
    var getUserDataUrl = {!! route('userData.get') !!};
    var postUserDataUrl = {!! route('userData.post')!!};
    $('#butsave').on('click', function () {
      alert("click");
      var csrf_token = $('meta[name="csrf-token"]').attr('content');
      var name = $('#name').val();
      var email = $('#email').val();
      var phone = $('#phone').val();
      var city = $('#city').val();
      var password = $('#password').val();
      if (name != "" && email != "" && phone != "" && city != "") {
        $.ajax({
          url: postUserDataUrl,
          type: "POST",
          data: {
            _token: csrf_token,
            type: 1,
            name: name,
            email: email,
            phone: phone,
            city: city
          },
          cache: false,
          success: function (dataResult) {
            console.log(dataResult); // to view your response from controller in webbrowser's console
            if (dataResult.statusCode == 200) {
              window.location.href = getUserDataUrl; // if you want to show console data comment this line
            }
            else if (dataResult.statusCode == 400) {
              alert("Error occured!");
            }
          }
        });
      } else {
        alert('Please fill all the field !');
      }
    });
  });
</script>

Now change your controller's store function.

public function store(Request $request) {
  $request -> validate([
    'name' => 'required',
    'email' => 'required',
  ]);
  $userObj = UserData::create($request->all()); 
  //the create method only create user in database when there are fileds match in UserData model and request->all() otherwise you have to manipulate request data
  $data = [];
  if(!empty($userObj)){
    $data['statusCode'] = 200;
    $data['userObj'] = $userObj;
  } else {
    $data['statusCode'] = 400;
  }
  return response()->json($data);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can try this method. It always works for me.

Step 1: Add a meta tag for CSRF

<meta name="csrf" content="{{ csrf_token() }}" />

Step 2: Create a route:

Route::post('/userData', [ControllerHere::class, 'store'])->name('userData');

Step 3: Run the ajax request:

var csrf_token = $("meta[name='csrf']").attr('content');

var name = $('#name').val();
var email = $('#email').val();

$.ajax({
    url: '/userData',
    type: 'POST',
    data: {
        _token: csrf_token,
        name: name,
        email:email
    },
    success: function(res)
    {
        console.log(res);
    }
})

Step 4: Check controller:

public function store(Request $request)
{
    return $request;
}

Check your browser console for the response. I hope it will help!

Comments

0

First remove type submit and replace type button to prevent page refresh,

<button type="button" class="btn btn-primary" id="butsave">Submit</button>

And place your JavaScript code inside the same blade file between <script> </script> tags.

For better,

Give your route a name like this,

Route::post('/userData', [ControllerHere::class, 'method_name_here'])->name('userData');

After that change your ajax request url to something like this,

$.ajax({
    url: '{{ 'userData' }}', //put your route name here

1 Comment

Thank you for your reply, still nothing happening :(

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.