0

I want to submit this modal form and get the message success without refresh the page.

So I'm using the following code :

the view :

 <x-app-layout>
<div class="container-fluid">
    <div class="row">
        <div class="col app-col">
            <div class="mb-2">
                <h1>Castings</h1>
                <div class="top-right-button-container">
                    <a href="javascript:void(0);"  data-target="#castingmodel" data-toggle="modal" class="btn btn-outline-primary btn-lg top-right-button  mr-1"> Add New </a> 
                    <div class="col-xl-6">
                    <div id="result"></div>
                    </div>
                </div>
                <div class="separator mb-5"></div> 
            </div>
            <div class="modal fade" id="castingmodel" tabindex="-1" role="dialog" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalContentLabel">New message</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <form  method="post" class="needs-validation tooltip-label-right" id="formcast" novalidate enctype="multipart/form-data">
                                 @csrf
                                 <input type="hidden" id="id_hidden" name="id" />
                                 <div class="form-group position-relative error-l-50">
                                    <label>Name</label>
                                    <input type="text" class="form-control" name ="casting_name" id="casting_name" >
                                    <div class="invalid-tooltip">
                                        Name is required!
                                     </div>
                                 </div>
                                 <div class="form-group position-relative error-l-50">
                                     <label>CIN</label>
                                    <input type="text" class="form-control" name="casting_cin" id="casting_cin" required>
                                    <div class="invalid-tooltip">
                                        CIN is required!
                                    </div>
                                </div>
                                <div class="form-group position-relative error-l-50">
                                    <label>EMAIL</label>
                                    <input type="text" class="form-control" rows="2" name="casting_email" required>
                                    <div class="invalid-tooltip">
                                        EMAIL is required!
                                    </div>
                                </div>
                                <div class="form-group position-relative error-l-50">
                                    <label>PHONE</label>
                                    <input type="number" class="form-control" rows="2" name="casting_phone" required>
                                    <div class="invalid-tooltip">
                                        PHONE is required!
                                    </div>
                                </div>
                                <div class="form-group position-relative">
                                    <label>Radio</label>
                                    <div>
                                        <div class="custom-control custom-radio">
                                                <input type="radio" id="jQueryCustomRadio1" name="casting_gender"  class="custom-control-input" required value="homme">
                                            <label class="custom-control-label" for="jQueryCustomRadio1">Homme</label>
                                        </div>
                                            <div class="custom-control custom-radio">
                                                <input type="radio" id="jQueryCustomRadio2" name="casting_gender" class="custom-control-input" required value="femme">
                                            <label class="custom-control-label" for="jQueryCustomRadio2" >Femme</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group position-relative error-l-50">
                                    <label>ADDRESS</label>
                                        <input type="text" class="form-control" rows="2" name="casting_address" required>
                                    <div class="invalid-tooltip">
                                        ADDRESS is required!
                                    </div>
                                </div>
                                <div class="form-group position-relative error-l-50">
                                    <label>CITY</label>
                                        <input type="text" class="form-control" rows="2" name="casting_city" required>
                                    <div class="invalid-tooltip">
                                         CITY is required!
                                    </div>
                                </div>
                                <div class="input-group mb-3">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">Upload</span>
                                    </div>
                                    <div class="custom-file">
                                         <input type="file" name="casting_photo" class="custom-file-input" id="inputGroupFile01">
                                         <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
                                    </div>
                                </div>
                                                                <!-- <div class="form-group position-relative">
                                                               
                                                                <button type="submit" id="submit" name="submit" class="btn btn-primary mb-0">Submit</button>
                                                              </div> -->
                                <button type="submit" id="createBtn" class="btn btn-primary" onclick="createPost()"> Save </button>
                                <div class="result"></div>
                                                           
                            </form>


                                                         
                        </div>
                                                        
                    </div>
                </div> 
                           
            </div>

        </div>

    </div>

     
</div>

script.js

 // Pass csrf token in ajax header
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});


    //----- [ button click function ] ----------

$("#createBtn").click(function(event) {
    event.preventDefault();
    $(".error").remove();
    $(".alert").remove();

   

    var form_data   = $("#formcast").serialize();

        createPost(form_data);

});

// create new post
function createPost(form_data) {
    $.ajax({
        url: 'castings',
        method: 'post',
        data: form_data,
        dataType: 'json',

        beforeSend:function() {
            $("#createBtn").addClass("disabled");
            $("#createBtn").text("Processing..");
        },

        success:function(res) {
            $("#createBtn").removeClass("disabled");
            $("#createBtn").text("Save");

            if(res.status == "success") {
                $(".result").html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
            }

            else if(res.status == "failed") {
                $(".result").html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
            }
        }
    });
}

Controller

 public function store(Request $request)
{

      $file=$request->file('casting_photo');

     if($file->isValid())
     {
        $destinationPath='castingimage/';
        $image=date('YmdHis').'.'.$file->getClientOriginalExtension();
        $file->move($destinationPath,$image);
     }

      $cast = new Casting;

$cast -> casting_name= $request->input('casting_name');
$cast -> casting_cin= $request->input('casting_cin');
$cast -> casting_email= $request->input('casting_email');
$cast -> casting_phone= $request->input('casting_phone');  
$cast -> casting_gender= $request->input('casting_gender');
$cast -> casting_address= $request->input('casting_address');
$cast -> casting_city= $request->input('casting_city');
$cast-> casting_photo=$image;

  $cast->save();

    
  if(!is_null($cast)) {
        return response()->json(["status" => "success", "message" => "Success! post created.", "data" => $cast]);
   }

   else {
       return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
   }

}

When I execute my code I get this page which contains the data inserted enter image description here

And when I check the console I get this error :

    Access to XMLHttpRequest at 'javascript:void(0);' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
javascript:void(0); Failed to load resource: net::ERR_FAILED

I'm sticking with this error, I don't know what is the problem

Edit

app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>

    <meta charset="UTF-8">
    <title>Casting/Influenceurs</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}" />

    <link rel="stylesheet" href="font/iconsmind-s/css/iconsminds.css" />
    <link rel="stylesheet" href="font/simple-line-icons/css/simple-line-icons.css" />
      <link rel="stylesheet" href="css/vendor/bootstrap.min.css" />
    <link rel="stylesheet" href="css/vendor/bootstrap.rtl.only.min.css" />
    <link rel="stylesheet" href="css/vendor/fullcalendar.min.css" />
    <link rel="stylesheet" href="css/vendor/dataTables.bootstrap4.min.css" />
    <link rel="stylesheet" href="css/vendor/datatables.responsive.bootstrap4.min.css" />
    <link rel="stylesheet" href="css/vendor/select2.min.css" />
    <link rel="stylesheet" href="css/vendor/perfect-scrollbar.css" />
    <link rel="stylesheet" href="css/vendor/glide.core.min.css" />
    <link rel="stylesheet" href="css/vendor/bootstrap-stars.css" />
    <link rel="stylesheet" href="css/vendor/nouislider.min.css" />
    <link rel="stylesheet" href="css/vendor/bootstrap-datepicker3.min.css" />
    <link rel="stylesheet" href="css/vendor/component-custom-switch.min.css" />
    <link rel="stylesheet" href="css/main.css" />
    </head>
 
    <body id="app-container" class="menu-default show-spinner">


            @include('layouts.navigation2')

            <main>
                {{ $slot }}
            </main> 


    <script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
    

     <script src="{{asset('js/script.js')}}"></script>
    
    <script src="js/vendor/jquery-3.3.1.min.js"></script> -->
    <script src="js/vendor/bootstrap.bundle.min.js"></script>
    <script src="js/vendor/Chart.bundle.min.js"></script>
    <script src="js/vendor/chartjs-plugin-datalabels.js"></script>
    <script src="js/vendor/moment.min.js"></script>
    <script src="js/vendor/fullcalendar.min.js"></script>
    <script src="js/vendor/datatables.min.js"></script>
    <script src="js/vendor/perfect-scrollbar.min.js"></script>
    <script src="js/vendor/progressbar.min.js"></script>
    <script src="js/vendor/jquery.barrating.min.js"></script>
    <script src="js/vendor/select2.full.js"></script>
    <script src="js/vendor/nouislider.min.js"></script>
    <script src="js/vendor/bootstrap-datepicker.js"></script>
    <script src="js/vendor/Sortable.js"></script>
    <script src="js/vendor/mousetrap.min.js"></script>
    <script src="js/vendor/glide.min.js"></script>
    <script src="js/dore.script.js"></script>
    <script src="js/scripts.js"></script>
    <script src="js/vendor/jquery.contextMenu.min.js"></script> 
    <script src="js/vendor/bootstrap-notify.min.js"></script>
    <script src="js/vendor/jquery.validate/jquery.validate.min.js"></script>
    <script src="js/vendor/jquery.validate/additional-methods.min.js"></script>
    <script src="js/vendor/bootstrap-tagsinput.min.js"></script>
   
     
    </body>

 
   
</html>
  • Is the url param (’castings’) of your ajax configuration object correct? – Luckyfella May 25 '21 at 21:26
  • yes it is correct – user14053977 May 25 '21 at 21:44
  • Doesn’t it have to be an url? I thought the value of an url parameter has to be a valid network address. Just wondering :) – Luckyfella May 25 '21 at 21:48
  • I think the fact we're seeing "javascript:void(0)" in your console shows something going wrong with your event handlers. Regardless, you shouldn't have that in your code at all. If you must use an `` element, set the `href` attribute to "#". But you really should be using a ` – miken32 May 25 '21 at 22:11
  • And why do you have `onclick` on the form submit button? – miken32 May 25 '21 at 22:15
  • You can disable cors for development temporarily : https://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome or try with header - Access-Control-Allow-Origin: * – Arun Verma May 26 '21 at 07:22
  • Can you describe where your ajax call is supposed to be handled? I guess you have a laravel conroller/route responsible to handle the ajax call? As long as you don't have unexpected magic going on, the ajax url of "casting" will lead the request to nowhere. Your error says: `Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.` you have just a string there that is meaningless for the browser. It is cross origin because your script runs over `http://127.0.0.1:8000` and your ajax call not. – Luckyfella May 26 '21 at 10:24

1 Answers1

0

I do not know the Laravel framework but I do know PHP, HTML, jQuery and Bootstrap. First, you have both a button that is of type "submit" and an "onclick" in the same button. Both of these are not needed and there are multiple ways to accomplish submitting a form via jQuery. I have adjusted your view below to use the ".submit" handler.

Your View - The changes made were code cleanup for better readability and removed "onclick" from Submit button. I also removed the "@csrf" since I am not sure why that is there.

<x-app-layout>
<div class="container-fluid">
  <div class="row">
    <div class="col app-col">
      <div class="mb-2">
        <h1>Castings</h1>

        <div class="top-right-button-container">
          <a href="javascript:void(0);"  data-target="#castingmodel" data-toggle="modal" class="btn btn-outline-primary btn-lg top-right-button  mr-1"> Add New </a> 

          <div class="col-xl-6">
            <div id="result"></div>
          </div>
        </div>
        <div class="separator mb-5"></div>
      </div>
      <div class="modal fade" id="castingmodel" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalContentLabel">New message</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
              <form method="post" class="needs-validation tooltip-label-right" id="formcast" novalidate enctype="multipart/form-data">
                <input type="hidden" id="id_hidden" name="id" />

                <div class="form-group position-relative error-l-50">
                  <label>Name</label>
                  <input type="text" class="form-control" name ="casting_name" id="casting_name" >
                  <div class="invalid-tooltip">Name is required!</div>
                </div>
                <div class="form-group position-relative error-l-50">
                  <label>CIN</label>
                  <input type="text" class="form-control" name="casting_cin" id="casting_cin" required>
                  <div class="invalid-tooltip">CIN is required!</div>
                </div>
                <div class="form-group position-relative error-l-50">
                  <label>EMAIL</label>
                  <input type="text" class="form-control" rows="2" name="casting_email" required>
                  <div class="invalid-tooltip">EMAIL is required!</div>
                </div>
                <div class="form-group position-relative error-l-50">
                  <label>PHONE</label>
                  <input type="number" class="form-control" rows="2" name="casting_phone" required>
                  <div class="invalid-tooltip">PHONE is required!</div>
                </div>
                <div class="form-group position-relative">
                  <label>Radio</label>
                  <div>
                    <div class="custom-control custom-radio">
                      <input type="radio" id="jQueryCustomRadio1" name="casting_gender"  class="custom-control-input" required value="homme">
                      <label class="custom-control-label" for="jQueryCustomRadio1">Homme</label>
                    </div>
                    <div class="custom-control custom-radio">
                      <input type="radio" id="jQueryCustomRadio2" name="casting_gender" class="custom-control-input" required value="femme">
                      <label class="custom-control-label" for="jQueryCustomRadio2" >Femme</label>
                    </div>
                  </div>
                </div>
                <div class="form-group position-relative error-l-50">
                  <label>ADDRESS</label>
                  <input type="text" class="form-control" rows="2" name="casting_address" required>
                  <div class="invalid-tooltip">ADDRESS is required!</div>
                </div>
                <div class="form-group position-relative error-l-50">
                  <label>CITY</label>
                  <input type="text" class="form-control" rows="2" name="casting_city" required>
                  <div class="invalid-tooltip">CITY is required!</div>
                </div>
                <div class="input-group mb-3">
                  <div class="input-group-prepend">
                    <span class="input-group-text">Upload</span>
                  </div>
                  <div class="custom-file">
                    <input type="file" name="casting_photo" class="custom-file-input" id="inputGroupFile01">
                    <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
                  </div>
                </div>

                <button type="submit" id="createBtn" class="btn btn-primary">Save</button>

                <div class="result"></div>
              </form>
            </div>
          </div>
        </div> 
      </div>
    </div>
  </div>
</div>

For your Javascript / jQuery, the only thing changed was from ".click" to ".submit":

// Pass csrf token in ajax header
$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

//----- [ button click function ] ----------
$("#formcast").submit(function(event) {
  event.preventDefault();

  $(".error").remove();
  $(".alert").remove();

  var form_data = $("#formcast").serialize();

  createPost(form_data);
});

// create new post
function createPost(form_data) {
  $.ajax({
    url: 'castings',
    method: 'post',
    data: form_data,
    dataType: 'json',
    beforeSend:function() {
      $("#createBtn").addClass("disabled");
      $("#createBtn").text("Processing..");
    },
    success:function(res) {
      $("#createBtn").removeClass("disabled");
      $("#createBtn").text("Save");

      if(res.status == "success") {
        $(".result").html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
      } else if(res.status == "failed") {
        $(".result").html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
      }
    }
  });
}

And for your PHP, I just cleaned it up since I do not know Laravel:

public function store(Request $request) {
  $file = $request->file('casting_photo');

  if($file->isValid()) {
    $destinationPath='castingimage/';
    $image=date('YmdHis').'.'.$file->getClientOriginalExtension();
    $file->move($destinationPath,$image);
  }

  $cast = new Casting;
  $cast->casting_name = $request->input('casting_name');
  $cast->casting_cin = $request->input('casting_cin');
  $cast->casting_email = $request->input('casting_email');
  $cast->casting_phone = $request->input('casting_phone');  
  $cast->casting_gender = $request->input('casting_gender');
  $cast->casting_address = $request->input('casting_address');
  $cast->casting_city = $request->input('casting_city');
  $cast->casting_photo=$image;
  $cast->save();

  if(!is_null($cast)) {
    return response()->json(["status" => "success", "message" => "Success! post created.", "data" => $cast]);
  } else {
    return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
  }
}

As for the error that you originally reported, it looks to me like your primary problem is with CORS. I am not sure what software you're using to do your testing but it appears to be local so I would assume something like WAMP. I would do some additional searching to ensure that WAMP has CORS support enabled and all requests are accepted. This article might help: Enable CORS with wamp on windows 8

From there, you want to make sure that your PHP function is returning a "200" response if the request was successful. Your Javascript/jQuery will be looking for this response status code.

recoilnetworks
  • 401
  • 2
  • 5
  • 16