So I've been trying to do this for more than a day now. I'm getting a few user inputs through a form (ex - a name of a car), then I search through a JSON file to see whether its available. After this I'm trying to send the results of the search to a results page. I've been trying to use a cookie for this process. However there is a problem that I can't figure out. Following is my code,
This is getting input and searching:
function search() {
var name = $("input[name=carName]").val();
var cars = new Array();
$.getJSON("properties.json", function (data) {
$(data.cars).each(function (index, value) {
if (value.name == name) {
cars.push(value);
}
});
if (cars.length > 0) {
send(cars);
} else {
// do some handling
}
});
function send(cars) {
var str = JSON.stringify(cars);
Cookies.set("carResults", str);
window.location.replace("result.html");
}
This is the script from result.html
<script>
$(document).ready(function () {
var temp = Cookies.get("carResults");
var cars = JSON.parse(temp);
if(results!=null) {
for (var i = 0; i < results.length; i++) {
var temp1 = "Found a " + cars[i].name;
$("#resultArea").append(temp1);
}
} else {
$("#resultArea").append("Nothing to show");
}
});
</script>
PS. I'm using a javascript library called cookie.js for creating cookies
Related
I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.
I have a function that is supposed to check old data against data. I am parsing data and oldData to get a JSON object respectively as dbData and formData are simply strings containing ID's and values for the HTMML form. The purpuse of the function is to check if the user has made any textchanges some textareas in the HTML form. I want to do this by checking the ID for each textarea and then check if the value in formData and Data are the same. In that case no change has been made and the function will return true.
The data string im parsing looks something like this:
"[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\Apple \",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]"
So for example, i have to check the ID for "textarea1" in dbData and formData and then check if the value is the same. Can this be done using wildcard or is there a better way to archive this?
function CheckValues() {
var isChanged = false;
var formData = $.parseJSON(data);
var dbData = $.parseJSON(oldData);
if(formData !== dbData) {
var isChanged = true;
}
return isChanged;
}
The code shown below works in IE9+, Chrome, FireFox but other
browsers yet to test. The example shows two different values, data and
OldData - data contains "Tea" where as OldData contains "OldTea" so
isChanged flag is true.
function CheckValues() {
var data = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"Tea\"}";
var oldData = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"OldTea\"}";
var formData = JSON.parse(data);
var dbData = JSON.parse(oldData);
var oFormData = Object.keys(formData);
var oDbData = Object.keys(dbData);
var isChanged = false;
if (oFormData.length === oDbData.length)
{
for (var i = 0; i < oFormData.length; i++) {
var propName = oFormData[i];
if (typeof (dbData[propName]) === "undefined") {
isChanged = true;
break;
}
else {
if (formData[propName] !== dbData[propName]) {
isChanged = true;
break;
}
}
}
}
}
I am having an issue displaying json data. I have searched and found many examples, but for some reason I get the "Cannot read property 'length' of undefined" error, because "var object = notes.data;" comes back as undefined.
Why is object undefined? From everything I can see I am doing it right.
My json that is returned.
{
"data":[
{
"NumberOfAnswers":25,
"Answer":"51-89 Percent of all items in section are <b>IN STOCK<\/b>",
"Percent":54.35
},
{
"NumberOfAnswers":21,
"Answer":"90-100 Percent of all items in section are <b>IN STOCK<\/b>",
"Percent":45.65
}
]
}
And here is the function to display it. (With some debugging code as well)
function format(notes) {
console.log(notes); //this displays the json
var object = notes.data;
console.log(object);
var i;
for (var i = 0; i < object.length; i++) {
var Result = object[i];
var Answer = Result.Answer;
console.log(Answer)
}
}
Here is the ajax function:
$.ajax({
type: 'post',
url: '/rmsicorp/clientsite/pacingModal/surveyajax2.php',
success: function(result) {
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
detailsrows.splice(RowID, 1);
} else {
row.child(format(result)).show();
tr.addClass('shown');
if (RowID === -1) {
detailsrows.push(tr.attr('id'));
}
}
}
});
Most likely, the response is still in string format. You can add JSON.parse to convert it to an object and then be able too access the data property.
Try modifying your function like this to see if it fixes the problem.
function format(notes) {
console.log(notes); //this displays the json
// The following converts the response to a javascript object
// and catches the exception if the response is not valid JSON
try {
notes = JSON.parse(notes);
} catch(e) {
console.log('notes is not valid JSON: ' + e);
}
var object = notes.data;
console.log(object);
var i;
for (var i = 0; i < object.length; i++) {
var Result = object[i];
var Answer = Result.Answer;
console.log(Answer)
}
}
I am getting a very strange issue whereby when I try to extract the word document as a compressed file for processing in my MS Word Task Pane MVC app the third time, it will blow up.
Here is the code:
Office.context.document.getFileAsync(Office.FileType.Compressed, function (result) {
if (result.status == "succeeded") {
var file = result.value;
file.getSliceAsync(0, function (resultSlice) {
//DO SOMETHING
});
} else {
//TODO: Service fault handling?
}
});
The error code that comes up is 5001. I am not sure how to fix this.
Please let me know if you have any thoughts on this.
Additional Details:
From MSDN:
No more than two documents are allowed to be in memory; otherwise the
getFileAsync operation will fail. Use the File.closeAsync method to
close the file when you are finished working with it.
Make sure you call File.closeAsync before you read the file again - that could explain the issue you are seeing.
More at: https://msdn.microsoft.com/en-us/library/office/jj715284.aspx
I have an example about how to use this API correctly. Actually the current example in the MSDN is not very correct. This code is tested in Word.
// Usually we encode the data in base64 format before sending it to server.
function encodeBase64(docData) {
var s = "";
for (var i = 0; i < docData.length; i++)
s += String.fromCharCode(docData[i]);
return window.btoa(s);
}
// Call getFileAsync() to start the retrieving file process.
function getFileAsyncInternal() {
Office.context.document.getFileAsync("compressed", { sliceSize: 10240 }, function (asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
document.getElementById("log").textContent = JSON.stringify(asyncResult);
}
else {
getAllSlices(asyncResult.value);
}
});
}
// Get all the slices of file from the host after "getFileAsync" is done.
function getAllSlices(file) {
var sliceCount = file.sliceCount;
var sliceIndex = 0;
var docdata = [];
var getSlice = function () {
file.getSliceAsync(sliceIndex, function (asyncResult) {
if (asyncResult.status == "succeeded") {
docdata = docdata.concat(asyncResult.value.data);
sliceIndex++;
if (sliceIndex == sliceCount) {
file.closeAsync();
onGetAllSlicesSucceeded(docdata);
}
else {
getSlice();
}
}
else {
file.closeAsync();
document.getElementById("log").textContent = JSON.stringify(asyncResult);
}
});
};
getSlice();
}
// Upload the docx file to server after obtaining all the bits from host.
function onGetAllSlicesSucceeded(docxData) {
$.ajax({
type: "POST",
url: "Handler.ashx",
data: encodeBase64(docxData),
contentType: "application/json; charset=utf-8",
}).done(function (data) {
document.getElementById("documentXmlContent").textContent = data;
}).fail(function (jqXHR, textStatus) {
});
}
You may find more information from here:
https://github.com/pkkj/AppForOfficeSample/tree/master/GetFileAsync
Hope this could help.
Additional to Keyjing Peng's answer (which I found very helpful, thanks!) I thought I'd share a variation on the encodeBase64, which you don't want to do if you are uploading via REST to SharePoint. In that case you want to convert the byte array to a Uint8Array. Only then could I get it into a SharePoint library without file corruption.
var uArray = new Uint8Array(docdata);
Hope this helps someone, couldn't find this info anywhere else online...
See this link
http://msdn.microsoft.com/en-us/library/office/jj715284(v=office.1501401).aspx
it contains this example method:
var i = 0;
var slices = 0;
function getDocumentAsPDF() {
Office.context.document.getFileAsync("pdf",{sliceSize: 2097152}, function (result) {
if (result.status == "succeeded") {
// If the getFileAsync call succeeded, then
// result.value will return a valid File Object.
myFile = result.value;
slices = myFile.sliceCount;
document.getElementById("result").innerText = " File size:" + myFile.size + " #Slices: " + slices;
// Iterate over the file slices.
for ( i = 0; i < slices; i++) {
var slice = myFile.getSliceAsync(i, function (result) {
if (result.status == "succeeded") {
doSomethingWithChunk(result.value.data);
if (slices == i) // Means it's done traversing...
{
SendFileComplete();
}
}
else
document.getElementById("result").innerText = result.error.message;
});
}
myFile.closeAsync();
}
else
document.getElementById("result2").innerText = result.error.message;
});
}
change "pdf" to "compressed" and the method call doSomethingWithChunk() needs to be created and should probably do something like this:
function base64Encode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
I use this technique to successfully save to Azure blob storage.
Obviously you should rename the method as well.
I have this particular problem, where I need to validate the data before it is saved via an ajax call. save_ass_rub function is called when user navigates to a different URL.
In my application, I have a custom Window and user is allowed to input data. I am able to capture all the data in this step: var data = $('form').serialize(true);. But I need to loop through this and check if data for some specific elements is empty or not. I can't do it when the user is in the custom window. The Custom window is optional for the user. All I want is to alert the user in case he has left the elements blank before the data is submitted.
We are using Prototype.js and ajax .
<script>
function save_ass_rub() {
var url = 'xxxx';
var data = $('form').serialize(true);
var result;
new Ajax.Request( url, {
method: 'post',
parameters: data,
asynchronous: false, // suspends JS until request done
onSuccess: function (response) {
var responseText = response.responseText || '';
if (responseText.length > 0) {
result = eval('(' + responseText + ')');
}
}
});
if (result && result.success) {
return;
}
else {
var error = 'Your_changes_could_not_be_saved_period';
if (window.opener) { // ie undocked
//Show alert in the main window
window.opener.alert(error);
return;
}
return error;
}
}
// Set up auto save of rubric when window is closed
Event.observe(window, 'unload', function() {
return save_ass_rub();
});
</script>
Can some thing like this be done?
After Line
var data = $('form').serialize(true);
var split_data = data.split("&");
for (i = 0; i < split_data.length; i++) {
var elem = split_data[i];
var split_elem = elem.split('=');
if( split_elem[0].search(/key/) && split_elem[0] == '' ){
console.log( split_elem );
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
}
Instead of using the serialized form string, I would use the form itself to do the validation. if $('form') is your form element then create a separate function that checks the form element so its compartmentalized.
function checkform(form)
{
var emptytexts = form.down('input[type="text"]').filter(function(input){
if(input.value.length == 0)
{
return true;
}
});
if(emptytexts.length > 0)
{
return false;
}
return true;
}
and in the save_ass_rub() function
//..snip
if(checkform($('form') == false)
{
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
var data = $('form').serialize(true);
var result;
I only added text inputs in the checkform() function you can the rest of the input types and any other weird handling you would like to that function. As long as it returns false the error will be displayed and the js will stop otherwise it will continue