Related
I need to validate, on server side, if a person with a given registration number is already on the database. If this person is already registered, then I proceed with the program flow normally. But, if the number is not already registered, then I'd like to show a confirmation dialog asking if the operator wants to register a new person with the number entered and, if the operator answers yes, then the person will be registered with the number informed on the form on it's submission.
I've tried
Server side(PHP):
if (!$exists_person) {
$resp['success'] = false;
$resp['msg'] = 'Do you want to register a new person?';
echo json_encode($resp);
}
Client side:
function submit(){
var data = $('#myForm').serialize();
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
return false;
}
I can't even see the alert, that's where I wanted to put my confirmation dialog, with the message written on server side. Other problem, how do I resubmit the entire form appended with the operator's answer, so the server can check if the answer was yes to register this new person?
EDIT
I was able to solve the problem this way:
Server side(PHP):
$person = find($_POST['regNo']);
if ($_POST['register_new'] === 'false' && !$person) {
$resp['exists'] = false;
$resp['msg'] = 'Do you want to register a new person?';
die(json_encode($resp)); //send response to AJAX request on the client side
} else if ($_POST['register_new'] === 'true' && !$person) {
//register new person
$person = find($_POST['regNo']);
}
if($person){
//proceed normal program flow
}
Client side:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
var ajax1 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function (response) {
if (!response.exists && confirm(response.msg)) {
document.getElementById('register_new').value = 'true'; //hidden input
dados = $('#myForm').serialize(); //reserialize with new data
var ajax2 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function () {
document.getElementById('register_new').value = 'false';
$('#myForm').unbind('submit').submit();
}
});
} else if (response.success) {
alert(response.msg);
$('#myForm').unbind('submit').submit();
}
}
});
}
There doesn't appear to be anything wrong with your PHP.
The problem is (1) You are doing the alert inside of an error callback, and your request isn't failing, so you don't see the alert. (2) You are alerting the string 'response' instead of the variable response.
It is also worth noting that you should be using the .done() and .fail() promise methods (http://api.jquery.com/jquery.ajax/#jqXHR).
Here is the fixed JS:
function submit() {
var data = $('#myForm').serialize();
// Same as before, with the error callback removed
var myAjaxRequest = $.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
});
// The request was successful (200)
myAjaxRequest.done(function(data, textStatus, jqXHR) {
// The data variable will contain your JSON from the server
console.log(data);
// Use a confirmation dialog to ask the user your question
// sent from the server
if (confirm(data.msg)) {
// Perform another AJAX request
}
});
// The request failed (40X)
myAjaxRequest.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
return false;
}
Also, you are setting a 'status' in PHP and checking that in the JS (I presume). What you want to be doing is setting a HTTP status code from the server, as below:
if (!$exists_person)
{
$resp['msg'] = 'Do you want to register a new person?';
// 400 - Bad Request
http_response_code(400);
echo json_enconde($resp);
}
Then, jQuery will determine whether the request failed based on the status code you respond with. 200 is a successful request, and 400 numbers are fail.
Check out this page for a full list: https://httpstatuses.com/
Okay so this is a two part question; I'll try my best to answer both parts:
Part 1: How to detect if success is false and trigger the confirmation popup?
In jQuery.ajax the error handler is triggered based on response code. This is probably not what you want. You can use your success handler and test the value res.success to see if it's true or false. It would be something along the lines of:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
}).done(function(res) {
if (!res.success) {
alert(res.msg);
}
});
}
Part 2: How do I resubmit with a confirmation?
Working off of our previous code we will make some changes that allow for submit() to be passed an argument registerNew. If registerNew is true we will pass it as a param to the ajax handler in the PHP so it knows we want to register a new person. The Javascript will look something like this:
function submit(e, registerNew) {
if (e) e.preventDefault();
var data = $('#myForm').serialize();
var ajax_options = {
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
};
ajax_options.data.register_new = !!registerNew;
$.ajax(ajax_options).done(function(res) {
if (!res.success && confirm(res.msg)) {
submit(null, true);
}
});
}
As you can see here, we are passing a new register_new param in the data in our ajax options. Now we need to detect this on the PHP side, which is easy enough and looks like this (this goes in your php ajax handler):
if ($_POST["register_new"]) {
// new user registration code goes here
} else {
// your existing ajax handler code
}
Add confirm inside submit function
function submit(){
var data = $('#myForm').serialize();
if (confirm('Are you ready?')) {
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
}
return false;
}
I'm trying to compile project https://github.com/kannan4k/django-carpool
please refer this project repo for this issue.
and end up with following error during ajax call.
Failed to load resource: the server responded with a status of 400 (BAD REQUEST).
I know this is because of ajax post request & CSRF tokens.
following is my setting.
1. disable "django.middleware.csrf.CsrfViewMiddleware"
2. in new_trip page I have a button (Postdata)so this button sends an ajax request.
My View:-
#login_required
def save_journey(request):
if request.is_ajax() and request.method == "POST":
try:
res = json.loads(request.body)
cords = res['cords']
cords = [[x['d'], x['e']] for x in cords]
distance = res['distance']
start_place = res['start']
end_place = res['end']
clusters = clusterize_latlngs(cords, distance)
time = datetime.datetime.strptime(res['time'], "%m/%d/%Y %H:%M")
Trip.objects.create(user=request.user, time=time, cluster=json.dumps(clusters), travel_distance=distance,
start_place=start_place, end_place=end_place)
return HttpResponse()
except:
return HttpResponseBadRequest()
else:
return HttpResponseNotAllowed(['POST'])
Ajax call (home.js)
function postData() {
radius = 0;
var url = "/save_journey/";
var dataType = 'json';
if (type == 'r') {
radius = $('#radius').val();
url = "/get_results/";
dataType = 'html';
}
var data = JSON.stringify({
cords: myroute,
time: document.getElementById('dateStart').value,
start: document.getElementById('startPlace').innerHTML,
end: document.getElementById('endPlace').innerHTML,
radius: radius,
distance: distance
});
$.ajax({
type: "POST",
url: url,
dataType: dataType,
data: data,
success: function (data) {
if (type == 'r') {
window.location.href = "/search_results/";
}
else {
window.location.href = '/trip_success/';
}
},
error: function () {
console.log('Error getting options list...')
}
});
console.log(data);
}
this code is not able to call /save_journey/ URL.
I tried many answers from stack overflow & didn't figure out what is the problem .
You should never disable csrftoken unless you're absolutely sure about what you're doing. It's an important part of the security features implemented in Django.
Here is an example of how you can use Ajax with Django with csrftoken:
You can use Ajax Post to send JSON to Django and then handle the arguments as a dict(). Here is an example:
In browser (JQuery/JavaScript):
function newModule() {
var my_data = $("#my_element").val(); // Whatever value you want to be sent.
$.ajax({
url: "{% url 'modules' %}", // Handler as defined in Django URLs.
type: "POST", // Method.
dataType: "json", // Format as JSON (Default).
data: {
path: my_data, // Dictionary key (JSON).
csrfmiddlewaretoken:
'{{ csrf_token }}' // Unique key.
},
success: function (json) {
// On success do this.
},
error: function (xhr, errmsg, err) {
// On failure do this.
}
});
In server engine (Python):
def handle(request):
# Post request containing the key.
if request.method == 'POST' and 'my_data' in request.POST.keys():
# Retrieving the value.
my_data = request.POST['my_data']
# ...
Hope this helps.
I am using dropzone in my Code Igniter Project.
With every drag of a file, dropzone creates an ajax request and my files is getting stored on the server too. But now, my requirement is that I want to send additional data (DYNAMIC) alongside the file.
With the use of params, Only static datas can be sent, but the data I want to send will be changing everytime.
This is how my code looks:
<script>
Dropzone.autoDiscover = false;
Dropzone.options.attachment = {
init: function(){
this.on('removedfile',function(file){
// console.log('akjsdhaksj');
var fileName = file.name;
$.ajax({
type: 'POST',
url: "<?php echo BASE_URL.'index.php/admin/mail_actions/deleteFile' ?>",
data: "id="+fileName,
dataType: 'html'
});
});
},
// params: {
// customerFolder: $('#toValue').substr(0, toValue.indexOf('#')),
// },
dictDefaultMessage:"Click / Drop here to upload files",
addRemoveLinks: true,
dictRemoveFile:"Remove",
maxFiles:3,
maxFilesize:8,
}
$(function(){
var uploadFilePath = "<?php echo BASE_URL.'index.php/admin/mail_actions/uploadFile' ?>";
var myDropzone = new Dropzone("div#attachment", { url: uploadFilePath});
});
</script>
Anyway I can achieve it?
I got it.
This is what I had to use
myDropzone.on('sending', function(file, xhr, formData){
formData.append('userName', 'bob');
});
Abhinav has the right and working answer I only want to give a second option to use it in the options object (for example if you have multiple Dropzone sections on one page.)
myDropzone.options.dropzoneDivID = {
sending: function(file, xhr, formData){
formData.append('userName', 'Bob');
}
};
In case you have a nested payload object - e.g. to add a name to your file and your api only accepts something like this
{
someParameter: {
image: <my-upload-file>,
name: 'Bob'
}
}
your dropzone setup would look like this
var myDropzone = new Dropzone("div#attachment", {
url: uploadFilePath,
paramName: 'someParameter[image]'
});
myDropzone.on('sending', function(file, xhr, formData){
formData.append('someParameter[image]', file);
formData.append('someParameter[userName]', 'bob');
});
I only added this as there was no example for nested parameters documented since now.
i was using JQuery and this is how worked for me :
$("#dZUpload").dropzone({
url: "ajax/upload_img_ben.php",
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :" + imgName);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
sending: function(file, xhr, formData){
formData.append('id', '5');
}
});
I'm trying to add an id attribute to each file uploaded in Dropzone.js, So I can sort it later on.
This is my code:
Dropzone.options.pictureDropzone = {
paramName: "file",
addRemoveLinks: true,
init: function() {
this.on("success", function(file, response) {
file.serverId = response.id;
$(file.previewTemplate).find('.dz-preview').attr('id', "document-" + file.serverId);
});
}
};
The line
$(file.previewTemplate).find('.dz-preview').attr('id', "document-" + file.serverId);
Should add the id, but it does nothing.
Tried it with prop() too.
If I choose a different element, it does work fine. for example, this works for .dz-details
$(file.previewTemplate).find('.dz-details').attr('id', "document-" + file.serverId);
But I cannot seem to find a way to add it to the dz-preview element.
The HTML structure looks like that:
<div class="dz-preview dz-processing dz-image-preview dz-success">
<div class="dz-details"> ... </div>
<div class="dz-progress"> ... </div>
<div class="dz-success-mark"> ... </div>
</div>
Thank you for the help :)
I know this is old but if anyone is still looking for the answer: -
this.on("success", function(file, response) {
file.previewElement.id = response.id;
});
Cast the previewElement into jQuery object and perform any action.
this.on("success", function(file, response) {
$(file.previewElement).attr("id", response.id);
});
this.on("success", function(file, response) {
file.serverId = response.id;
$(".dz-preview:last-child").attr('id', "document-" + file.serverId);
});
I had similar problem but tried it through declaring a variable in javascript ,following is code :
$("#fileUpload${dropdown}").dropzone(
{
url : "uploadAdditionalFile?name="+$("#fileUpload${dropdown} div:first-child").prop('id'),
addRemoveLinks : true,
maxFiles : 1,
init : function() {
var imageId = $("#fileUpload${dropdown} div:first-child").prop('id');
this.on("maxfilesexceeded",
function(file) {
alert("Only one file can be uploaded at a time");
this.removeFile(file);
});
this.on("addedfile",
function(file) {
switch (file.type) {
case 'application/pdf':
this.emit("thumbnail",file,"/sbms/static/img/pdf.png");
break;
case 'application/msword':
this.emit("thumbnail",file,"/sbms/static/img/word.png");
break;
}
}
);
this.on('removedfile', function(file){
$.ajax({
type : "GET",
url : "removeAdditionalMediaPreviewForm?id="+imageId,
dataType : "json",
async : false,
success : function(response) {
if (response.status == 'SUCCESS') {
alert("File removed successfully.")
}else {
alert("File not removed successfully.")
}
}
});
});
},
success : function(file,response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :"+ imgName);
},
error : function(file,response, xhr) {
alert("Unable to upload file. Please check if it is a valid doc or pdf file.");
this.removeFile(file);
}
});
imageId is a variable which stores the id and is used later on while file remove.
This will fail spectacularly if the user drops multiple files.(Szczepan Hołyszewski Dec 17 '15 at 18:45);
BryanFoong answer won't fail if you set the option uploadMultiple: false. Which is set so by default. In this case Dropzone sends separate request to the server for each file. Therefore "success" event triggers for each individual file.
In case the uploadMultiple: true. Dropzone will send single request to server for all files. And "success" event will trigger once. And following code will handle that.
YourDropzoneInstance.on("success", function(file, response) {
response.files.forEach(function(file) {
file.previewTemplate.id = file.id;
})
})
Again you need to return from server array of files.
In PHP it will look like
function yourFileUploadHandler() {
...
// your server file upload implementation
$response = [
"files" => [
["id" = 1, ...],
["id" = 2, ...],
...
],
];
return json_decode($response);
}
I am using dropzone.js.
When I try to delete files only the thumbnails get deleted but not the files from server.
I tried some ways but it just gives me the name of the image which was on client side and not the name on server side(both names are different, storing names in encrypted form).
Any help would be much appreciated..
Another way,
Get response from your server in JSON format or a plain string (then use only response instead of response.path),
dropzone.on("success", function(file, response) {
$(file.previewTemplate).append('<span class="server_file">'+response.path+'</span>');
});
Here, the server can return a json like this,
{
status: 200,
path: "/home/user/anything.txt"
}
So we are storing this path into a span that we can access when we are going to delete it.
dropzone.on("removedfile", function(file) {
var server_file = $(file.previewTemplate).children('.server_file').text();
alert(server_file);
// Do a post request and pass this path and use server-side language to delete the file
$.post("delete.php", { file_to_be_deleted: server_file } );
});
After the process, the preview template will be deleted by Dropzone along with file path stored in a span.
The way I handle this, is after each file is uploaded and stored on the server, I echo back the name I give the file on my server, and store it in a JS object, something like this:
PHP:
move_uploaded_file($_FILES['file']['tmp_name'], $newFileName);
echo $newFileName;
JS:
dropZone.on("success", function(file, serverFileName) {
fileList[serverFileName] = {"serverFileName" : serverFileName, "fileName" : file.name };
});
With this, you can then write a delete script in PHP that takes in the "serverFileName" and does the actual deletion, such as:
JS:
$.ajax({
url: "upload/delete_temp_files.php",
type: "POST",
data: { "fileList" : JSON.stringify(fileList) }
});
PHP:
$fileList = json_decode($_POST['fileList']);
for($i = 0; $i < sizeof($fileList); $i++)
{
unlink(basename($fileList[$i]));
}
Most simple way
JS file,this script will run when you click delete button
this.on("removedfile", function(file) {
alert(file.name);
$.ajax({
url: "uploads/delete.php",
type: "POST",
data: { 'name': file.name}
});
});
php file "delete.php"
<?php
$t= $_POST['name'];
echo $t;
unlink($t);
?>
The file will be deleteed when you click the "Remove" button :
Put this on your JS file or your HTML file (or your PHP view/action file):
<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = {
// Change following configuration below as you need there bro
autoProcessQueue: true,
uploadMultiple: true,
parallelUploads: 2,
maxFiles: 10,
maxFilesize: 5,
addRemoveLinks: true,
dictRemoveFile: "Remove",
dictDefaultMessage: "<h3 class='sbold'>Drop files here or click to upload document(s)<h3>",
acceptedFiles: ".xls,.xlsx,.doc,.docx",
//another of your configurations..and so on...and so on...
init: function() {
this.on("removedfile", function(file) {
alert("Delete this file?");
$.ajax({
url: '/delete.php?filetodelete='+file.name,
type: "POST",
data: { 'filetodelete': file.name}
});
});
}}
</script>
..and Put this code in your PHP file :
<?php
$toDelete= $_POST['filetodelete'];
unlink("{$_SERVER['DOCUMENT_ROOT']}/*this-is-the-folder-which-you-put-the-file-uploaded*/{$toDelete}");
die;
?>
Hope this helps you bro :)
I've made it easier, just added new property serverFileName to the file object:
success: function(file, response) {
file.serverFileName = response.file_name;
},
removedfile: function (file, data) {
$.ajax({
type:'POST',
url:'/deleteFile',
data : {"file_name" : file.serverFileName},
success : function (data) {
}
});
}
success: function(file, serverFileName)
{
fileList['serverFileName'] = {"serverFileName" : serverFileName, "fileName" : file.name };
alert(file.name);
alert(serverFileName);
},
removedfile: function(file, serverFileName)
{
fileList['serverFileName'] = {"serverFileName" : serverFileName, "fileName" : file.name };
alert(file.name);
alert(serverFileName);
}
When you save the image in upload from there you have to return new file name :
echo json_encode(array("Filename" => "New File Name"));
And in dropzone.js file :
success: function(file,response) {
obj = JSON.parse(response);
file.previewElement.id = obj.Filename;
if (file.previewElement) {
return file.previewElement.classList.add("dz-success");
}
},
And when the dropzone is initialize..
init: function() {
this.on("removedfile", function(file) {
var name = file.previewElement.id;
$.ajax({
url: "post URL",
type: "POST",
data: { 'name': name}
});
});
return noop;
},
Now you will receive new image file and you can delete it from server
You can add id number of uploaded file on the mockFile and use that id to delete from server.
Dropzone.options.frmFilesDropzone = {
init: function() {
var _this = this;
this.on("removedfile", function(file) {
console.log(file.id); // use file.id to delete file on the server
});
$.ajax({
type: "GET",
url: "/server/images",
success: function(response) {
if(response.status=="ok"){
$.each(response.data, function(key,value) {
var mockFile = {id:value.id,name: value.name, size: value.filesize};
_this.options.addedfile.call(_this, mockFile);
_this.options.thumbnail.call(_this, mockFile, "/media/images/"+value.name);
_this.options.complete.call(_this, mockFile);
_this.options.success.call(_this, mockFile);
});
}
}
});
Server Json return for getting all images already uploaded /server/images:
{
"data":[
{"id":52,"name":"image_1.jpg","filesize":1234},
{"id":53,"name":"image_2.jpg","filesize":1234},
]}
In my case server sends back some ajax response with deleteUrl for every specific image.
I just insert this url as 'data-dz-remove' attribute, set in previewTemplate already.
As I use jquery it looks so:
this.on("success", function (file, response) {
$(file.previewTemplate).find('a.dz-remove').attr('data-dz-remove', response.deleteUrl);
});
Later this attr used to send ajax post with this url to delete file on server by removedfile event as mentioned above.
This simple solution will work for single files upload, no need for DOM manipulation.
PHP Upload Script
[...]
echo $filepath; // ie: 'medias/articles/m/y/a/my_article/my-image.png'
JS Dropzones
this.on("success", function(file, response) {
file.path = response; // We create a new 'path' index
});
this.on("removedfile", function(file) {
removeFile(file.path)
});
JS outside of Dropzone
var removeFile = function(path){
//SEND PATH IN AJAX TO PHP DELETE SCRIPT
$.ajax({
url: "uploads/delete.php",
type: "POST",
data: { 'path': path}
});
}