I am trying to post File using JQuery. Below is my code.
<script language="javascript">
$(document).ready(function() {
$('#frmUpdateProfile').on("submit", function(event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data = {
"FileName" : event.target.FileName.files,
"_token" : "{!! csrf_token() !!}"
};
$.ajax({
url: '{{URL::route("UpdateProfile")}}',
method: "POST",
async: true,
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8",
success: function (msg) {
SuccessCallback(msg);
},
error: function (jqXHR) {
ErrorCallback(jqXHR);
}
});
});
});
</script>
I tried processData: false,. While debugging in Js, you can check that image is coming in the data. Below is the screenshot.
But when I print the request data in Laravel, it show blank array.
Html form is here
<form method="POST"
action="http://localhost:1234/AS6-Code/public/UpdateProfile"
accept-charset="UTF-8"
enctype="multipart/form-data"
id="frmUpdateProfile">
<input name="_token" type="hidden" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input type="hidden" name="_token" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input multiple="1" name="FileName" type="file">
<input class="btn btn-info" type="submit" value="Update">
</form>
Am I doing something wrong?
Try sending your request with FormData instead:
var data = new FormData($('#frmUpdateProfile')[0]);
Also set contentType to false:
contentType: false
Also Update
event.target.FileName.files
to
event.target.FileName.files[0]
event.target.FileName.files is a FileList object. I believe you need event.target.FileName.files[0] instead.
Related
I have a form. When I post the form without using ajax, it works well. But when I use the ajax, I have an error like this;
django.utils.datastructures.MultiValueDictKeyError:
My codes are below that without using ajax. It works.
HTML Form:
<form id="add_form" action="/adding/" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input type="file" name="picture">
<button type="submit" id="send_form" value="ok">Ok</button>
</form>
My views.py codes are:
if request.method == "POST":
title = request.POST.get('title')
pic = request.FILES['picture']
query = Images_Table(title=title, pic=pic)
query.save()
My model codes are:
class Images_Table(models.Model):
title = models.CharField(max_length=70, blank=True, null=True)
pic = models.FileField(upload_to='images_folder', blank=True, null=True)
Until here; everythings are normal, codes works. When I use ajax, I have an error. My HTML Form:
<form id="add_form" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input type="file" name="picture">
<button id="send_form" value="ok">Ok</button>
</form>
My ajax codes are:
$("#send_form").click(function(){
$.ajax({
url: '/adding/',
method:'post',
data: $("#add_form").serialize(),
headers: '{{ csrf_token }}',
success : function(){
alert('Success posted!');
}
});
});
Error code is below;
django.utils.datastructures.MultiValueDictKeyError: "'picture'"
I solved the problem by changing ajax.
$("#send_form").click(function(){
var file_data = $('#picture').prop('files')[0];
var form_data = new FormData($('form').get(0));
form_data.append('file', file_data);
$.ajax({
url: '/adding/',
method:'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
headers: {'X-CSRFToken': '{{ csrf_token }}'},
success : function(){
alert('Success posted!');
}
});
});
$('#id').change(function(){
var a = $('#id_one').val();
var token = '<?php echo csrf_token(); ?>';
$.ajax({
url: "url",
type: 'POST',
data: {'id':a,'_token':token},
success: function(data)
{
// some code
}
});
})
This is my code.
Getting token mismatch error..!!
I have tried both of the following..
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<script type="text/javascript">
var _globalObj = {{ json_encode(array('_token'=> csrf_token())) }}
Can any one help ??
You can utilize your token from the blade template, just declare your session token in the blade file of your view under the script tag like this:
<script> var token = '{{ Session::token() }}'; </script>
and call the token in ajax, in your code it will be something like this:
$('#id').change(function(){
var a = $('#id_one').val();
$.ajax({
url: "url",
type: 'POST',
data: {'id':a,'_token':token},
success: function(data)
{
// some code
}
});
})
Possibly because the token field name should be _token and not token
Also If this javascript code in a separate javascript file then php function will not work.
Also if the data you are trying to send is of a form then you can do this
$('#id').change(function(){
var data = $("#form").serialize() ;
$.ajax({
url: "url",
type: 'POST',
data: data,
success: function(data)
{
// some code
}
});
})
where your form looks like
<form id="form">
<input type='hidden' value='{{ csrf_token() }}' name='_token'>
<input type="text" name='id'>
</form>
$.ajax({
url: someurl,
type: 'POST',
data : formData,
headers: {
"x-csrf-token": $("#token").data('id')
}
});
}
and in your html
<div id="token" data-id="{!! csrf_token() !!}"></div>
html
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector"/>
<input type="file" id="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
js/ajax
var fileVar = null;// global var to store file info
$(document).ready(function(){
$('#dataForm').on('submit', function(e) {
e.preventDefault();
SendData();
});
$('#fileSelector').on('change',function(ev){
fileVar = null;
fileVar = new FormData();
$.each(ev.target.files, function(key, value)
{
fileVar.append(key, value);
});
});
});
function SendData(){
var formData = new FormData($("#dataForm")[0]);
// should i add the filerVar like this ?
// formData.append("Image", fileVar);
$.ajax({
type: "POST",
url: "checkinput.php",//you need to add this '?files part' to URL
data: formData,// use fileVar here now
cache: false,
processData: false,
// contentType: false,
success:function(data)
{
console.log(data);
console.log("success");
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log("failure");
}
});
}
php
print_r($_POST);
print_r($_FILES);
my intention is to send input(file) and input(text) in one ajax , i can get the input file value if i add ajax data with fileVar , but i cant get my input text value i have no idea why , can anyone tell me what i did wrong ?
var formData = new FormData($("#dataForm")[0]) is the way to get both to one ajax but i cant get any input text value.
anyone can teach me how to make this work ?
I think you need to specify input name attributes:
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector" name="textSelector"/>
<input type="file" id="fileSelector" name="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
Hope that helps.
I'm new to MooTools and trying to send Ajax request with form content to the url.
<form method="post" enctype="multipart/form-data" action="<?= $PHP_SELF; ?>" name="fn" id="fn">
<input name="user_name" id="user_name">
<input name="user_mail" id="user_name">
<input name="user_text" id="user_name">
<input type="file" name="attach">
<input id="button" type="button" value="Submit">
</form>
<script type="text/javascript">
$('button').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'url.php',
onSuccess: function(response) {
alert(response);
});
});
</script>
When I click on button, nothing happens. How right transferring data from form?
Your code looks good, you had a } missing but aside from that you just forgot to add a .send();
Like req.send();, and you can actually pass the data as a argument to that method.
Test that and check here about the .send() method.
Suggention to how your code could look like:
<script type="text/javascript">
var req = new Request({
method: 'post',
url: 'url.php',
onSuccess: function(response) {
alert(response);
} // < --- You actually missed this one
});
$('button').addEvent('click', function(event) {
req.send();
});
</script>
i am trying to display the full response of jsonp call in textarea and div but for some reason it doesnt work! could any one tell me what i am doing wrong here?Thanks
ajax script:
<script>
$(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/test&count=-1",
success: function(data) {
alert(data);
$(".response").append(data);
$("#outputtext").append(data);
document.myform.outputtext.value = document.myform.outputtext.value+data+'\n' ;
}
});
});
</script>
<div class="response"></div>
<form id="myform" name="myform" action="./" method="post">
<td><textarea rows="6" cols="15" name="outputtext" style="width: 99%;"></textarea></td>
</form>