Ajax Uncaught TypeError: Illegal invocation - javascript

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);
}
});
});
});

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

serialized form not sending ajax

I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!

How do I add my csrf token to my jQuery call?

My server generates a csrfToken, which is inserted into the following element:
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
The {{_csrfToken}}, is used for templating, but at run time is replaced at the server with the actual token.
<div class="formContainer">
<form class="form-horizontal signupform" role="form" action="/process?form=signupform" method="POST">
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
<div class="form-group">
<label for="fieldName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control"
id="fieldName" name="name">
</div>
</div>
<div class="form-group">
<label for="fieldEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" required id="fieldName" name="email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-default">Register</button>
</div>
</div>
</form>
</div>
{{#section 'jquery'}}
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
{{/section}}
How do I update my jQuery call to include the token ? Right now it is generating errors because the token is not included...
Try this, you did not post anything in fact. I did not test it, if it fails, maybe you should collect data manually.
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
+ var payload = $(this).serializeArray()
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
+ data: payload,
success: function(data){
if(data.success){ $container.html('<h2>Thank you</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
though it looks like it's a duplicate post still as far as answer is concerned this is how you should do check this SO post
and I am writing the code for you here
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer');
var token = $('input[name="_csrf"]').attr('value')
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', token);
}
});
$.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>

Ajax POST file upload in django

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.

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>

Categories

Resources