Info: I don't use Laravel.
In a post on stack I saw how you can protect yourself against CSFR .
Unfortunately, this contribution only related to a Laravel application and I'm not sure whether I can integrate it into my code just like that without using Laravel and if not whether there is another way to elegantly protect myself from CSFR ?
I'm not quite sure if it even makes a different using Laravel or not. Here is my code:
<head>
<title>Newsletter</title>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}"> // copied form the post
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajaxSetup({ // copied form the post start here
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
}); // copied form the post end here
$("#newsletter-form").submit(function(event) {
event.preventDefault();
var thisemail = $("#newsletter-email").val();
var thisdatenschutz = $("#newsletter-datenschutz").val();
var thissubmit = $("#newsletter-submit").val();
$.ajax({
type: "POST",
url: "submitemail.php",
data: {
email: thisemail,
datenschutz: thisdatenschutz,
submit: thissubmit
},
success: function(data) {
document.getElementById("response").innerHTML = data;
$("#newsletter-email").val("");
$('input[type=checkbox]').prop('checked',false);
}
});
});
});
</script>
</head>
Related
I want to receive judgement result from model of Azure Custom Vision by using JavaScript.
I changed JavaScript code that this site has.
https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814
But I can't.
What is wrong with my code?
I changed IterationId, application, url, content-Type, Prediction-key, and data.
These part are enclosed with {} in the code below.
<!DOCTYPE html>
<html>
<head>
<title>Human</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"iterationId": "{Iteration id that showed in Performance Page}",
"application": "{My Project name of Custom Vision}",
};
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Of course, I expected showing "success".
But, the actual output is "error"......
When I changed URL that this site has(https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814) in my code, I can get Success message.
And, I also write
processData: false,
contentType: false,
in ajax in my code
Change your code to see what is the error that you get back:
(Note the new "error" parameter to the request)
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
error: function(xhr,status,error) {
// >>>>>>>>>>>> CHECK HERE THE ERROR <<<<<<<<<<<<
}
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
Once you have the error, it would be easier to help you.
I'm trying to use ajax call in my blade view and post ajax data to controller to insert to database.
Here is my ajax:
<!DOCTYPE html>
<html>
<head>
<title>FormBuilder Editor</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div id="fb-editor"></div>
<div id="saveToDatabase">
<button id="saveBtn" type="button">Save To Database</button>
</div>
</body>
<script>
var formBuilder = $('#fb-editor').formBuilder();
$("#saveBtn").click(function() {
var mFormData = formBuilder.actions.getData(); //JSON data return
console.log(mFormData);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: "save",
data: {
"mFormData":mFormData
}
}).done(function (msg) {
alert("Data saved!" + msg);
});
});
</script>
</html>
And here is my controller:
public function saveToDb(Request $request) {
$data = $request->all();
if($data) {
Form::insertData($data);
}
return view('welcome');
}
And this is my insert function in Model:
public function insertData($formData) {
DB::EnableQueryLog();
$sql = DB::table('form')->insert(['formKey' => 'testForm2', 'formData' => $formData]);
return $sql;
}
When I click on button save, this is error in Network XHR:
How I can fix this? Thank you very much!
you are calling the inserData statically. so it should be
public static function insertData($formData) {
DB::EnableQueryLog();
$sql = DB::table('form')->insert(['formKey' => 'testForm2', 'formData' => $formData]);
return $sql;
}
Replace this line:
Form::insertData($data);
with this:
app()->make(From::class)->insertData($data);
Or inject the Form model instance in the constructor if you prefer.
However, the way you are inserting is not how models are meant to be inserted.
I am new to front-end development and am having troubles piecing together a solution for this specific form setup.
I have an already created jsp representing this instance creation page. It's a form containing numerous drop downs and check boxes. I need to add a file upload option to it.
The jsp is set up like this...
<form class="form-horizontal" id="editInstanceForm" onsubmit="return false;"> ....
Here's my input field
<div class="form-group" id="uploadForm">
<label class="col-xs-4 control-label instanceDefaultLabel" for="fileSearchField">Default Location and Zoom:</label>
<div class="col-xs-3">
<input name="myFile" type="file" id="fileSearchField" multiple=false>
<button id="upload-button">Upload</button>
</div>
.....
</div>
Now I have an ajax call that I was originally wanting to use before I realized that the whole form is attempting to submit when I uploaded the file. Here it is...
$('#upload-button').click( 'click',
function() {
var form = $('#fileSearchField')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/edit/uploadfile",
data: data,
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert("hi stuff worked");
},
error: function (e) {
alert("nope!");
}
});
}
);
I got this suggestion in researching how to upload a file with jQuery/ajax and Spring Boot (I am using Spring Boot to create my endpoint). Here are some articles that I have been reading in an attempt to understand how to do this...
https://www.mkyong.com/spring-boot/spring-boot-file-upload-example-ajax-and-rest/
http://javasampleapproach.com/spring-framework/spring-boot/multipartfile-create-spring-ajax-multipartfile-application-downloadupload-files-springboot-jquery-ajax-bootstrap#3_Implement_upload_controller
and many more. This seemed like the solution until I realized this was a form and I think I need to save all the fields at once. This is going to mean that I have to modify the already created ajax function that saves this form and passes it to the end point. Now I don't know how to get my MulitpartFile in as part of this different function. The existing one is like this...
$.ajax({
type: "POST",
url: webroot + "/viewerConfig/mapInstance/insertOrUpdate",
data: JSON.stringify(instanceData),
processData: false,
contentType: 'application/json',
success: function (data) {
if (data.status === "OK") {
alert("Instance created/updated successfully");
} else {
alert("Unknown error");
}
},
fail: function () {
alert("Unknown error");
},
error: function (a) {
alert("Unknown error");
}
});
});
This is exactly where I am stuck and I need to be pointed in the correct and productive direction.
I don't know if this will help but here's my end point that looks like the one I have to hit with my file param added...
#RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST, consumes = "application/json")
public #ResponseBody BaseStatusResponse insertOrUpdate(final #RequestBody SaveAdminInstanceView newInstance, HttpServletResponse servletResponse,
#RequestParam MultipartFile file)
EDIT:
I have done some curl troubleshooting and it's the MulitpartFile that's failing. I am passing it as suggested yet I am getting this exception:
org.springframework.web.multipart.MultipartException: The current request is not a multipart request</p><p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request
You can try below code:
$.ajax({
url: "/edit/uploadfile",
type: 'POST',
data: new FormData($(this)[0]),
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
cache: false,
success: function(res) {
console.log(res);
},
error: function(res) {
console.log('ERR: ' + res);
}
});
And in controller, you needn't declare consumes = "application/json"
I figured out what I was doing wrong. It wants the form element not the file one. FormData needs the Form. Thanks for your help though! :)
There you have 3 diferent ways to do this with spring-boot at 2022 be sure the file size is lower than the server maximun file size.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="http://192.168.12.168:8081/uploadfile" enctype="multipart/form-data">
<input type="file" id="fileinput" name="file" /><br/><br/>
<input type="submit" value="Submit using HTML" />
</form>
<button onclick="submitStyle1()">Submit using FETCH</button>
<button onclick="submitStyle2()">Submit using XHR</button>
</body>
<script>
function submitStyle1(){
const photo = document.getElementById("fileinput").files[0];
const formData = new FormData();
formData.append("file", photo);
fetch('http://192.168.12.168:8081/uploadfile', {method: "POST", body: formData});
}
function submitStyle2(){
const photo = document.getElementById("fileinput").files[0]; // file from input
const req = new XMLHttpRequest();
const formData = new FormData();
formData.append("file", photo);
req.open("POST", 'http://192.168.12.168:8081/uploadfile');
req.send(formData);
}
</script>
</html>
To see an example type me at https://github.com/JmJDrWrk
My view like this :
<input type="file" style="display: none" id="test">
When the file called, it will call ajax
I put my ajax in main.js (myshop\resources\assets\js\main.js)
It is global js. I put all my js there. I also put my ajax there
I put my ajax in main.js like this :
var _token = $('input[name="_token"]').val();
console.log(_token);
$('#test').on("change", function(){
data = new FormData();
$.ajax({
url: window.Laravel.baseUrl+'/product/addImage',
type: "POST",
data: { data: data, _token: _token },
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
console.log(data);
});
});
My routes like this :
Route::post('product/addImage', 'ProductController#addImage');
My controller like this :
public function addImage(Request $request)
{
dd('test');
// dd($request->all());
}
When executed, the console tab exist error like this :
POST http://myshop.dev/product/addImage 500 (Internal Server Error)
and on the network tab exist error like this :
TokenMismatchException in VerifyCsrfToken.php line 68:
How can I solve the error?
Whether ajax can be placed in global js?
You can resolve this issue in two ways:
You could use
<meta name="csrf-token" content="{{ csrf_token() }}" /> // add this under head tag
And before Ajax call add this:-
$.ajaxSetup({
headers:
{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Or the other (simpler) way, inside your app\Http\Middleware/VerifyCsrfToken.php add
protected $except = [
'product/addImage',
];
Hope it helps!
Remember to add file to data
data = new FormData();
data.append("test", $("#fileInput")[0].files[0])
I'm looking to be able to implement the Emotion API from Project Oxford on my website. I've currently written the below HTML/JavaScript code which checks an image from a URL and displays the result of said image after having run the Emotion API:
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
// Request body
data: '{"url": "https://philosophybank.files.wordpress.com/2013/08/happy-people.jpg"}',
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
//console.log(data);
//alert(data.scores);
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
</script>
This code works fine, however I'm looking to implement this on my website such that people upload images themselves locally from their machine with the use of a browse button as opposed to looking up an image using the link. Any help would be very much appreciated!
I mocked this up using application/octet-stream as the body type which allows you to post a binary object (i.e. the image itself), rather than a url to an image. The Emotion API documentation details how this is a supported content type.
I've continued with use of JQuery as per your original example.
You should be able to copy and paste this entire example into a HTML file, add your Emotion API key where it says my-key and it will work
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<input type="file" id="file" name="filename">
<button id="btn">Click here</button>
<script type="text/javascript">
$('#btn').click(function () {
var file = document.getElementById('file').files[0];
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
data: file,
processData: false
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
})
.fail(function(error) {
alert(error.getAllResponseHeaders());
});
});
</script>
</body>
</html>