I'm working on a laravel web app, I'm relatively new to laravel so I'm not very familiar with the ajax tokens and such, but I believe I have set it up correctly.
Below is my Ajax code for a test page that I want to try and send data from.
<meta name="csrf-token" content="{{ csrf_token() }}">
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#btn').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'testSend',
data: {
test: 'hello'
},
dataType: 'json',
success: function (response) {
alert(response);
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
Here is my form:
<div class="flex-center position-ref full-height">
<div class="content">
<form action="testSend" method="post" enctype="multipart/form-data">
<button type="submit" id="btn"> submit</button>
</form>
</div>
And here is a simple route that I have setup just to test this:
Route::post('testSend', function (Request $request) {
return response()->json($request);
});
However when I go to check the network in chrome, the JSON Object is empty.
The empty JSON Object:
I'm pretty new to this, I have learned it but never really tried to create a web app until now. I have searched everywhere, but no one seemed to have the same problem, maybe they did but I just don't know.
The problem might just be a dumb mistake, but I really can't figure it out ):
Thanks.
Rather than passing Request instance try this:
return response()->json($request->all());
Related
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.
For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.
My form is something like this:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
and my jQuery script for getting the form value is something like this:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
But this returns all the field values except image one, in case of image is return null.
How do I store in the dataarray?
I want to store so I can send the value to the server through the AJAX.
For uploading single image its like this
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
For multiple images u will have to loop its kinda different
I have found a similar question, hope it will help you.
Upload image using jquery
Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
and then include all required jQuery files:
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
try this code, it's work for me.
$("form").submit(function (event) {
var form_data = new FormData($(this));
$.ajax({
url : url,
type : 'POST',
data : form_data,
processData: false, // tell jQuery not to process the data
contentType: false,
success : function(resp){
}
});
});
Try this code. using formData()
$("form").submit(function (event) {
var formData = new FormData($(this));
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
//success callback
},
cache: false,
contentType: false,
processData: false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
your Html
<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
AJAX call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
}
});
});
});
</script>
upload_image.php
print_r($_FILES) //check you get file data or not
Try this way.Hope it will help you
Please check the follow the code, which i am using to upload image.
$.ajax({
url: UPLOADURL, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false,// To unable request pages to be cached
processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data)// A function to be called if request succeeds
{
data = JSON.parse(data);
console.log(data);
if(data.status == "Success"){
attachmentListing();
//$("#mailerMessage").html(data.data.mailStatus);
//$("#mailerMessage").fadeIn();
setTimeout(function () {
$("#mailerMessage").fadeOut();
},5000);
}else{
toastr.warning(data.status);
}
$("#ajaxloader").addClass("hideajaxLoader");
},
error: function (jqXHR, errdata, errorThrown) {
log("error");
$("#ajaxloader").addClass("hideajaxLoader");
}
});
I am new to Laravel and am using Laravel 5.3. I want to make a text field where it will automatically suggest some data and when I select a data it will add it to an array. I want to send that array to a controller for further use. For this the
view file is as follows:
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
var members = {!! json_encode($member) !!};
console.log(members);
var arr = [];
$("#tags").autocomplete({
source: members,
select: function (event, ui) {
arr.push(ui);
console.log(arr);
}
});
$("#submit").click(function(event){
$.ajax({
type: "POST",
url: '/storeresearch',
data: {selectedMembers: arr},
success: function( msg ) {
console.log(msg);
}
});
});
});
</script>
</head>
<body>
<form id="hu" action="/storeresearch" method="POST">
{!! csrf_field() !!}
<label>Research Author</label>
<input type="text" id="tags" name="researchsupervisor_1" value="">
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="Add">
</form>
</body>
My Controller file is as follows:
public function store(Request $request){
if($request->ajax())
{
$mem = $request->all();
return response()->json($mem,200) ;
}
else{
return "not found";
}
And web.php is as followings:
Route::post('/storeresearch','ResearchController#store');
But it seems that there is no ajax call happening. In the controller it always enters the else section. What is the problem can anyone help?
Your code mostly looks good. But you are missing to send a csrf token with AJAX call as you are using POST request.
You can send csrf token with AJAX call in this way:
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
More info: https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token
When you hit the button, does it really fires an AJAX call? Please check that on network tab of browser.
I solved this problem by doing following
$.ajax({
type:'POST',
url:'your url',
data:{_token: "{{ csrf_token() }}"
},
success: function( msg ) {
}
});
Try some thing like this:
$.ajax({
url : '/login',
method : 'post',
data : {
login_username : userName,
password : password
},
headers:
{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success : function(response){
}
});
Route:
Route::post('/login',[
'uses' => 'AdminServiceController#login'
]);
Controller method:
public function login()
{
$userName = INPUT::get('login_username');
$password = INPUT::get('password');
// your logic
}
What's your namespace declaration for Request ?
If it is use Illuminate\Http\Request; try use Request;
Before marking it as duplicated, i tried the other solutions found on the web, including SO, and none of them solved my issue.
I'm using x-editable plugin to store a new record using a store route.
When the form is submitted, i get a 500 with TokenMismatchException error.
I know about setting the csrf token thing, but i tried it in several ways, and nothing is working.
That's my javascript code:
$.fn.editable.defaults.params = function (params) {
params._token = window.Laravel.csrfToken;
return params;
};
$('.editable').each(function () {
$(this).editable();
});
The html
<head>
[...]
<meta name="csrf-token" content="{{ csrf_token() }}">
[...]
<script>
window.Laravel = <?php
echo json_encode([
'csrfToken' => csrf_token(),
]);
?>
</script>
[...]
</head>
<button id="note-asl-text"
data-type="textarea"
data-placeholder="Aggiungi Nota"
data-url="{{route('ricettanota.store')}}"
data-title="Inserisci una nuova nota"
data-highlight="false"
data-mode="inline"
data-send="always"
data-showbuttons="bottom"
class="editable"
>Aggiungi nota</button>
The Route
Route::resource('ricettanota', 'RicettaNotaController');
I already tried all possible combinations of the following:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': window.Laravel.csrfToken
}
});
$('.editable').each(function () {
$(this).editable({
ajaxOptions: {contentType: 'application/json', dataType: 'json'},
params: function (params) {
params._token = window.Laravel.csrfToken;
return JSON.stringify(params);
}
});
});
note
$('meta[name="csrf-token"]').attr('content') and window.Laravel.csrfToken are the same
update
I found out that placing Route::resource('ricettanota', 'RicettaNotaController'); into the api routes file(api.php) causes the issue, while placing the routes into the web routes file (web.php) and using the code above works.
Why using the API i get token mismatch, is still a mystery.
Not sure if this is what you are looking for, but maybe you should not struggling in sending custom header with x-editable plugin, but sending custom parameters.
The following code works for me.
$(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.node').editable(
{
params: function(params) {
var data = {};
data['_csrf_token'] = $(this).data("csrf");
return data;
},
}
);
});
Set csrf in your a-tag or somewhere else you like.
<a href="#" ... data-csrf="xxxxxxx" /a>
Hope this helps.
try this in your ajaxSetup
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
I also faced same issue in Laravel 5.8. Following code worked for me.
$.fn.editable.defaults.ajaxOptions = {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
};
this is use code
$.ajax({
type: 'POST',
url: url,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType:'html',
data:data,
success:function(data){
}});
this Follow link
https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token
I'm trying to get some information from my php code when clicking on a button, but it doesn't connect to php.
front page is displayed in index.php
index.php:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="functions.js"></script>
<title>Account Panel</title>
</head>
<div "getInfos">
<h2>In this section you can get your inforrmation</h2>
<button id="getNameBtn">Get Your Name!</button>
<span id="getNameSpan"> something must come here</span>
</div>
</body>
</html>
javascript codes and ajax are in
functions.js:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
and php in serverside is some simple thing like this:
handler.php:
<?php
echo('Ajax successful!');
?>
You have not close the document ready function:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
data:JSON.stringify({taskid = 1}),
shoulde be
data:JSON.stringify({taskid: 1}),
First of all, you should better use a newer jquery version.
There is at least one error in your Code:
data:JSON.stringify({taskid = 1})
The json should read
{taskid : 1}
Use a colon, not an equal sign. Not sure that it is true for your jQuery version, but usually data can be attached as json object already, so the whole line should work so:
data: {taskid : 1},
And the data is then visible as POST data in the PHP page. Note that the live() function is deprecated since 1.7. You can use
$("#getNameBtn").click(function(){...});
instead. Moreover, I don't think you need the headers in your request.
First important change you need to do, use $.on instead of $.live, since the latter is deprecated. Another thing you should check, if the handler.php file is at the same level as your JS/HTML file. It could be that the file is not reachable from your code. Here is what you can try:
$(document).ready(function(){
$("#getNameBtn").on('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data: { call: 'myAjax', taskid : 1 },
headers: {
'content-type': 'application/json'
},
success: function(response) {
$('#getNameSpan').html(response);
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
And in the PHP file, you can check for the call key:
<?php
if(isset($_POST) && $_POST['call'] == 'myAjax') {
echo $_POST['taskid'];
exit;
}
?>
That exit is really important.
In your PHP file that returns JSON you should also set the header to JSON.
header("Content-Type: application/json"); //Above all HTML and returns
And the true answer to your problem has already been answered.