Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest - Laravel

I am uploading a file with laravel and using ajax request to create the progress bar for it. This is how the form action routes to the controller:

<form action="{{ URL::route('upload-file-form-post') }}" method="POST" enctype="multipart/form-data">
.
.
</form>

ajax:

function _(el) {
    return document.getElementById(el);
}

function uploadfile() {
  var file = _("file").files[0];
  // dev
  alert(file.name+" | "+file.size+ " | "+" | "+file.type);
  var formdata = new FormData();
  formdata.append("file", file);
  var ajax = new XMLHttpRequest();
  ajax.upload.addEventListener("progress", progressHandler, false);
  ajax.addEventListener("load", completeHandler, false);
  ajax.open("POST", "here_is_where_the_url_needs_to_go");
  ajax.send(formdata);
}

function progressHandler(event) {
   _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + "bytes of "+ event.total;
   var percent = (event.loaded / event.total) * 100;
   _("progressBar").value = Math.round(percent);
   _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}

function completeHandler(event) {
  _("status").innerHTML = event.target.responseText;
  _("progressBar").value = 0;
} 

is there a way to send this {{ URL::route('upload-file-form-post') }}to the ajax request?

in my routes file the above is referenced as:

Route::post('/asset/upload-file', array(
    'as'  => 'upload-file-form-post',
    'uses' => 'AssetController@postUploadCreate'
));
like image 867
cch Avatar asked Apr 30 '26 07:04

cch


1 Answers

Simply use JavaScript to get the form action attribute

//Whatever your action value
var action = document.formName.getAttribute('action');

First:

Don't mix onclick event on submit button, clicking submit button actually process the form itself. Its better to bind submit events to forms instead of binding click events on submit button.

By giving a name attribute to your form like name="my_form", you can add submit event handler to your form.

Like this:

document.my_form.addEventListener('submit', function(e) {
    e.preventDefault();

    var actionURL = this.action; // will get the form action url
    uploadfile(actionURL); // your upload event with request url
});

Your function uploadfile(..) will accept a parameter called URL. Which will be passed to ajax.open(..) method

Modified:

// -----------------!!!! pass parameter for url
function uploadfile(url) {
  var file = _("file").files[0];
  // dev
  alert(file.name+" | "+file.size+ " | "+" | "+file.type);
  var formdata = new FormData();
  formdata.append("file", file);
  var ajax = new XMLHttpRequest();
  ajax.upload.addEventListener("progress", progressHandler, false);
  ajax.addEventListener("load", completeHandler, false);
  ajax.open("POST", url); // your url will pass to open method
  ajax.send(formdata);
}

Edited:

To fix Laravel Mismatch token issue (Referrence):

Add below <meta > tag within your <head> tag of your current form view file.

<meta name="csrf-token" content="<?php echo csrf_token() ?>">

Or use blade

<meta name="csrf-token" content="{{{ csrf_token() }}}">

Now within your uploadfile(...) function add this snippet:

var metas = document.getElementsByTagName('meta'); 

for (i=0; i<metas.length; i++) { 
    if (metas[i].getAttribute("name") == "csrf-token") {  
        ajax.setRequestHeader("X-CSRF-Token", metas[i].getAttribute("content"));
    } 
}

See updated JavaScript code from this fiddle

like image 112
Rahil Wazir Avatar answered May 02 '26 20:05

Rahil Wazir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!