Peace And blessing be upon you :)
Basically I have two function, each performs an ajax call. Something like:
1:
function step1(){
var formdata = new FormData();
formdata = {
'URI': sendtosev
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
$('.UID).text(result);
}
});
}
2:
function step2(){
var stkname=$('.UID').text();
var formdata = new FormData();
formdata = {
'URI': stkname
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
alert(result);
}
});
}
FYI: step1 ajax is performed to get some data from serv1 servlet. and step2 ajax uses step1 ajax output and through it get some new Data from serv2.
Now Currently What I'm doing is:
$(function({
step1();
step2();
});
Through this step2 FormData is null because step1 has not yet finished it's call and haven't received its output.
Question: How to find if step1() ajax is completed and have received the output So I could call step2();
function step1(){
var formdata = new FormData();
formdata = {
'URI': sendtosev
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
$('.UID').text(result);
step2();
}
});
}
//step2 implementation
//start with
step1();
Simply call step2 if step1 succeeded...
You can use jquery callback functions. Please see below code for reference
function step1(callback){
var formdata = new FormData();
formdata = {
'URI': sendtosev
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
$('.UID).text(result);
callback(result);
}
});
}
function step2(result){
var stkname=$('.UID').text();
var formdata = new FormData();
formdata = {
'URI': stkname
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
alert(result);
}
});
}
$(function({
step1(function(result){
step2();
});
});
This is a good candidate for callbacks. For example, step1 could be rewritten as follows:
function step1(callback){
var formdata = new FormData();
formdata = {
'URI': sendtosev
};
$.ajax({
type: 'POST',
url: 'http://localhost:20012/serv1',
data: formdata,
contentType: "text/html",
success: function(result){
$('.UID').text(result);
callback();
}
});
}
And then you can code the following when you call it:
step1(step2);
2 ways to accomplish it
pass 'async:false' to $.ajax parameter. then $.ajax will not return until the response come
call step2() in ajax callback function
Related
$("#sendingForm").submit(
function ()
{
if (checkForm())
sendForm();
return false;
}
);
function sendForm ()
{
var formData = new FormData($("#sendingForm"));
$.ajax({
url: '/process.php',
method: 'post',
contentType: 'multipart/form-data',
data: formData,
success: function(response){
if (response!="0")
errorsDecode(response);
else
alrightMes();
alert(response);
}
});
}
I used to serialize form data, but then I had to add file uploading, so i use FormData class. but it doesn't work. I can't find out the reason. Help me please.
FormData won't unwrap a jQuery object representing the form element.
Try changing:
var formData = new FormData($("#sendingForm"));
To
var formData = new FormData($("#sendingForm")[0]);
You also need to prevent processing of the FormData object internally by $.ajax and browser will set the multi-part content type when a FormData object is used
$.ajax({
url: '/process.php',
method: 'post',
contentType: false,// browser will set multi-part when FormData used
processing: false,
data: formData,
success: function(response) {
if (response != "0")
errorsDecode(response);
else
alrightMes();
alert(response);
}
});
I'm trying to post an image and some text via ajax onto my laravel server except I can't seem to add the File into the ajax request.
I have tried making a FormData and appending the needed params, I also tried serializing my form with jQuery.
$("#create-post-button").click(function(){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// var formData = new FormData();
// formData.append('src', $('#src')[0].files[0]);
// formData.append('title', $);
// formData.append('_token', CSRF_TOKEN);
// formData.append('_method', 'POST');
event.preventDefault();
console.log($('#src')[0].files[0]);
$.ajax({
headers: {
'X-CSRF-TOKEN': CSRF_TOKEN
},
url: '/posts/create',
type: 'POST',
data:
{
'_method': 'POST',
'_token': CSRF_TOKEN,
'title':$("#title").val(),
'src': {
'name':$('#src')[0].files[0].name,
'size':$('#src')[0].files[0].size
}
},
dataType: 'json'
});
});
I expect that when I dump my $request in laravel, that it has the correct request params but also including the $file (FileBag) param for the file that is being posted.
EDIT:
I have looked up the link #charlietfl provided in the comments and it helped me a lot, so here is the end result:
$("#create-post-button").click(function(){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
event.preventDefault();
var file_data = $('#src').prop('files')[0];
var form_data = new FormData();
form_data.append('_method', 'POST');
form_data.append('_token', CSRF_TOKEN);
form_data.append('title', $('#title').val());
form_data.append('src', file_data);
$.ajax({
url: '/posts/create',
dataType: 'text',
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
showSuccessUploadingPost();
},
error: function() {
showErrorUploadingPost();
}
});
});
The CSRF token at file upload required to pass as a GET parameter.
$("#create-post-button").click(function(){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var form_data = new FormData();
form_data.append('title', $('#title').val());
jQuery.each(jQuery('#src')[0].files, function(i, file) {
data.append('src', file); //use the following line to handle multiple files upload
// data.append('src' + i, file);
});
$.ajax({
url: '/posts/create?_token=' + CSRF_TOKEN,
data: form_data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(){
showSuccessUploadingPost();
},
error: function() {
showErrorUploadingPost();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form id="uploadFrm" enctype="multipart/form-data" method="post">
<input type="file" name="src" />
<button id="create-post-button">Upload</button>
</form>
I'm trying to send HTML form data using AJAX however I'm also trying to send other data along with the same AJAX POST call.
Is this possible?
$('#HTMLConForm').on('submit', function (e)
{
e.preventDefault();
$.ajax({
url: "***NewUserURL.com***",
type: "POST",
data:{
'otherinfo': otherinfo,
'form_data': new FormData(this),
},
processData: false,
contentType: false,
success: function (data)
{
alert('You Have Registered')
/*window.location = "index.html"; */
},
error: function (xhr, desc, err)
{
}
});
});
Any help with be appreciated!
Pass the FormData object itself to data, don't wrap it in a simple object.
Use the FormData object's append method to add additional data.
e.preventDefault();
const formdata = new FormData(this);
formdata.append("otherinfo", otherinfo);
$.ajax({
url: "***NewUserURL.com***",
type: "POST",
data: formdata,
I'm currently working the project using Polymer and I'd like to get the return value of API after POST using Iron-Ajax.
Here is my sample code,
var rs = $.ajax({
type: "POST",
url: apiUrl,
data: _data,
dataType: "json",
contentType: 'application/json'
});
rs.done(function (data) {
console.log(data);
alert(data);
}
});
Ajax is asynchronous by default,you need add async:false to make it synchronous
var rs = $.ajax({
type: "POST",
url: apiUrl,
data: _data,
async:false,
dataType: "json",
contentType: 'application/json'
});
var result = null;
rs.done(function (data) {
console.log(data);
alert(data);
result = data;
}
});
//return result;//you can return value like this
I'd like to pass a PHP session variable (called 'profileid') using FormData and AJAX. I thought this below would work, it did not. Why?
var imageData = new FormData();
imageData.append('image', $('#uploadImage')[0].files[0]);
imageData.append('profileid', <?php echo $_SESSION['profileid'];?>);
//Make ajax call here:
$.ajax({
url: '/upload-image-results-ajax.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: imageData,
//leaving out the rest as it doesn't pertain
You could add the profileid in the $.ajax URL parameter instead of adding it in FormData:
$(document).ready(function (e) {
$('#uploadImageForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "/upload-image-results-ajax.php?profileid=<?= $_SESSION['profileid']; ?>",
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response){
console.log("success");
console.log(response);
},
error: function(response){
console.log("error");
console.log(response);
}
});
}));
$('#uploadImage').on("change", function() {
$("#uploadImageForm").submit();
});
});
Don't forget to place session_start(); at the beginning of your code.