Django + Ajax | File Upload | Server doesn't recognise Ajax Request - javascript

I am trying to implement file upload using ajax with Django but facing some problem.
When the user tries to upload the files after selecting the file and submitting the form, then as per my understanding , an ajax request should be send to the server using POST method ,but in my case a POST request is being made to the server, but the server is not able to identify it as an ajax request and browser is redirected to http://<server>:<port>/upload/ and the contents on this page are as follows.
{"status": "error", "result": "Something went wrong.Try Again !!"}
Django Version: 1.6.2
Python Version: 2.7.5
Also, testing on Django Development Server.
views.py
def upload(request):
logging.info('Inside upload view')
response_data = {}
if request.is_ajax():
logging.info('Is_AJAX() returned True')
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
logging.info('Uploaded Data Validated')
upload = Upload( upload=request.FILES['upload'] )
upload.name = request.FILES['upload'].name
upload.save()
logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded !!"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "Something went wrong.Try Again !!"
return HttpResponse(json.dumps(response_data), content_type='application/json')
Template
<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>
Javascript 1:
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Javascript 2
var options = {
url: '/upload/',
type: "POST",
error: function(response) {
alert('Something went Wrong. Try Again');
},
success: function(response) {
if ( response.status == 'success' ) {
alert('success');
}
}
};
$('#uploadForm').ajaxSubmit(options);
Question:
1) Why is Django not able to recognize the ajax request and value of request.is_ajax() is always False.
2) Even if the server doesn't recognize ajax request why is my browser getting redirected to another page ?
There is another similar question here but with no result.

This works for me. You need a jquery.form.js
$("#uploadForm").submit(function(event) {
$(this).ajaxSubmit({
url:'{% url upload_file %}',
type: 'post',
success: function(data) {
console.log(data)
},
error: function(jqXHR, exception) {
console.log("An error occurred while uploading your file!");
}
});
return false;
});
Here's the similar question here with answers.

Make sure that javascript code block
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
loaded after your uploadForm html form in DOM on page. In your case seems you trying to bind submit handler with form element which not yet loaded so when you click, it send simple POST request.

1) why is_ajax() not working?
Have you included the JQuery form plugin (jquery.form.js) ? ajaxSubmit() needs that plugin.
Take a look at http://jquery.malsup.com/form/
If it's already done, you might take a look at the HTTPRequest object
Django Documentation says HttpRequest.is_ajax()
Returns True if the request was made via an XMLHttpRequest. And if you are using some javascript libraries to make the ajax request, you dont have to bother about this matter. Still you can verify "HTTP_X_REQUESTED_WITH" header to see if Django received an XMLHttpRequest or not.
2) Why page redirects?
As I said above, JQuery form plugin is needed for handling the ajax request and its call back. Also, for ajaxSubmit() you need to override the $(#uploadForm).submit()
$('#uploadForm').submit( function (){
$(this).ajaxSubmit(options);
return false;
});
Hope this was helpful :)

Related

Unable to pass formData with other parameters in jQuery

I am trying to pass formData along with other parameters to a PHP script.
Using the $.post method, I was getting an 'Illegal Invocation' error. So I abandoned the $.post method and went to $.ajax method.
As follows:
$('#uploadBtn').on('click', function()
{
var formData = new FormData($('#uploadfile')[0]); // the form data is uploaded file
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
var parameters =
{
formData:formData,
booking:booking,
partner:partner
}
$.ajax({
url: 'process/customer.php',
data: parameters, // <- this may be wrong
async: false,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
});
On the PHP side, I'm trying to get the parameters object like so:
<?php
if(isset($_POST['parameters']))
{
echo "Hello";
$value = $_POST['parameters'];
// I can get the other 2 parameters like this
$company = htmlspecialchars(trim($value['booking']));
$partner = htmlspecialchars(trim($value['partner']));
// not sure how to get the uploaded file information
}
?>
Basically, I am uploading a file to be saved to a directory. But the problem is, I cannot send anything over to the PHP side. I am getting this warning:
"jquery.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/."
I need to be able to send the 'parameters' object over to the PHP script, then access it for processing.
How can I achieve this using the $.ajax method? Then how do I access the formData once on the PHP side?
The parameters is the object you are POSTing. the key value pairs will be based on it's properties. Try accessing them like $_POST['formData'] and $_POST['booking'].
Also... please rework your code to remove the async:false ... TBH this should never have been put into jQuery and is absolutely terrible. Don't feel bad, it's the first thing every newcomer tries when they first start using ajax, myself included. You're going to cause the UI thread to hang for the duration, preventing all user interaction during the call.
EDIT
I didn't realize you are trying to post a file at first, so this is not a complete answer as I don't think you are accessing it correctly. But The important part of this answer is that there is no parameters index of $_POST (which is why not even your echo "hello" is coming back).
if you POST an object that looks like
{
key1 : "value1",
key2 : "value2"
}
they will come through to php as
$_POST['key1'];//"value1";
$_POST['key2'];//"value2";
important to note, files posted to the server are typically found in the $_FILES superglobal. (don't know if AJAX changes that, but I imagine not)
EDIT2
Combining the two... this is the general idea. Make your html + JS look like...
$('#form').on('submit', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('fileInput').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
form_data.append("booking ",booking);
form_data.append("partner",partner);
$.ajax({
url: 'process/customer.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
return false;//prevent default form submission
});
<form id='form'>
<input type='file' id='fileInput' />
<label for='bookingNum'>Booking Num: </label>
<input type='text' id='bookingNum' name='bookingNum' />
<label for='partnerCode'>Partner Code:</label>
<input type='text' id='partnerCode' name='partnerCode' />
<button id='uploadBtn'>Submit</button>
</form>
and try it with your php code like
<?php
if($_POST['bookingNum']){
var_dump($_POST['bookingNum']);
}
if($_POST['partnerCode']){
var_dump($_POST['partnerCode']);
}
if($_FILES['file']){
var_dump($_FILES['file']);
}
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('ID').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
form_data.append("booking ",booking);
form_data.append("partner",partner);
$.ajax({
url: 'process/customer.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
});

handle form request with ajax in django

i have problem with ajax when i send a request from my form it doesn't get the value from the form
this is my view code
def create(request):
if request.method == 'POST':
msg_text = request.POST.get('the_massage')
data = {}
form = ChatApp(message=msg_text, user=request.user)
form.save()
data['message']=form.message
data['user']=form.user.username
return JsonResponse(data)
else:
return JsonResponse({'nothing coming thrue'})
it shod get the_massage variable but it give me null value
this is my ajax function :
$(function () {
$('#main-form').on("submit" ,function () {
console.log("create function is here");
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: {the_massage:$('#msgbox').val()},
dataType: 'json',
success: function(json) {
console.log(json);
console.log('success');
},
error: function(error){
console.log('we have error');
},
});
});
});
when i console log the value it just come through in the console
please help me
and show me this in the console :
Resource interpreted as Document but transferred with MIME type
application/json: "http://localhost:8000/create/".
Call the function in your event:
$('#main-form').on("submit" ,function (event) {
event.preventDefault();
console.log('submited');
console.log($('#msgbox').val())
created();
});
I see many possibles problems here.
1) just for dev propose, delete #login_required (if you have) from your view and add #csrf_exempt to avoid this problem on dev.
2) Please look inside request.body on your view.
3) if point 1 and 2 doesn't work, please put the server response of this call: POST localhost:8000/create 403 (Forbidden)
this is the write answer : i solve this and its on git hub now https://github.com/mhadiahmed/tinypice

Problema sending json file from javascript to laravel controller

im having problems trying to send a JSON file from javascript to Laravel controller, when i press my button from the view i didnt get any response.
This is my code, i appreciate any help or suggestion, thnks.
This is the the JS code:
var horarios= { Lunes: arrLunes, Martes: arrMartes, Miercoles: arrMiercoles, Jueves:arrJueves, Viernes:arrViernes};
var schedule = JSON.stringify(horarios);
//console.log(schedule);
var varurl= 'http://localhost/registerEntrance';
$.ajax({
type: "POST",
url: varurl,
data: {json:schedule},
dataType:'json',
success: function(res) {
var message = res.mesg;
if (message) {
$('.flash').html(message).fadeIn(300).delay(250).fadeOut(300);
};
}
});
When i press my button, doesnt happend anything. The next id the route and the controller code, the JSON file not arrive there yet.
Route::post('registerEntrance', array('as' => 'registerEntrance','uses' => 'CursoController#regisEnt'));
public function regisEnt(){
if(Request::ajax()) {
$data = Input::all();
return $data;
}
}
Thnks for any help.
What are you using to debug your requests? Have you checked your storage/logs/framework/laravel.log (if your log is HUGE you can always delete it and re-run your request)
Working with AJAX can get tricky when it comes to debugging your requests.
My recommendation would be
Open up your browser Inspector, and monitor Network Requests
Analyze the request you're sending.
Set debug to true under config/app.php to actually see a debug
Hope this helps!
I get resolv my problem, i post it if someone is getting a similar inconvenience.
In my view i wasnt create a form.
{!! Form::open(['route' => ['route'], 'method' => 'POST', 'id' =>'form-name']) !!}
{!! Form::close() !!}
This part create a implicit token that is necesary in laravel for use ajax method.
My code JS was modified for getting and send the csrf token.
var form = $('#form-name');
var myurl = form.attr('action');
crsfToken = document.getElementsByName("_token")[0].value;
$.ajax({
url: myurl,
type: 'POST',
data: {data:data},
datatype: 'JSON',
headers: {
"X-CSRF-TOKEN": crsfToken
},
success: function(text){
bootbox.dialog({
closeButton: false,
message: "Ok!",
title: "Perfect!!",
},
error: function(data){
console.log("Error");
}
});
With this change i get arrive to my controller.
Anyway Thnks.

Ajax post not received by php

I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;

how to prevent redirect on form submit

i am getting a form with user parameters when i make an AJAX call to a page which later on is submiited to a url so that i can create a session for the same user in advance and when
that person goes to that site he sees his name there.
i created one div tag with id "abc_session", assign that form (whose id is fm1) to it,and submitted the form.
now as per the requirement session is created but page automatically gets redirected to that site url to which form is submitted.i just don't wan't that to happen.
can anyone please suggest something..or some workaround
the form that AJAX returns looks something like this:
<html>
<body onload="document.fm1.submit();return false">
<form name = "fm1" method="post" action = "https://abcd.com/abc ">
<input type=hidden name ="name" value="xyz">
<input type=hidden name ="login_parameters" value="CDF5D71C5BDB942EE2FB6C285B8DEBFE4C5675137B615CD2276571813AAC872AC8942E26B71026414BED1FEA09427D0B20A50FE2F70032D2E5B382598EC3C71D73EAB4ECBF7273A73BEB98ACEA4A0B775E7772BDC7C6746C355">
</form></body>
</html>
and the script goes like this
$(document).ready(function() {
function callwebsite()
{
$.ajax({
url: "/NASApp/benemain/website",
data: {},
type:"POST",
dataType: 'text',
cache: false,
success: function (data) {
alert("Call made to website.. ");
console.log(data);
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit();
},
error : function(response){
console.log('ERROR');
},
statusCode : {
500 : function() {
console.log('500 error');
window.location.reload(true);
},
401 : function() {
console.log('401 error');
window.location.reload(true);
},
404 : function(){
console.log('400 error');
}
}
});
}
callwebsite();
tried extracting the data and maiking another ajax call as suggested by quentin but getting this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource.This can be fixed by moving the resource to the same domain or enabling CORS."
$.ajax({
url: lcAction,
data: {partner_id:lcPartner,login_parameters:lcLP },
type:"POST",
headers:{'Access-Control-Allow-Origin': '*'},
dataType: 'text',
//crossDomain: true,
//cache: false,
success: function(data)
{
alert("success");
},
error:function(response)
{
//alert("error");
console.log(response);
}
});
You are submitting the form:
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit(); // Here
Don't do that.
Extract the data from it and make another Ajax request.
You should use e.preventDefault() as soon as you submit the form.

Categories

Resources