Get Object XmlDocument value - javascript

I'm executing an ajax call to a external api (this cannot be modified) to upload an store a file into a folder. This request must return a path (ex. "C:\Doctos\File.pdf" but after a console.log is returning something like this:
#document < string xmlns="http://tempuri.org/">"C:\Doctos\File.pdf"
So my question is, what can I do to get only the text that I want without any change in the api (because I'm not able to do it).
Here is the ajax call that I'm using.
PD. This ajax call is using the provided structure for the dev team that developed the api so things like dataType also cannot be modified
var data = new FormData();
var files = $('#fileUpload').get(0).files;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
var res = data;
//Returns above example
console.log(res);
//Returns something like <p>[object XMLDocument]</p>
$('#MyInput').attr('src', res);
}
});

I would use regular expressions to get the desired string from received data. Put this after success line.
var regex = />\"(.*)\"/;
var matched = regex.exec(data);
var result = matched[1];
console.log(result);
The regex matches the last quoted string in your example.

You can get the data in the xml with jQuery
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
// Get the contents of the xml
var file = $(data).find('string').text();
$('#MyInput').attr('src', file);
}
});

Related

Javascript object properties undefined after ajax request

I've made an ajax call which has returned a json string from a .Net JsonConvert.SerializeObject() call, the json is automatically parsed into an object at the browser but I am currently unable to access the properties without "undefined" being returned.
My current json string being returned is (removed bulk of byte array):
"[{\"filename\":\"\",\"size\":6,\"csize\":\" 5.85 KB\",\"extfile\":\"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA....AAAAAAAAAAAf//Z\"}]"
I've validated this and it's all fine.
My javascript is:
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data != null) {
$("#ImgItem").attr("src", "data:image/png;base64,'" + data.extfile + "'");
}
}
});
}
I have made sure it is definitely an object. I've tried accessing as data.extfile, data["extfile"], passing extfile in as a byte array and then accessing that but it is always coming up as "undefined". In desperation I even tried accessing indexes, iterating through the object etc. and still nothing.
I have a feeling that there is an issue in the json string which is preventing it from converting properly but I can't see it as I haven't worked much with json. Could someone point out where I'm going wrong?
Solution
Javascript was parsing the response into an object with a single property "data.d", parsed data.d and that created the object correctly.
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data != null && data.d != null) {
let imgData = JSON.parse(data.d);
$("#ImgItem").attr("src", "data:image/png;base64," + imgData[0].extfile);
}
}
});
}
basically if the string that you pasted is the response (data), when using JSON.parse() it converts into an array , so you should use it like that.
const stringResponse = "[{\"filename\":\"\",\"size\":6,\"csize\":\" 5.85 KB\",\"extfile\":\"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA....AAAAAAAAAAAf//Z\"}]"
const parsedResponse = JSON.parse(stringResponse);
console.log(parsedResponse)
const entry = parsedResponse[0];
console.log(entry.extfile)
so basically, you need to do:
data[0].extfile
Since the console.log(data) statement returns:
{d: "[{"filename":"","size":6,"csize":" 5.85 KB",…AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf//Z"}]"}
The data you are actually trying to obtain is contained in a JSON string contained in the d property of the data received. If you were to parse the string and then access the extfile property you would have your data:
var actualData= JSON.parse(data.d);
var extfile = actualData[0].extfile;
Don't know if this will help but here it is:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
http://api.jquery.com/jquery.ajax/
Also the data is an Array, maybe grab the first object in the array data[0].extfile.
I'm thinking it maybe reworked as such:
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8"
}).done(function(data){
if (data != null) {
$("#ImgItem").attr("src", "data:image/png;base64,'" +
data[0].extfile + "'");
}
});
}

Sending Json Array in POST request for JavaScript

I am having trouble in sending a JSON array in an AJAX call. Following is my Code
var company_name = $('input#company_name').val();
var company_localname = $('input#company_localname').val();
var companytype = $('#companytype').val();
if (companytype == 'retailer') {
var bank_name = $('input#bank_name').val();
var account_title = $('input#account_title').val();
var business_nature = $('input#business_nature').val();
var gross_sales = $('input#gross_sales').val();
}
After getting all the values I am storing the data in Json like the following
var jsonArray = [];
jsonArray["company_name"] = company_name;
jsonArray["company_localname "] = company_localname;
if (companytype == 'retailer') {
jsonArray["bank_name"] = bank_name;
jsonArray["account_title"] = account_title;
jsonArray["business_nature"] = business_nature;
jsonArray["gross_sales"] = gross_sales;
}
Now for sending the jsonArray in Ajax call
$.ajax({
url : url,
type : "POST",
dataType : 'json',
contentType : 'application/json; charset=UTF-8',
data : JSON.stringify(jsonArray),
success : function(response) {
//Some Code here
}
});
Please help me sending data. Or tell me if I am making any mistake here. Thank you
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing. Read more about JSON.parse() method
The JSON.stringify() method converts a JavaScript value to a JSON string. Read more about JSON.stringify() method
Here simply you can send an array and Parse it in server side.
$.ajax({
url : url,
type : "POST",
dataType : 'json',
data : jsonArray,
success : function(response) {
//Some Code here
}
});

JavaScript Saving data from an ajax request

Challenge:
While on URL1(random wikipedia page), make an ajax request to URL2(100 most common words wikipedia page), format a list out of the returned data to be used later.
I have to run this from the console while on "URL1"
example:
Navigate to URL1
Open Console
paste code
hit enter
So far I have been able to grab the entire html source while on URL1 with the following:
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function (response) {
console.log(response); // works as expected (returns all html)
}
});
I can see in the console the entire HTML source -- I then went to URL2 to figure out how to grab and format what I needed, which I was able to do with:
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
Now this is where my issue is -- combining the two
$.ajax({
url:'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type:'GET',
dataType:'html',
success: function(data){
// returns correct table data from URL2 while on URL2 -- issue while running from URL1
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
};
});
Im guessing this is due to the HTML I want to map is now a string, and my array is looking for HTML elements on the current page which it of course would not find.
Thanks
Simple fix here! You're exactly right, it's not parsing the html you return, so just tell jQuery to convert it into an object it can use $(data) and use that to find what you need.
In essence, your 'document' now becomes $(data) which you will use as the source of all your queries.
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function(data) {
var myVar = data;
Names = $.map($(myVar).find('.wikitable tr'), function(el, index) {
return $(el).find('td:last').text()
});
console.log(Names);
}
});

AJAX Fileupload with jquery

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

How to navigate JSON Object in jQuery?

I made this webservice that handles my database functions, and this is an AJAX call to one of the methods.
$.ajax({
type: "POST",
url: "Service/dataBaseService.asmx/getRMAData",
data: '{"RMAId": 1 }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
console.log(data);
alert(data.RMA_ID);
}
});
this is what is logged:
({d:"[{\"RMA_ID\":1,\"RequestDate\":\"2013-02-28T00:00:00\",\"Company\":1,\"Status\":\"Accepted \",\"Serial\":201764,\"LastChangeDate\":\"2013-02-28T00:00:00\",\"LastChangeBy\":\"Foreign \",\"Price\":null}]"})
However alert(data.RMA_ID) returns undefined aswell as data.d.RMA_ID?
How can I get hold of the values?
The value of data that you've logged is an object with a property named d, that contains a string value. You could probably make adjustments at your server side to make the value of d an object rather than a string, but the way it is currently constructed, you would be able to parse it into an object using JSON.parse.
Once you've done that, the resulting object should be an array, containing one single object. Thus, your access to RMA_ID would be as follows:
var data = JSON.parse(data.d);
alert(data[0].RMA_ID);
Using simple javascript you need to parse JSON response
var resp = eval('(' + data + ')');
or thru jQuery
var resp = jQuery.parseJSON(data);
now you can access the data using '.' and key name
console.log(resp.d[0].RMA_ID)

Categories