I am trying to make a file upload system on AWS based on laravel with ajax. I am talking about a resume parser system where i used the apilayer API to parse the CV from pdf to json.
I tried to make a file upload system where files are uploaded to aws (this works) and after i get the uploaded file url to send to API.
public function store(Request $request)
{
$request->validate([
'file' => 'required|mimes:doc,docx,pdf|max:2048',
]);
$fileName = time() . '.' . $request->file->extension();
$path = $request->file->storeAs('file', $fileName, 's3');
CVupload::create(['name' => $fileName]);
$urlcv = Storage::disk('s3')->url($path);
return response()->json("$urlcv");
}
}
Everything is ok, but when the API is executed from the below code i receive the error:
Client error: POST https://api.apilayer.com/resume_parser/url?url=https://--.s3.eu-central-1.amazonaws.com/file/-- resulted in a 403 Forbidden response:{"message":"You cannot consume this service"}
I see that the request is POST, and i have to make a GET REQUEST. Maybe its an error in Ajax Script?
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#file-upload').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$('#file-input-error').text('');
$.ajax({
type: 'POST',
url: "{{ route('resume.store') }}",
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response) {
this.reset();
$("#showResponseArea span").html(response); //you will paste your response msg to the
$.ajax({
type: 'GET',
url: "{{ route('resume.api') }}",
dataType: 'json',
data: {
'url': response,
}
})
}
},
error: function(response) {
$('#file-input-error').text(response.responseJSON.message);
}
});
});
</script>
Related
I have the following ajax code in my frontend.
var formData = $('#application-information-step-one').serialize();
var actionUrl = $('#application-information-step-one').attr('action');
$.ajax({
url: actionUrl,
type: 'POST',
data: formData,
success: function(data) {
var resp = JSON.stringify(data);
console.log(resp);
},
error: function(data) {
}
And following code to return json response from my controller if the request is ajax:
if ($request->ajax()) {
return response()->json([
'message' => 'Information saved sucessfully !'
],200)->headers('Content-Type', 'application/json');
}
But with the above code setup. Laravel returns HTML code of same page from where the request was made.
HTML page is rendered in preview section of network tab .
Can anyone suggest what am I missing here ?
Check for Ajax request is incorrect, otherwise the controller wouldn't have outputted HTML.
You can try several things:
use Illuminate\Support\Facades\Request; at the top of the file
replace request->ajax() with Request::wantsJson()
use request()->ajax()
Any of the above subject to your Laravel version.
More details here
Return JSON response from controller
if ($request->ajax()) {
return response()->json([
'status' => 'success',
'data' =>[],
'message' => 'Information saved successfully!'
], 200);
}
In AJAX success function code:
success: function (data) {
console.log(data.message);
},
and add to AJAX request object next parameters too
dataType: 'json',
contentType: false,
processData: false
I have been searching high and low for answers but I cant seem to find.
Trying to send file input to laravel controller via ajax but laravel controller can't seem to read the data at all
Following is my ajax code
let fd = new FormData();
fd.append('fwigNo' , $('#fwigNo').val());
fd.append('x' , 27);
formData = fd;
$('#submit').click(function(e) {
e.preventDefault();
url = url.replace(':vdrId', dataId);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "PUT" ,
dataType: "json" ,
cache: false,
processData: false,
contentType:false,
url: url,
data: formData,
success: function(result) {
console.log(result)
},
});//end of ajax
})//end of submit
Following is my laravel controller
public function store($vdrId , Request $request)
{
dd($request->all());
}
I managed to send to form Data via ajax but when I dd($request->all()) , it shows empty
Please do advise
update:
Route shown in cmd
Thank you
in web.php route file,try use resource form method get request
I already created MVC spring and I want consume with SAPUI5 (javascript) with AJAX but I found an error "415 (Unsupported Media Type)". I use swagger in spring for test CRUD. in swagger, I success for insert data but failed in AJAX.
controller Spring:
#PostMapping(value={"/tesinsert"}, consumes={"application/json"})
#ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<?> insert(#RequestBody KasusEntity user) throws Exception {
Map result = new HashMap();
userService.insertTabel(user);
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
in javascript:
var data = {
"kodekasus":5,
"nama":"baru",
"isdelete":1,
"createdby":"hahaa",
"createddate":null,
"updatedby":"hihii",
"updateddate":null
};
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
console.log('sukses: '+data);
},
error: function(error){
console.log('gagal: '+error);
}
});
if I code above in AJAX, show error "415 (Unsupported Media Type)", if I add in AJAX show different error: "Response for preflight has invalid HTTP status code 403
":
headers: {
Accept : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
}
How to solve this problem?
Thanks.
Bobby
Add dataType: 'json' in your ajax call:
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(data) {
console.log('sukses: '+data);
},
error: function(error){
console.log('gagal: '+error);
}
});
I'm trying to do GET that retrieves data from a URL and then a POST to a RESTful api. The get call seems to work okay but the server sees nothing in the file parameter. I have verified that the GET call is return pdf stream data and that it is placing it in the FormData arg.
Here is the complete call
function upload(key, url){
var file;
/* get data from url */
$.ajax({
url: url,
type: 'GET',
async: false,
cache: false,
dataType : 'text',
contentType : 'application/pdf',
success: function( data ) {
file = data;
},
error: function(xhr, status, error) {
console.log("error logging: "+ error);
}
});
/* send data to api */
var data = new FormData();
data.append("key", key);
data.append("file", file); //<-- this has pdf stream data
$.ajax({
url: ROOT_URL + "/api/account/upload",
type: 'POST',
cache: false,
async: false,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: data,
success: function( data ) {
console.log("Uploaded!");
},
error: function(xhr, status, error) {
console.log("error logging: "+ error);
},
dataType: "json"
});
};
Here is the server side (grails + spring + jaxrs)
#POST
#Path('upload')
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces('application/json')
String upload(#Context HttpServletRequest request){
GrailsWebRequest w = WebUtils.retrieveGrailsWebRequest()
MultipartFile multipartFile = w.getRequest().getFile('file');
println("request:" + request)
println("multipartFile:" + multipartFile)
println("parameterMap:" + w.getRequest().getParameterMap() )
return ['okay':'uploaded'] as JSON
}
Which currently prints out:
request:org.grails.jaxrs.web.RequestWrapper#448593df
multipartFile:null
parameterMap:[file:[], key:[c07fc0974ebb4f3a8fc21e3d002152d4]]
Looks like when the POST call is happening, the variable file doesn't have a value yet. Since you are wanting everything after GET call to occur after the server has returned data, you should move that code into a separate function that is called upon success.
I want to send an ajax post request to a module named sampleTest in Drupal6.
I have tried some bits of codes but I do not know how to put the module url in the jquery ajax function.
<script type="text/javascript">
$(function(){
$("#one").click(function(){
$.ajax({
type: 'POST',
url: 'http://localhost/drupal/www/admin/build/modules/module/get/contact',
dataType: 'json',
data: "test",
success:function(data) {
alert("123");
},
complete: function(data){
alert("complete");
}
});
});
});
</script>
You can't send an AJAX request to a module as such, rather you implement a path in your module (using hook_menu()), provide a page callback for that path that outputs the AJAX response, and then call that path in your AJAX call. This is a very basic example:
function mymodule_menu() {
$items['ajax-test'] = array(
'access callback' => TRUE,
'page callback' => 'mymodule_ajax_callback',
'type' => MENU_CALLBACK
);
}
function mymodule_ajax_callback() {
$post_data = $_POST;
// Do something with the post data
$output = array('status' => 'OK');
// For Drupal 6
drupal_json($output);
exit();
// Or for Drupal 7, just in case you want to know
drupal_json_output($output);
drupal_exit();
}
Then your JS would look like this:
$(function(){
$("#one").click(function(){
$.ajax({
type: 'POST',
url: '/drupal/ajax-test',
dataType: 'json',
data: "test",
success:function(data) {
alert(data.status);
},
complete: function(data){
alert("complete")
}
});
});
});