This question already has answers here:
Uploading both data and files in one form using Ajax?
(13 answers)
Closed 9 years ago.
I am currently POSTING my form through AJAX with the following code:
$(document).ready(function(){
$("form#createForm").submit(function() { // loginForm is submitted
$("form#createForm input#createForm_submit").attr('disabled','disabled');
tinyMCE.triggerSave();
$.ajax({
type: "POST",
dataType: "json",
url: "perform", // URL of the Perl script
data: $("#createForm").serialize(),
// script call was successful
// data contains the JSON values returned by the Perl script
success: function(data){
$('div.form-group').each(function(){
$(this).removeClass('has-error');
});
if (data.error) { // script returned error
var myList = $('ul.msg-list').empty();
$.each(data.msg, function(key,item) {
$("div."+key).addClass('has-error');
$('<li>').text(item.errtxt).appendTo(myList);
});
$('div#create_createresult').html('some error').html(myList);
$('div#create_createresult').addClass("text-danger");
$("form#createForm input#createForm_submit").removeAttr('disabled');
} // if
else
{ // login was successful
//$('form#login_loginform').hide();
$('div#create_createresult').text(data.msg);
$('div#create_createresult').addClass("success");
} //else
} // success
}); // ajax
$('div#login_loginresult').fadeIn();
return false;
});
});
Now I want to add the posibility of uploading a picture in the same form and just implement it in this JQUERY and in the same server-side script. My only problem is, I don't know how to do it.. I have tested the above, and I find, that it doesn't pass the $_FILES-variable to my server side script.
Can anyone lead me in any direction of, what I need to do, to add the possibility of image upload with this script?
try to use this.
// grab your file object from a file input
$('#fileInput').change(function () {
sendFile(this.files[0]);
});
// can also be from a drag-from-desktop drop
$('dropZone')[0].ondrop = function (e) {
e.preventDefault();
sendFile(e.dataTransfer.files[0]);
};
function sendFile(file) {
$.ajax({
type: 'post',
url: '/targeturl?name=' + file.name,
data: file,
success: function () {
// do something
},
xhrFields: {
// add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet)
onprogress: function (progress) {
// calculate upload progress
var percentage = Math.floor((progress.total / progress.totalSize) * 100);
// log upload progress to console
console.log('progress', percentage);
if (percentage === 100) {
console.log('DONE!');
}
}
},
processData: false,
contentType: file.type
});
}
Related
I have been struggling with a problem for some time. I cannot understand the reason as it happens in a specific case, not with the others.
I have a javascript function that calls a PHP script to upload a file to the server (standard code, have been using it and works perfectly normally).
function upload_picture(fieldID, success, error) {
var folderName;
switch (fieldID) {
case "pop_drawing":
folderName = "pop_dwg";
break;
case "pop_installation":
folderName = "pop_inst";
break;
case "pop_picture":
folderName = "pop_pict";
break;
}
var file_data = $('#' + fieldID).prop('files')[0];
var form_data = new FormData();
form_data.append('folder', folderName);
form_data.append('file', file_data);
$.ajax({
url: 'dbh/upload.php',
dataType: 'text',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function (response) {
event.preventDefault();
console.log (response); // display success response from the PHP script
if (response.indexOf("yüklendi") > 0) {
success();
}
},
error: function (response) {
event.preventDefault();
console.log (response); // display success response from the PHP script
error(response);
}
});
}
The function is called from several points in the code and it works OK except one point. At this particular point when it returns it changes the page URL from
http://localhost/pop/#
to
http://localhost/pop/?pop_drawing=&pop_installation=&pop_picture=Compelis-Logo.jpg&pop_need_special_prod=Hay%C4%B1r&pop_need_application=Hay%C4%B1r&pop_order_made=Evet&pop_approval=4&pop_cost_visible=Hay%C4%B1r#
due to a reason I could not understand. This string in the URL line are some parameters on the web page where I press the button to call the function.
The code which call the function is:
function uploadPopPicture () {
if ($('#pop_picture_label').html() !== 'Seçili dosya yok...') {
upload_picture('pop_picture',
function(){
console.log('Görsel yüklendi...');
},
function(error){
console.log('Error:', error);
});
}
}
Same code (obviously with different parameters) is used elsewhere in the program and works OK.
Any ideas what I might be missing.
Many thanks in advance
A button's default behaviour is "submit". If you don't specify any particular behaviour then that's what it will do. So when clicked it will submit your form, regardless of any JavaScript.
Add the attribute type="button" to your button HTML and that will stop it from automatically submitting the form.
I am using a plugin to autosave a textbox. However, when the autosave function is called, the text box cannot be typed into. I want users to be able to continue typing while the auto save is posted via AJAX.
tinymce.PluginManager.add('jsave', function(editor) {
// Get the form element into a jQuery object.
var $form = $(editor.formElement);
// Settings for initialization.
var settings = {
// Interval to execute the function. Default is 15000 (ms 1000 = 1 second).
//seconds: editor.getParam('jsave_seconds') || 2000,
seconds: 2000,
// This is our url that we will send data. If you want to have two different links,
// one for ajax and one for manual post this setting is pretty useful!
url: editor.getParam('jsave_url') || $form.attr('action'),
// This is the callback that will be executed after the form is submitted
callback: editor.getParam('jsave_callback')
};
$('.form_header,#attachbox').change(function (){
tinymce.get('mail_body').isNotDirty=0;
$("#save_status").html("Not saved");
});
var interval = setInterval(function() {
// Quit the function if the editor is not dirty.
if (!editor.isDirty()){
return;
}
// Update the original textarea
editor.save();
// Create a data string from form elements.
ds =$form.serialize();
// $form.find(':input').each(function (i, el) {
// $el = $(el);
// if($el.attr('name')!=null)
// ds[$el.attr('name')] = $el.val(); }
// );
$("#save_status").html("Saving");
$.ajax({
url: settings.url,
type: $form.attr('method'),
data: ds,
dataType:"json",
async:false,
success: function(msg) {
if (settings.callback){
//editor.setContent(msg.draft_body);
$("#save_status").html("Saved");
settings.callback(msg);
}
else{
$("#save_status").html("Saving error");
console.log(msg);
}
}
});
}, settings.seconds);
}); //vsk.me/en/28/adding-an-autosave-plugin-to-tinymce-2#sthash.jsOruJSd.dpuf
I have solved this problem:
just change form async:false, to async:true, in ajax calling part.
$.ajax({
url: settings.url,
type: $form.attr('method'),
data: ds,
dataType:"json",
async:true,
success: function(msg) {
if (settings.callback){
//editor.setContent(msg.draft_body);
$("#save_status").html("Saved");
settings.callback(msg);
}
else{
$("#save_status").html("Saving error");
console.log(msg);
}
}
});
Why don't you just disable it while doing the ajax call and enable again on ajax call ends?
You have a reference to enable/disable the field via JavaScript here:
make readonly/disable tinymce textarea
That way you could use the complete attribute on your Ajax call to enable the field again after either succes or error response like this:
var interval = setInterval(function() {
// Quit the function if the editor is not dirty.
if (!editor.isDirty()){
return;
}
// Update the original textarea
editor.save();
// Create a data string from form elements.
ds =$form.serialize();
$("#save_status").html("Saving");
tinyMCE.get('textarea_id').getBody().setAttribute('contenteditable', false);
$ajax({
url: settings.url,
type: $form.attr('method'),
data: ds,
dataType:"json",
async:false,
success: function(msg) {
if (settings.callback){
//editor.setContent(msg.draft_body);
$("#save_status").html("Saved");
settings.callback(msg);
}
else{
$("#save_status").html("Saving error");
console.log(msg);
}
},
error:function(){
//DO ERROR STUFF
},
complete:function(){
tinyMCE.get('textarea_id').getBody().setAttribute('contenteditable', true);
}
});
I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});
I have image upload function in my "form" which gets uploaded via ajax. So, until image is uploading, User continues to fill rest of form. and than click on submit button which is another ajax function to submit whole form.
Problem is I have below function for image upload :-
jQuery(window).load(function(){
jQuery(':button').click(function(){
var formData = new FormData(jQuery('form')[0]);
jQuery.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = jQuery.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function(e) { $('#progress').css('display', 'block'); },
success: function(e) {
if (e != "no" && e != 'dir') {
$('#img').attr("src", e);
$('#imglinktosent').val(e);
} else if (e == 'dir') {
alert('Oops! We could not find \image\ directory or may be permission is not correct');
} else {
alert('File was not Uploaded, Kindly Upload Image with Size less than 512KB');
}
} ,
error: function(e) { alert('error' + e.message); } ,
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
});//]]>
It was hindering my complete form submission, therefore i changed it into Below function.
function uploadimage(){
jQuery(':button').click(function(){
var formData = jQuery('#myfile').val();
jQuery.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = jQuery.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function(e) { $('#progress').css('display', 'block'); },
success: function(e) {
if (e != "no" && e != 'dir') {
$('#img').attr("src", e);
$('#imglinktosent').val(e);
} else if (e == 'dir') {
alert('Oops! We could not find \image\ directory or may be permission is not correct');
} else {
alert('File was not Uploaded, Kindly Upload Image with Size less than 512KB');
}
} ,
error: function(e) { alert('error' + e.message); } ,
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
}
So, that whenever user clicks on "upload image" button. Image will get uploaded by "uploadimage()" function set on "button" with event "onclick".
But PHP was giving error with "undefined index myfile" in upload.php
After searching for a while, i found, There was "request payload" and no formdata option in header.
After searching more in stackoverflow, i found i have to specify this too :
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
as if you would have noticed at line 30, I am sending direct formData
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
**
But I am unsure where should i specify
**
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
in my uploadimage() function to work.
Ajax doesn't support binary file transfers by default. I think it is more easy to base-64 encode your image and just post the data string to the server. You can use a html5 canvas element to get a base-64 encoded string from your image canvas.toDataURL(); . Server side you'll need to decode this string with base64_decode($yourimagedatastring);
This question already has an answer here:
javascript alert messages is not show in mvc3
(1 answer)
Closed 9 years ago.
I am working on a form in mvc3 and use form validations in javascript and ajax.
in my form i add code and description in database and before form submission want to check that code already exist in database or not.i get the code in javascript through ajax function call andd eturn data in json form. when i get the data i display error message in alert to user that code already exist. but my alert is not display.what can i do for it.
below is my javascript save button click function
$('#sve').click(function () {
//e.preventDefault();
var iscodeexis = CodeExistChk();
if (iscodeexis) {//
//***********************CODE TO SAVE DATA IN DATABASE***********************************
var person = { AcCode: $('#AcCode').val(), Descrip: $('#Descrip').val(), AddOn: dd };
$.ajax({
url: '/Home/Save?action=Sve',
type: "POST",
data: JSON.stringify(person),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
// $('#message').html('Record saved successfully' + result).fadeIn();
alert("Record saved successfully");
},
error: function () {
// $('#message').html('Error Occurred').fadeIn();
alert("Record not saved successfully");
}
});
}//end of is valid function chk
else
return false;//if isvalid function return false then save button also return false
}); //end button clcik function
function CodeExistChk() {
subA = $('#AcCode').val().trim();
// ===========================check whether code exist already or not
if (subA.length === 10) {
str1 = "select AcCode from Account where AcCode='";
str2 = str1 + subA + "'";
GetCodeData(str2); //check whether code exist or not
strRes = strRes.substring(1, strRes.length - 1);
if (strRes.length > 0 && strRes != "") //if code exist then return false and not allow to enter code
{
alert('Code already exist cannot insert record');
return false;
}
}
//===============================
}
below is getcodedata function which use in above code to get code from database
//===============FUNCTION TO GET CODE FROM DATABASE TO USE IN JS FILE==========
function GetCodeData(Str) {
var p = {
StrSql: Str
};
$.ajax({
url: '/Home/GetGenVal',
type: 'POST',
// contentType: 'application/x-www-form-urlencoded',
dataType: "JSON",
contentType: "application/json; charset=utf-8",
processData: false,
crossDomain: false,
traditional: true,
data: JSON.stringify(p),
cache: false,
// success: callback
success: function (data) {
//$("#Descrip").val(data);
// ResSubCode = data;
strRes = null;
strRes = data;
return strRes;
}
});
}
waiting for early solution.
Whoa, I see a some mistakes in this code.
At first, never construct your sql queries on client side to execute them. What if I modify the query to be a "delete from"? Bye bye database!
I would simply edit your logic and use a [RemoteAttribute] MVC3/4 feature to call a controller action and return simply a true or false.
Check it here: Remoteattribute test usage
You cannot be wrong!
Vincenzo.