Ajax POST file upload in django - javascript

I'm trying to process a POST request with a file field via Ajax post in my djano app.
I'm getting this error:
Forbidden (CSRF token missing or incorrect.): /user/instance/create/new/awod/
Here's what I have tried:
From template.html
<div class="container" style="background-color: lightgray; opacity: 0.7;margin-top:10%;margin-left: 2%; padding-bottom: 10%;">
<form method="post" class="form-horizontal" action="" id="gitForm" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label" for="inputGroupSuccess1">Deployment Name:</label>
<div class="input-group">
<span class="input-group-addon">#</span>
<input type="text" class="form-control" name="name" id="inputGroupSuccess1" aria-describedby="inputGroupSuccess1Status">
</div>
</div>
<div class="form-group">
<label class="control-label">Select File</label>
<input type="file" id="inputGroupSuccess2" name="archive" class="file" multiple data-allowed-file-extensions='["zip", "tar"]'>
<small id="fileHelp" class="form-text control-label" style="color:black">Upload a Tar or Zip archive without a Dockerfile, otherwise your deployment will fail.</small>
</div>
<div id="spinner" style="display: none;">
<div class="f_circleG" id="frotateG_01"></div>
<div class="f_circleG" id="frotateG_02"></div>
<div class="f_circleG" id="frotateG_03"></div>
<div class="f_circleG" id="frotateG_04"></div>
<div class="f_circleG" id="frotateG_05"></div>
<div class="f_circleG" id="frotateG_06"></div>
<div class="f_circleG" id="frotateG_07"></div>
<div class="f_circleG" id="frotateG_08"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg pull-right" value="Submit"> Submit </button>
<span style="padding-right: 5%;float: right;"><img src="{% static 'images/go-back-arrow.svg' %}" style="width: 24px; height: 24px;"> Go Back! </span>
</div>
</form>
</div>
</div>
</div>
</div>
my javascript
<script type="text/javascript">
$(document).ajaxStart(function() {
$('#spinner').show();
console.log("ajax start")
});
$(document).ajaxStop(function() {
$('#spinner').hide();
});
$(document).on('submit', '#gitForm', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url : '/user/instance/create/new/awod/',
data: {
name:$('#inputGroupSuccess1').val(),
archive:$('#inputGroupSuccess2').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
},
async: false,
cache: false,
contentType: false,
processData: false,
success:function () {
$('#message').show();
$('#inputGroupSuccess1').val('');
$('#inputGroupSuccess2').val('');
}
})
});
Even when I console.log the csrf_token field, it prints the csrf token properly.
is there something wrong?
Help me, please!
Thanks in advance!

While you can pass the token in the data, the recommended method is to set a custom X-CSRFToken HTTP header:
$.ajax({
type: 'POST',
headers: {'X-CSRFToken': $.cookie('csrftoken')},
url : '/user/instance/create/new/awod/',
data: {
name:$('#inputGroupSuccess1').val(),
archive:$('#inputGroupSuccess2').val()
},
async: false,
cache: false,
contentType: false,
processData: false,
success:function () {
$('#message').show();
$('#inputGroupSuccess1').val('');
$('#inputGroupSuccess2').val('');
}
})
As you can see, the value is the csrftoken cookie (set by Django). I have used the jQuery.cookie library to retrieve the token, but you can retrieve it however you'd prefer.

It is generely a bad idea to use async:false since it'll prevent other events on the page from firing you probably don't want your code to be paused, I'd suggest you to use ajax like this :
$(document).on('submit', '#gitForm', function (e) {
var form_data = new FormData($(this)[0]);
$.ajax({
type:'POST',
url:'/user/instance/create/new/awod/',
processData: false,
contentType: false,
data : form_data,
success: function(response) {
$('#message').show();
$('#inputGroupSuccess1').val('');
$('#inputGroupSuccess2').val('');
}
});
});
this should also resolve your issue with csrf_token.

Related

in Laravel I GOT AN ERROR The POST method is not supported for this route. Supported methods: GET, HEAD

I am trying to when the customer wants to upload an image or logo I want this image to display it in front of him by span element for him to make sure he uploaded the correct image to the system but when I press on upload I got POST method is not supported for this route. Supported methods: GET, HEAD. error
here is my code in card_view_blade
<div class="form-group row">
<div class="col-md-8">
<form method="post" id="upload-image-form" enctype="multipart/form-data">
#csrf
<div class="input-group" data-type="image">
<input type="file" name="file" class="form-control" id="image-input">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</form>
</div>
<div class="col-md-4">
<div class="alert" id="message" style="display: none"></div>
<span id="uploaded_image"></span>
</div>
</div>
here is the js code
#section('script')
<script type="text/javascript">
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#upload-image-form').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$('#message').hide().html('');
$.ajax({
type:'POST',
url: `/upload-images`,
data: formData,
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success: (data) => {
console.log("success-",data);
if (data) {
this.reset();
$('#message').show().html(data.message);
$('#message').addClass(data.class_name);
$('#uploaded_image').html(data.uploaded_image);
}
setTimeout(function(){
$('#message').hide().html('');
}, 3000);
},
error: function(data){
console.log("error-",data);
// $('#image-input-error').text(data.responseJSON.errors.file);
$('#message').show().html('Something went wrong');
$('#message').addClass('danger');
$('#uploaded_image').html('');
setTimeout(function(){
$('#message').hide().html('');
}, 3000);
}
});
});
})
</script>
#endsection
route code
Route::post('/upload-images', 'CheckoutController#storeImage' )->name('images.store');
Nothing seems to be wrong with the code perhaps the routes are cached. Try clearing them first and see if the problem is resolved or not with the following commands:
php artisan route:clear

Ajax Uncaught TypeError: Illegal invocation

I have look at every tutorial but it's not change anything
$(document).ready(function(e){
$('#formImage').on('submit', function(e){
e.preventDefault();
$.ajax({
url: '../php/insertImage.php',
type: 'post',
data: new FormData(this),
prosessData:false,
contentType: false,
success:function(e){
console.log(e);
alert(e);
}
});
});
});
here my form
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal" id="formImage">
<div class="form-group col-md-12 row" style="margin-top: 50px;">
<label class="col-form-label">Input picture here</label>
<div class="col-md-6">
<input type="file" name="inputfile" id="my-pic" class="form-control">
</div>
<div>
<button type="submit" class="btn btn-primary" id="upload-mypic">Upload</button>
</div>
</div>
</form>
i have no idea anymore.. please help
Thanks
Have you noticed the spelling of processData? You've written prosessData.
Please Check your spelling Mistake.
prosessData:false,
$(document).ready(function(e){
$('#formImage').on('submit', function(e){
e.preventDefault();
$.ajax({
url: '../php/insertImage.php',
type: 'post',
data: new FormData(this),
processData:false,
contentType: false,
success:function(e){
console.log(e);
alert(e);
}
});
});
});

Jquery ajax not working in firefox

My code is working in chrome,safari but its not working in firefox.
Here is my code
<script>
$(document).ready(function () {
$("#loginform").on('submit',(function(e) {
e.preventDefault();
$('#loading').html("Loading....");
$.ajax({
url: "login.php",
type: "POST",
data: new FormData(this),
contentType:false,
cache: false,
processData:false,
async:false,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
return false;
}));
});
</script>
Can anyone solve this issue??? I have one more same script in the same page only url is different but its working fine,but this script is not working .Iam getting empty data .But in chrome,safari its working fine.
My Html Code :
<form role="form" method="post" id="loginform" action="">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Username" required>
</div>
<div class="form-group">
<label for="password"> Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<div class="checkbox">
<label><input type="checkbox" value="" name="user_rememberme" checked>Remember me</label>
</div>
<div id="loading"></div>
<div id="message"></div>
<button type="submit" name="login" class="btn btn-success pull-right">Login</button>
</form>
Never use async:false in ajax call unless you knows specifically wat you are doing.The problem is that async:false freezes the browser until ajax call is complete (either error or success).set it to true or remove it (by default it is true).Implement error block too and check if its an error from server side
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
},error:function(data){
console.log(data)
}
Try this:
<script>
$(document).ready(function () {
$("#loginform").on('submit',(function(e) {
dta = $(this).serialize();
e.preventDefault();
$('#loading').html("Loading....");
$.ajax({
url: "login.php",
type: "POST",
data:dta,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
return false;
}));
});
</script>

Ajax Success display Message inside div displayed through jQuery

i'm trying to display a success /error message when a user login to my website through a hidden div, that is displayed by on click event jQuery. Looks like whatever i try, nothing works. Already searched over and over but can't find a solution. Any help please?
My current code:
$(document).on('submit', '#loginform',function(e){
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'portal/login',
type: 'POST',
dataType:"json",
data:formData,
contentType: false,
processData: false,
success: function(data) {
if(data.status == 1) {
console.log(data.status);
$('.login_result.success').show();
} else {
$('.login_result.error').show();
}
}
});
});
$('.modaltrigger').on('click',function() {
$('#loginmodal').fadeIn(500);
});
So i'm using Ajax to validate the user login, and then at success i want to fadeIn the .login_result
EDIT
My HTML code:
<div id="loginmodal" style="display:none;">
<div id="placeHolder">
<div class="main_logo"><img src="images/logo.jpg"></div>
<form action="portal/login" method="post" class="login" name="loginform" id="loginform">
<input id="user_email" name="user_email" placeholder="Email" type="text">
<input id="user_password" name="user_password" placeholder="Senha" type="password">
<button class="search_button login_button" name="admin_login">Entrar</button>
<span><?php //echo $error; ?></span>
</form>
<div class="login_result success">Login Efetuado com sucesso, Redirecionando!</div>
<div class="login_result error">Login Inválido!</div>
</div>

How to make run a javascript function that calls a web service from another project

In my Phonegap project I need to call a web service that does some login stuff. I can run the web service and make it visible; but when I try to call it from a login button's on-click; it doesn't return any errors nor do anything.
Thanks for help.
that is userLogin.js
function login() {
$("#loginButon").click(function() {
var requestData = {
email : $('#email').val(),
password : $('#password').val()
};
$.ajax({
type : 'POST',
dataType : 'json',
headers: { 'Access-Control-Allow-Origin': '*' },
origin: 'http://localhost:8080',
contentType : 'application/json; charset=utf-8',
url : 'http://localhost:8080/myWebServiceProjectName/ws/userLogin/userLoginControl',
data : JSON.stringify(requestData),
crossDomain: true,
success : function(responseData) {
onSuccess(responseData);
}
});
});
}
This is my login.html
<html>
<body>
<head>
<script src="js/jqm.globals.js"></script>
<script src="jsAndroid/jquery.min.js"></script>
<script src="jsAndroid/userLogin.js"></script>
<script src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header" style="background: #31B404; color: white;">
<h1>WELCOME</h1>
</div>
<div data-role="content">
<div id="ortala">
<div class="span-2 fl">
<!--login-->
<div class="controls-login">
<div class="form-login">
<h3>GIRIS</h3>
<form>
<div class="form-item">
<input type="text" id="email" placeholder="Kullanici Adi" />
</div>
<div class="form-item">
<input type="password" id="password" />
</div>
<div class="form-item">
<a href="yeniUyeEkleme.html" rel="external">Uye Degil
misiniz?</a>
</div>
<div class="form-item">
<input type="button" id="loginButon" value="Giriş Yap"
onclick="login();"
style="background-color: FFFFFF; color: #090101;" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
You are calling a function to setup an event listener.
Remove the onclick="login();" from the input button and replace login() with the following:
$(function() {
$("#loginButon").click(function() {
var requestData = {
email : $('#email').val(),
password : $('#password').val()
};
var request = $.ajax({
type : 'POST',
dataType : 'json',
contentType : 'application/json; charset=utf-8',
url : 'http://localhost:8080/myWebServiceProjectName/ws/userLogin/userLoginControl',
data : JSON.stringify(requestData),
crossDomain: true
});
request.done(function(data) {
console.log(data);
onSuccess(responseData);
});
request.fail(function(jqXHR, textStatus) {
console.log("request error: " + textStatus);
});
});
});
Make sure to remove the console.log() frpm both done & fail events if you are using IE, or when you are done testing as it will break some browsers.
I figured it out on my own. It was all about chrome itself.
I run chrome from command window with these parameters:
start chrome.exe allow-file-access-from-files --disable-web-security
Thanks again for helps.

Categories

Resources