When I push a green button on http://jazzkredit.ru/ after submission form, I get message "ajaxUrl is not defined" instead of image that should pop up and email that I should receive on email.
Can anybody help me to solve this issue? I have tried to search for an answer on Google and in Stackoverflow but it didn't help.
var formData = new FormData($('form#loanappform')[0]);
$.ajax({
url: ajaxUrl, //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.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
success: completeHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
You need to define ajaxUrl first or just use the direct name of the server-side file to which you are posting:
Method A: var ajaxUrl = "process-ajax.php"
Method B: url: "process-ajax.php"
Related
I want to upload a file using jQuery/Ajax in my Wordpress plugin. The javascript to PHP call works. So the wiring etc. works. But as soon as I post the formData, necessary to post the files, I don't reach the PHP function any more.
The javascript,
var doesntWork = new FormData();
doesntWork.append('file', 'a name');
var withthisItWorks = 'text'
var data = {
'action': 'emfi_file_upload',
'data': doesntWork
}
$.ajax({
type: "POST",
url: ajax_object.ajaxurl,
data: data,
success: function(response) {
jQuery('#emfi-message').html(`<span style="color: green;">Respons: ${response}</span>`);
}
});
The PHP function just returns a string answer:
function emfi_file_upload_callback() {
echo 'Yes, in the callback';
wp_die();
}
When I put the plain text in my data object I get answer from the PHP function. When I put the formData in, there is no answer. I've tried a lot of examples on the internet, but it boils down to this every time. Adding contentType: false and processData: false, as was mentioned somewhere else, didn't help. What's wrong?
All fields that are being sent must be in the formdata object.
Additionally for FormData to work with jQuery.ajax, processData and contentType have to be set to false.
var doesWork = new FormData();
doesWork.append('file', someFile);
doesWork.append('action', 'emfi_file_upload');
$.ajax({
type: "POST",
url: ajax_object.ajaxurl,
data: doesWork,
contentType: false,
processData: false,
success: function(response) {
jQuery('#emfi-message').html(`<span style="color: green;">Respons: ${response}</span>`);
}
});
I'm trying to do a Ajax's loops requests for send files to an API but i don't not what I send at Ajax's data. When I do only file in upload I use the own formdata object and works very well. I tried use loop and each row send an individual file but it's doesn't works too:
Multiple files:
var form_data = new FormData();
for(i=0;i<3;i++){ // 3 length just for tests
form_data.append('file', $('#myfile').prop('files')[i]);
}
for (var value of form_data.values()) {
$.ajax({
url: 'URI',
data: value,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
alert("Success!")
},
error: function(e){
alert("Error")
}
});
}
After click on submit beforeSend: works but it does not call success: also there is no console error . The data also submit to database correctly ! Then why it not call the success: . Please Help
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$(".alert").removeClass("hide");
var msg = $.ajax({
type: "GET",
url: actionurl,
async: false
}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function() { // wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
});
});
Console Message
Object {readyState: 4, responseText: "<strong>Seat Booked Successfully</strong>", status: 200, statusText: "OK"}
In a Ajax call 'dataType' attributes means what data format can be expect from client(browser). As per error message server is returning 'string' instead 'json'.
But on the other hand, given ajax call is expecting json data to be returned by backend server. Either provide a
valid JSON in response or change datatype to html.
In your AJAX call settings you set dataType to json, but in return you provide a string.
dataType (default: Intelligent Guess (xml, json, script, or html)) The
type of data that you're expecting back from the server. If none is
specified, jQuery will try to infer it based on the MIME type of the
response
So, you have two solutions:
Provide a valid JSON in response
Do not ask for JSON by changing your dataType value (to html), or by removing it.
I had similar problem. As you are redirecting page in success you need to use
e.preventDefault(); // to prevent page refresh
after the ajax call or
return false; // to prevent page refresh
Something like this :
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$( ".alert" ).removeClass( "hide" );
var msg = $.ajax({type: "GET", url: actionurl, async: false}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function(){// wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
return false; e.preventDefault(); //any one of this options to prevent page refresh after ajax call
});
});
So, i have an image on my page with this for src attribut :
src="blob:47d2cdd6-0ff0-401f-a195-a671d0db9b05"
I need to send this blob to php with ajax, for save this blob (a gif in my case) on my server.
This is my ajax :
var data = new FormData();
data.append('file', $('myImage').attr('src'));
$.ajax({
type:"POST",
url: "/webcam/",
data: data,
contentType: false,
processData: false,
success: function () {
parent.$.fancybox.close();
},
error: function() {
alert("not so boa!");
}
});
But, when i am on my php script, i don't know how to use this blob... When i try readimageblob() from imagick for example, i have an error.
Am i in the good way ?
Is it possible to post image file using the jQuery's ajax post method. Would it work if I just put the file data in the POST request's 'data' parameter?
I am using django framework. This is my first attempt:
$('#edit_user_image').change(function(){
var client = new XMLHttpRequest();
var file = document.getElementById("edit_user_image");
var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value
/* Create a FormData instance */
var formData = new FormData();
formData.append("upload", file.files[0]);
client.open("post", "/upload-image/", true);
client.setRequestHeader("X-CSRFToken", csrftoken);
client.setRequestHeader("Content-Type", "multipart/form-data; charset=UTF-8; boundary=frontier");
client.send(formData); /* Send to server */
});
The problem with this is that I don't get the'request.FILES' object on the serer side in my 'views.py'.
I also tried doing it with ajax post but it doesn't work either.
$('#edit_user_image').change(function(){
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
content:document.getElementById("edit_user_image").files[0],}
$.post("/upload-image/", data, function(){
});
});
Edit from one of the answers:
$('#edit_user_image').change(function(){
var formData = new FormData($("#edit_user_image")[0]);
$.ajax({
type: "POST",
url: "/upload-image/",
xhr: function() { // custom xhr
// If you want to handling upload progress, modify below codes.
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress', yourProgressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
data: formData,
// Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false,
beforeSend: function(xhr) {
// If you want to make it possible cancel upload, register cancel button handler.
$("#yourCancelButton").click(xhr.abort);
},
success: function( data ) {
// Something to do after upload success.
alert('File has been successfully uploaded.');
location.reload();
},
error : function(xhr, textStatus) {
// Something to do after upload failed.
alert('Failed to upload files. Please contact your system administrator. - ' + xhr.responseText);
}
});
});
This is my final working solution:
$('#edit_user_image').change(function(){
var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value
var formData = new FormData($("#edit_user_image")[0]);
var formData = new FormData();
formData.append("file", $('#edit_user_image')[0].files[0]);
formData.append("csrfmiddlewaretoken", csrftoken);
$.ajax({
type: "POST",
url: "/upload-image/",
data: formData,
contentType: false,
processData: false,
});
});
You can if you use FormData, otherwise you have to use Flash or iframes or Plugins (these ones use flash or iframes), FormData comes with HTML5 so it won't work in IE <= 9, a great guy created a replica of FormData for old browsers, to use it you only have to put formdata.js in the head tag. So in my opinion you have to use FormData.
We say you have a form like this:
<form method="POST" name="form" id="form" enctype="multipart/form-data">
<input type="file" id="img"/>
<input type="submit"/>
</form>
you have to get the img chosen by the user so your javascript have to look like this:
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var data = new FormData($('form').get(0));
$.ajax({
url: :"/URL",
method: "POST",
data: data,
success: function(data){},
error: function(data){},
processData: false,
contentType: false,
});
});
});
and now you are going to be able to retrieve the img chosen by the user in django with:
request.FILES
Yes. You can post your image file using jQuery's ajax.
Try below code snippet.
// Your image file input should be in "yourFormID" form.
var formData = new FormData($("#yourFormID")[0]);
$.ajax({
type: "POST",
url: "your_form_request_url",
xhr: function() { // custom xhr
// If you want to handling upload progress, modify below codes.
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress', yourProgressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
data: formData,
// Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false,
beforeSend: function(xhr) {
// If you want to make it possible cancel upload, register cancel button handler.
$("#yourCancelButton").click(xhr.abort);
},
success: function( data ) {
// Something to do after upload success.
alert('File has been successfully uploaded.');
location.reload();
},
error : function(xhr, textStatus) {
// Something to do after upload failed.
alert('Failed to upload files. Please contact your system administrator. - ' + xhr.responseText);
}
});
My suggestion is add "return false after the ajax block.