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,
));
}
Change your ajax type to POST, because your route type is POST, not GET.
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.
Related
my problem is while posting multiple forms with ajax in laravel, I am sending the form data without any problem, but I cannot send the file.
File is empty error. I've been dealing with this for 2 days, there is no method I haven't tried, please help me.
Apart from that, I added multipart to the form, but it still didn't work, I'm sharing my codes with you.
Sorry for my bad english.
I want it to upload 2 photos in the normal 4th form until the createProduct3 form, I tried to get them by doing the normal new formData() and I tried otherwise and I couldn't succeed.
It sends it to Laravel server side as [Object File].
My Form
<form class="form" id="createProduct4" method="POST" action="">
<input type="file" class="upload-box-title" id="urun-fotografi" name="urun_fotografi" value="Fotoğraf Seç">
<input type="file" class="upload-box-title" id="urun-dosyasi" name="urun_dosyasi" value="Dosya Seç">
</form>
My blade ajax:
function createProducts()
{
var dataString = $("#createProduct1, #createProduct2, #createProduct3, #createProduct4").serialize();
let photo = document.getElementById("urun-dosyasi").files[0];
let photo2 = document.getElementById("urun-fotografi").files[0];
console.log(photo,photo2);
$.ajax({
url: "{{ route('user.product.create') }}",
type: "POST",
data: dataString+"&urun_dosyasi="+photo+"&urun_fotografi="+photo2,
success: function( data ) {
},
error: function(xhr)
{
console.log(xhr);
}
});
}
Server Function
public function createProduct(Request $request)
{
$file = $request->file('urun_dosyasi');
$file2 = $request->file('urun_fotografi');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$filename2 = $file2->getClientOriginalName();
$extension2 = $file2->getClientOriginalExtension();
echo $filename,$extension."2. doc: ".$filename2.$extension;
}
Use multipart/form-data when your form includes any <input type="file"> elements :
<form ... enctype="multipart/form-data">
Ajax :
var form = $('#createProduct4')[0];
var data = new FormData(form);
$.ajax({
url: "{{ route('user.product.create') }}",
type: "POST",
enctype: 'multipart/form-data',
data: data,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
im trying to submit an ajax post in laravel but im having some problem regarding the form's csrf token. In my form, if the conditions i set in my ajax post url has been met the first time the form has been submitted. However if i submit the form and purposely failed the conditions i set in my ajax post url in the first try, If i submit the form again i get a token mismatch exception in my ajax error log. Do i need to refresh the csrf_token every ajax post?
Below is my code
JS
$(document).on('submit','.registration-form',function(e){
e.preventDefault();
var form = $(this);
var form_url = $(this).attr("action");
var form_values = $(this).serialize();
$.ajax({
url:form_url,
type:'POST',
data:form_values,
dataType: 'json',
async:false,
success: function(result){
console.log(result);
if(result['status']==true){
location.href = result['redirect'];
}
else{
form.find(".form-details").show().html(result['message']);
}
},
error: function(ts) {
console.log(ts.responseText)
}
});
});
HTML
<form action="{{ url('login') }}" method="POST" class="registration-form">
{{ csrf_field() }}
<input type="text" name="username" class="input" placeholder="Email">
<input type="password" name="password" class="input" placeholder="Password">
<button class="button is-redbox is-flat is-fullwidth">Login</button>
</form>
Are u sure that each time that is send in ajax?
data: {
"_token": "{{ csrf_token() }}",
}
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
public function regenerateToken(){
session()->regenerate();
return response()->json([
'msg'=>'success',
'token'=>csrf_token()
]);
}
$('#form').submit(funtion(event) {
event.preventDefault(event);
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
if (response.msg === 'success') {
$('#token').val(response.token);
console.log($('#token').val());
}
}
$('input[type="text"],input[type="email"] ,textarea, select').val(''); $(this).trigger('reset');
});
I'm simply trying to pass a text input and a file to Java but without success.
The formData seems to be working because I read the formData elements and all seems to be there. I just can't pass it to Java.
HTTP Status 500 - Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request
HTML
<form id="creationForm" method="get" enctype="multipart/form-data">
<input id="testName" class="form-control" name="testName">
<input type="file" name="fileUpload" id="fileUpload"/>
</form>
JavaScript
$(document).ready(function () {
var files = [];
$('#fileUpload').change(function (event) {
files = event.target.files;
});
$('#btnSubmit').click(function (e) {
e.preventDefault();
var formData = new FormData(document.getElementById('creationForm'));
console.log(files[0]);
$.ajax({
type: 'get',
url: '/upload/testCase',
data: formData,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function (result) {
},
error: function () {
}
});
});
});
Java
#RequestMapping(value = "/upload/testCase", method = RequestMethod.GET)
public #ResponseBody void uploadTestCase(#RequestParam("fileUpload") MultipartFile file ) {
//TestCases.upload(file);
System.out.println(file);
}
Spring XML included bean
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
I guess you're using the wrong http-method. Try to use post instead of get? That might solve it.
Spring:
#RequestMapping(value = "/upload/testCase" , method = RequestMethod.POST)
JQuery:
$.ajax({
type: 'post',
...
...
)};
According to https://spring.io/guides/gs/uploading-files/, this is the way your form should be defined to upload a file:
HTML
<form id="creationForm" method="POST" enctype="multipart/form-data" action="/upload/testCase">
<input id="fileName" class="form-control" name="name">
<input id="fileUpload" type="file" name="fileUpload"/>
<button class="form-control">Submit</button>
</form>
Java
#PostMapping("/upload/testCase")
public void uploadTestCase(#RequestParam("fileUpload") MultipartFile file) {
System.out.println(file);
}
In theory, you shouldn't need Javascript code for that.
But maybe you don't want the form to directly post your data, do you?
My form:
<form class="form-inline signup" action="php/signupForm.php" role="form" id="signupForm">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<button type="submit" class="btn btn-theme ladda-button" data-style="expand-left">
<span class="ladda-label" id="notice">Get notified!</span>
</button>
</div>
</form>
the end of my php script
$response = array(
"status" => $status,
"message" => $message
);
echo json_encode($response);
My page is receiving data like:
{"status":0,"message":"This email is already on list!"}
using JS I need to parse that data and then update text within an element.
<span id="notice">Get notified!</span>
here's my script which doesn't work, after senging form data to my php script I get a white screen that shows the json strong
$(document).ready(function() {
$.ajax({
dataType: 'json',
$('#notice').text(data.message);
});
});
You have to handle the response in a callback.
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
data: $(this).serialize(),
url: $(this).attr('action'), // Or the path of the PHP file
dataType: 'json',
}).done(function(response) {
$('#notice').text(response.message);
});
});
});
See the related docs here
That ajax call is not well formed, missing success callback and url e.g:
$(document).ready(function () {
$.ajax({
url: '/the/url/where/your/data/comes/from/',
dataType: 'json',
success: function (data) {
$('#notice').text(data.message);
}
});
});
Your code as is, is just executing at page load and not on submission of a form. You need to attach an onsubmit event, prevent the default action of doing the form submit and do your ajax call in there. Also your ajax call itself was malformed
$("#yourFormID").submit(function(e){
e.preventDefault();
$.ajax({
url:"/urlToServerScript",
data:{} //any form data the script needs you should be put here,
dataType:"json" //type of response the server will output
}).then(function(data){
$('#notice').text(data.message);
});
});
.Hello y'all. I'm trying to learn ajax and am currently trying to have an input in a form be sent via a route to a controller and then echoed in a div.
For some reason I am getting a NotFoundHttpException error when I press the submit button for the form and am having trouble seeing what is wrong with my route.
If anyone can point out where I'm going wrong it would be greatly appreciated! Thank you!
View:
<form id="edit_price_form" method="POST" action="">
<input name="new_price" id="new_price"/>
<input type='submit' class='button tiny radius' id='edit_price_button'/>
</form>
Ajax request:
$(document).ready(function(){
$("#edit_price_form").submit(function(e) {
e.preventDefault();
//form_data
var form_data = $('#edit_price_form').serializeArray();
$.ajax({
url: 'edit_prices',
type: "POST",
dataType: "html",
data: form_data,
success: function(data){
$("#edit_results").html(data);
$("#edit_results").addClass('panel callout radius');
},
error: function(xhr, status, error){
console.log(xhr);
console.log(status);
console.log(error);
}
});
});
});
Route:
/*Ajax Edit Price on Price Page*/
Route::post('edit_prices', array(
'as' => 'edit_prices',
'uses' => 'PriceController#edit_prices'
));
Controller:
public function edit_prices(){
$new_price = Input::get('new_price');
echo $new_price;
}
Thanks again!
The problem lies in your HTTP method. You're AJAX request looks like this:
$.ajax({
url: 'edit_prices',
type: "PUT",
...
But your route looks like this:
Route::post('edit_prices', array(
'as' => 'edit_prices',
'uses' => 'PriceController#edit_prices'
));
In short, you'll need to change your AJAX request from PUT to POST - Laravel is rejecting the PUT request because it's expecting POST.