I want to serialize array in a javascript and append the serialized value in form data, I have tried but serialize array showing empty, Kindly give a suggestion.
var IsolationFO = {};
IsolationFO['tagNumber'] = $('#tagNumberId').val();
IsolationFO['keyNumber'] = $('#lockProvidedId').val();
var formData = new FormData();
$.ajax({
url: baseURL + 'url',
type: "POST",
contentType: false,
processData: false,
data: function() {
//here the inputs showing empty
var inputs = $('#IsolationFO').serializeArray();
$.each(inputs, function(i, input) {
formData.append(input.name, input.value);
console.log("\nSending Data----------------" + input.name + "-----" + input.value);
});
return formData;
}(),
Related
The line which says it removes the markup doesn't completely and occasionally the text which gets displayed on the web page displays a 'rn' instead. I decided to skip removing the markup, but any attempt to remove or simplify the responseText.replace() function either gives me an error for the data.replaceAll() functions, or seems to do nothing. So how can I get the data to return with the markup and allow me to parse what I need?
var data = $.ajax({
type: "POST",
contentType: "application/json; charset=unicode",
url: '<%= ("Default.aspx/GetData") %>',
data: "{'fields': '" + fields}",
dataType: "json",
async: false
}).responseText.replace(/<\/?[^>]+>/gi, ''); //Remove markup
data = data.replaceAll("\\", "");
data = data.replaceAll("}}", "}");
data = data.replaceAll("{\"data\":", "");
data = data.replaceAll("{\"d\":", "");
data = data.replaceAll("]}", "]");
data = data.replaceAll("}}]\"}", "}]");
data = data.replaceAll("}]\"}", "}]");
I updated the code to the below and I am getting an error, "Uncaught SyntaxError: Expected ',' or '}' after property value in JSON at position 34" which is where dataset is defined. I played around with various combos of the replaces and it appears to be .replace("\", ""); is the one causing the issue, but I don't know why.
var data = $.ajax({
type: "POST",
contentType: "application/json; charset=unicode",
url: '<%= ("Default.aspx/GetData") %>',
data: "{'fields': '" + fields + "'}",
dataType: "json",
async: false
});
var json = JSON.stringify(data)
.replace("}}", "}")
.replace("{\"data\":", "")
.replace("{\"d\":", "")
.replace("]}", "]")
.replace("}}]\"}", "}]")
.replace("}]\"}", "}]")
.replace("\\", "");
var table = $('#dtable').DataTable();
table.clear().draw();
var i = 0;
var j = [];
var dataSet = JSON.parse(json);
$.each(dataSet, function (key, value1) {
$.each(value1, function (key, value) {
j[i] = value;
i++;
});
table.row.add([j[1], j[2], j[3], j[4], j[5], j[6], j[7], j[8], j[9], j[10], j[11], j[12]]).draw();
i = 0;
j = [];
});
HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);
I'm trying to follow some API documentation which provides the following example:
$("#submit").click(function () {
var data = new FormData();
var files = $('#fileUpload').get(0).files;
if (files.length > 0) {
data.append("attachment[file]", files[0]);
data.append("mediaExtension", "jpg");
}
$.ajax({
type: "post",
url: "http://[ur]/api/Interaction/InteractionCreateLocationResultAsMedia",
data: data,
mimeType: "multipart/form-data",
cache: false,
contentType: false,
processData: false,
success: function (data) {
//do stuff
},
error: function (data, resultstatus, xhr) {
alert("api call failed" + xhr);
}
});
However, I am not using a file upload to create the image. The image is actually being created from html5 canvas. I can successfully convert the canvas to base64 data and submit it to my server, at which point it returns a url to where the image resides on my server - so I want to pass that URL (or maybe the base64 data) on to the API using the sample code above, but when I use the method below, I have a feeling it is not working, because in the data returned to me from the API, the "MediaData" key value is null.
Anyone know the proper way to pass my image on to this API?
I figured this out - the answer was to create a blob as #Musa mentioend. I used the following method:
var imgSrc = $('.image-container').find('img').attr('src');
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {type: contentType});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}
var apiData = new FormData();
apiData.append( "attachment[file]", blob);
$.ajax({
url: submissionURL,
type: "post",
dataType: 'json', //return response as json
mimeType: "multipart/form-data",
cache: false,
contentType: false,
processData: false,
data: apiData,
error: function(data,resultstatus,xhr) {
console.error("error:",data,resultstatus,xhr);
},
success: function(){
//
}
});
I am currently trying to solve a problem.
I have several forms on a single page which get sent to the backend asynchronously via ajax.
Now some of them need to have a fileupload which doesnt break the process, so it alsoneeds to be handled asynchronously.
I am trying to figure it out like that :
// Allgemein Submit
$allgSubmit.click(function(){
event.preventDefault();
var gehrKundennummer = $('#gehrKundennummer').val();
var kundenklasse = $("input[type='radio'][name='kundenklasse']:checked").val();
var lkw12t = $('#lkw12t').val();
var lkw3t = $('#lkw3t').val();
var autobus = $('#autobus').val();
var firmenname1 = $('#firmenname1').val();
var firmenname2 = $('#firmenname2').val();
var uidnummer = $('#uidnummer').val();
var peselregon = $('#peselregon').val();
var firmenart = $('#firmenart option:selected').val();
var strasse = $('#strasse').val();
var ort = $('#ort').val();
var plz = $('#plz').val();
var land = $('#land').val();
var fd = new FormData();
var file = fd.append('file', $('#allg_firmen_dok').get(0).files[0]);
var allgArray = {
'gehrKundennummer':gehrKundennummer,
'kundenklasse':kundenklasse,
'lkw12t':lkw12t,
'lkw3t':lkw3t,
'autobus':autobus,
'firmenname1':firmenname1,
'firmenname2':firmenname2,
'uidnummer':uidnummer,
'peselregon':peselregon,
'firmenart':firmenart,
'strasse':strasse,
'ort':ort,
'plz':plz,
'land':land,
'file':file
};
//var data = new FormData();
//jQuery.each(jQuery('#allg_firmen_dok')[0].files, function(i, file) {
// data.append('file-'+i, file);
//});
console.log(allgArray);
$.ajax({
url: "PATHTOFILE/logic/logic_update_client_allg.php",
type: "POST",
data: allgArray,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function(allgArray){
alert(allgArray);
var allgSave = $('#allgSave');
allgSave.text('Aktualisieren erfolgreich!');
allgSave.toggle();
},
error: function(){
var allgSave = $('#allgSave');
allgSave.text('Aktualisieren fehlgeschlagen!');
allgSave.toggle();
}
});
});
The console log of the array returns all values correctly except the one for "file"
it says undefined.
I don't know how to deal with it, are there any requirements that im missing?
Thanks for any kind of help
EDIT
var file = fd.append('file', $('#allg_firmen_dok').get(0).files[0]);
returns undefined
I think the variable fd = new FormData() is an Object and it has attribute "file". So it cannot pass the attribute "file" to another Object "allgArray"
You need to check about it before you call function
$.ajax({
url: "PATHTOFILE/logic/logic_update_client_allg.php",
type: "POST",
data: allgArray,
Think about the data you send! It maybe another instance to get data from "file" of "fd". Hope it help you! ^^
Btw, I used AJAX to send file last time
$(document).ready(function (e) {
$("#Form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "uploader.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
console.log(data);
}
});
}));
});
add headers: { "Content-Type": "multipart/form-data" } in ajax option
I have a javascript function
function TxEncrypt(event)
{ //perform encryption of token data, then submit the form like normal
//obtain public key and initial JSEncrypt object
var txPubKey = txJ$(".zwitch_encryptionkey").val();
var txEncrypter = new JSEncrypt();
txEncrypter.setPublicKey(txPubKey);
//get Data and encrypt it
var txData = '{}';
var txCryptData = '';
if(txJ$(".zwitch_data").length > 1)
{ //if there are more than one element with this class, convert it to json string
txData = txJ$(".zwitch_data").serializeObject();
txCryptData = txEncrypter.encrypt(JSON.stringify(txData));
}
else
{ //else, just encrypt the value
txData = txJ$(".zwitch_data").val();
txCryptData = txEncrypter.encrypt(txData);
}
dataString = txCryptData; // array?
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
});
alert(dataString);
}
I could get the value of dataString.But the ajax parrt is not working.I have added the jquery library.But doesnt seem to work
What's the error you are getting?
I think this should be:
$.ajax({
type: "POST",
url: "tokenize.php", //removed the dot
.....