0

I want to pass data from controller to jquery using json don't know where is the problem but fro the jquery code I think its working fine as I tested the success code but can't get back the result from controller

home.blade

    <form role="form" name="form_address" id="form_address" action="" method="POST"  enctype="multipart/form-data">
     {{ csrf_field() }}
  <input type="text" id="postal_code" onFocus="geolocate()">
  <input type="text" id="totaldistance"  onFocus="geolocate()">
 </form>
  <button id="save_address">Save</button>
 <script>
$("#save_address").click(function (e) {
$.ajaxSetup({
    headers: {
         'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
    }
   });

   e.preventDefault();
  var form = document.forms.namedItem("form_address");
  var formData = new FormData(form); 
  $.ajax({
     type: "get",
    url: 'Get_distance',
    contentType: false,
    data: formData, 
    processData: false,
    success: function(data) {
      $('#totaldistance').val(data.distance); 
    }
   });
  });

web.php

Route::post('Get_distance','HomeController@getdistance');

controller

public function getdistance(Request $request)
{
  $distance =$request->postal_code;

  return Response::json(array(
    'distance' => $distance,  
  ));
}
7
  • Did you get an error message on ajax error callback? Commented Jun 26, 2018 at 15:15
  • @JustinusHermawan localhost/crisp/public/Get_distance?[object%20FormData] 500 (Internal Server Error) Commented Jun 26, 2018 at 15:19
  • Click it from devtools and see what kind of error Laravel returns to you. And put name="postal_code" on your <input type="text" id="postal_code" onFocus="geolocate()"> tag. Commented Jun 26, 2018 at 15:21
  • even if i added in controller $distance='gg'; I will not get a result and dont know how to use divtool Commented Jun 26, 2018 at 15:27
  • 1
    Change your ajax type to "POST", because your route type is POST not GET. Commented Jun 26, 2018 at 15:35

2 Answers 2

2

Change your ajax type to POST, because your route type is POST, not GET.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you but its not about post or get now it works with get now
0

Your defined route in web.php is a POST request, but your Ajax method is set to GET request. Change web.php to a GET request for it to work. Make sure to provide an error function to catch any errors from server side.

Or vice versa, change Ajax request to POST since you already added the csrf setup.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.