Laravel cant read formData - javascript

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

Related

Make a GET request after POST request is passed sucessfully with Laravel?

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>

Is it Possible to Upload Image Using HTTP GET

I've been using the following code to upload image to server. Is it possible to change it to pass file data using an object instead of form data and using GET instead of POST.
var uploadfileinfo = document.getElementById("upload-file-info").value;
var file_data = $('#a_imgfile').prop('files')[0];
var a_imgfile = document.getElementById("a_imgfile");
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
async: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
alert(response);
},
error: function(err) {
alert(err);
}
});
Browser file upload will send form multipart contenttype, you cant send content type in GET request
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
If you are looking for some workaround you can use some base64 encoder and pass your image to url query param
In GET request you can only get data or pass query paramerters. If you want to upload image change any other data it must be in POST request
Read more https://www.w3schools.com/tags/ref_httpmethods.asp

Using AJAX call in MVC5

I have tried to use AJAX call in an MVC5 project as many similar examples on the web, but every time there is an error i.e. antiforgerytoken, 500, etc. I am looking at a proper AJAX call method with Controller Action method that has all the necessary properties and sending model data from View to Controller Action. Here are the methods I used:
View:
#using (Html.BeginForm("Insert", "Account", FormMethod.Post, new { id = "frmRegister" }))
{
#Html.AntiForgeryToken()
//code omitted for brevity
}
<script>
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
$('form').submit(function (event) {
event.preventDefault();
//var formdata = JSON.stringify(#Model); //NOT WORKING???
var formdata = new FormData($('#frmRegister').get(0));
//var token = $('[name=__RequestVerificationToken]').val(); //I also tried to use this instead of "AddAntiForgeryToken" method but I encounter another error
$.ajax({
type: "POST",
url: "/Account/Insert",
data: AddAntiForgeryToken({ model: formdata }),
//data: { data: formdata, __RequestVerificationToken: token },
//contentType: "application/json",
processData: false,
contentType: false,
datatype: "json",
success: function (data) {
$('#result').html(data);
}
});
});
</script>
Controller: Code cannot hit to this Action method due to antiforgerytoken or similar problem.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult Insert(RegisterViewModel model)
{
try
{
//...
//code omitted for brevity
}
}
I just need a proper AJAX and Action methods that can be used for CRUD operations in MVC5. Any help would be appreciated.
UPDATE: Here is some points about which I need to be clarified:
1) We did not use "__RequestVerificationToken" and I am not sure if we send it to the Controller properly (it seems to be as cookie in the Request Headers of Firebug, but I am not sure if it is OK or not). Any idea?
2) Should I use var formdata = new FormData($('#frmRegister').get(0)); when I upload files?
3) Why do I have to avoid using processData and contentType in this scenario?
4) Is the Controller method and error part of the AJAX method are OK? Or is there any missing or extra part there?
If the model in your view is RegisterViewModel and you have generated the form controls correctly using the strongly typed HtmlHelper methods, then using either new FormData($('#frmRegister').get(0)) or $('#frmRegister').serialize() will correctly send the values of all form controls within the <form> tags, including the token, and it is not necessary to add the token again.
If your form does not include a file input, then the code should be
$('form').submit(function (event) {
event.preventDefault();
var formData = $('#frmRegister').serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")', // do not hard code your url's
data: formData,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
or more simply
$.post('#Url.Action("Insert", "Account")', $('#frmRegister').serialize(), function(data) {
$('#result').html(data);
});
If you are uploading files, then you need you need to use FormData and the code needs to be (refer also this answer and
$('form').submit(function (event) {
event.preventDefault();
var formData = new FormData($('#frmRegister').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")',
data: formData,
processData: false,
contentType: false,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
Note that you must set both processData and contentType to false when using jQuery with FormData.
If you getting a 500(Internal Server Error), it almost always means that your controller method is throwing an exception. In your case, I suspect this is because your method is returning a partial view (as suggested by the $('#result').html(data); line of code in you success callback) but you have specified that the return type should be json (your use of the datatype: "json", option). Note that it is not necessary to specify the dataType option (the .ajax() method will work it out if its not specified)
If that is not the cause of the 500(Internal Server Error), then you need to debug your code to determine what is causing the expection. You can use your browser developer tools to assist that process. Open the Network tab, run the function, (the name of the function will be highlighted), click on it, and then inspect the Response. It will include the details of the expection that was thrown.
contentType should be application/x-www-form-urlencoded
Try this code
<script>
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "/Account/Insert",
data: $(this).serialize(),
contentType:"application/x-www-form-urlencoded",
success: function (data) {
$('#result').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
</script>

ajax form submit redirect like a not ajax form

I have this code that I use to submit a form with a attachment file
$("#career_form").submit(function(e){
var this_current = $(this);
var formData = new FormData(this_current[0]);
var url = this_current.attr("action");
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
e.preventDefault();
});
but the form keeps redirecting me to its destination file "url in the action" like it wasn't an ajax submission but if I replace the 'data' argument with
data: $(this).serialize();
it works (ajax submit), any ideas, help, suggestions, recommendations?
give that e.preventDefault(); at the beginning of the function.
jQuery trys to transform your data by default into a query string, but with new formData it throws an error.
To use formData for a jquery ajax request use the option processData and set it to false like:
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
processData: false,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
Thats the reason why it works with serialize, but not with formData in your example.
The e.preventDefault works correctly, but if there is an error before it will not work. By placing the e.preventDefault at the top of your function it will allways prevent the action, no matter if there is an error in later code or not.
You can edit the var formData = new FormData(this_current[0]); in your code and use the below line:
var formData = new FormData(document.querySelector("#career_form"));
Also, if you are using multipart form to send files in your form, you need to set following parameters in your ajax call.
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
Hope this helps. See more about using formData here.
Try this:
$("#career_form").submit(function(e){
e.preventDefault();
var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "change-status.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response){
if(response){
alert("successfully sent");
}
}
});
});

Data from the Form Submit vs Data from Ajax

I'm trying to implement reCAPTCHA in my MVC site, but it doesn't Validate unless I submit it from a form, like this:
#using(Html.BeginForm("VerifyCaptcha", "Signup") )
{
#ReCaptcha.GetHtml(theme: "clean", publicKey: "6LcnfAITAAAAAAY--6GMhuWeemHF-rwdiYdWvO-9");
<input type="submit" id="btnVerify" value="Verify" />
}
[HttpPost]
public ActionResult Index(PolicyModel model)
{
var result = ReCaptcha.Validate(privateKey: "THE_KEY");
return View();
}
I don't want to use form submission because I don't want to return a new view. All my data is being pushed around with ajax in json form. What I'd like to do is:
$.ajax({
url: 'verifyCaptcha',
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
type: "POST",
async: false,
success: function (response) {
alert(response);
},
error: function(response) {
alert('There was a problem verifying your captcha. Please try again.');
}
});
return valid;
[HttpPost]
public ActionResult VerifyCaptcha()
{
var result = ReCaptcha.Validate(privateKey: "THE_KEY");
return Json(result);
}
The ajax call gets to the controller, but the Validation method completes immediately, almost as if it doesn't even get to making the request. I'm not sure why the validation always fails if the captcha isn't in a form - is it perhaps losing information like it's public key or something? Is there a workaround to this?
Edit: Added the ajax controller action method without model.
Just use serializeArray() or serialize() and change your ajax request to
$.ajax({
url: 'verifyCaptcha',
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
type: "POST",
async: false,
data: $('form').serializeArray(), // $('form').serialize(),
success: function (response) {
alert(response);
}
});
You haven't added the data part in your request. That seems to be the problem
You need to set the Ajax Request with all parameters for a form request. For example the content-type as application/x-www-form-urlencoded.
Look at this: application/x-www-form-urlencoded or multipart/form-data?
UPDATE:
...and yes ...you must do a POST request, and not a GET.
UPDATE:
$.ajax({
url: 'verifyCaptcha',
contentType: "application/x-www-form-urlencoded",
type: "POST",
success: function (response) {
alert(response);
},
error: function(response) {
alert('ERROR', response);
}
});

Categories