chrome.storage.local.get not working - javascript

Here i'm using to store the multiple value[below is the code]
Here DocName is the Name of the PDF and Base64File is the base64 string of the pdf
var obj = { DocName: res.Value.DocumentName, Base64File: res.Value.Base64File };
chrome.storage.local.set({ 'MyFile': obj });
In next page i'm retriving like this
$(document).on('click', '.sendToPdf', function(){
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
var arr=new Array();
var item={"CategoryID": 11,"DocumentNumber": "22022018053567","Base64FileData": PdfBase64,"DocumentName": DocumentName,
"OptionalParam1": "sample string 5"};
arr.push(item);
$.ajax({
type: "POST",
url: Documentupload,
headers: {
'Authorization': headerdata,
'Content-Type':'application/json'
},
data:JSON.stringify(arr),
dataType: 'json',
success: function (res) {
if (res.IsSuccess) {
setTimeout(function () {
$("#divLoading").hide();
}, 2000);
//$("#divLoading").hide();
$(".modal-iframe1").attr("src", window.emSigner.OnlineSignUrl + res.Response[0].DocumentID + "&AuthToken=" + AuthToken);
//window.location.reload();
}else{
alert(res.Messages);
window.location.href='/PdfLogin.html';
}
},
error: function (error) {
//alert("Error while communicating to the server");
alert(error.responseText);
window.location.href='/PdfLogin.html';
}
});
});
});
[check this image .sendToPdf(button)]
Question is, if i click the button first time on any icon, the values are retriving correctly, but in second time if i click other than 1st icon i'm getting the values as the before one? it is accepting the previous values only?
How to resolve this,
Help me to come out of this problem.

Related

AJAX Post call no data

Hello wenn i want to send a post request to my Controller there is no data.
I tried to log my Json file and there is something. But when I send the post request my controller shows it is empty.
Here is my call:
var item = {};
var jsonObj = [];
item["ProductCategoryId"] = i;
item["Name"] = txtName;
item["Description"] = txtDescription;
item["Price"] = txtPrice;
item["Stock"] = txtStock;
item["ProductCategory"] = txtProductCategory;
item["Image"] = await getAsByteArray(txtImage);
jsonObj.push(item);
var jsonString = JSON.stringify(jsonObj);
console.log("jsonString : " + jsonString);
$.ajax({
url: "/Admin/SaveProductToDB",
type: "POST",
data: { dataToSend: jsonString},
success: function (data) {
if (data.status == "Success") {
BootstrapDialog.show({
title: 'Success!',
message: "Data Updated Successfully!",
buttons: [{
label: 'OK',
action: function (dialog) {
window.location.href = "/Admin/Product";
removeProdData(i);
$("#btnAddProd").attr("disabled",false);
dialog.close();
}
}]
});
}
}
});
//Here I make a breakpoint but my string is empty
public JsonResult SaveProductToDB(string dataToSend)
{
List<Product> _List = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(dataToSend);
}
the getAsByteArray
async function getAsByteArray(file) {
return new Uint8Array(await readFile(file))
}
function readFile(file) {
return new Promise((resolve, reject) => {
// Create file reader
let reader = new FileReader()
// Register event listeners
reader.addEventListener("loadend", e => resolve(e.target.result))
reader.addEventListener("error", reject)
// Read file
reader.readAsArrayBuffer(file)
})
}
I found out if I remove the Image. that the controller is then able to resize it. Thanks for the help so far. So I need to look at this place where the problem is.
You are checking against data.status as if it's a given that it exists. Just console.log(data) instead and you will see whether or not status is being returned.
Also, if you open the Network tab in Chrome you can click on the post request & see if your headers are going through accurately and also click on 'Preview' to see an unfiltered result from the controller.
You might want to modify your code to catch errors for debugging, ie:
$.ajax({
url: "/Admin/SaveProductToDB",
type: "POST",
data: { dataToSend: jsonString},
success: function (data) {
if (data.status == "Success") {
BootstrapDialog.show({
title: 'Success!',
message: "Data Updated Successfully!",
buttons: [{
label: 'OK',
action: function (dialog) {
window.location.href = "/Admin/Product";
removeProdData(i);
$("#btnAddProd").attr("disabled",false);
dialog.close();
}
}]
});
}
},
error:function (xhr, ajaxOptions, thrownError) {
// Set up whatever error reaction you want, here. ie:
console.log('An error was encountered.');
alert(xhr.status);
alert(thrownError);
}
});
Another tip is to validate empty data being submitted prior to the Ajax call, so you only touch the backend server when your data is valid - to avoid an error.

Returning the correct promise in angular

I'm having trouble returning the correct promise for a service in angular.
this is my function:
postToSP.post($scope.sharePointURL, data).then(function() {
$scope.gettingData = false;
$scope.yammerListName = "Successfully posted to SP";
}).catch(function(e){
//console.log("Error: ", e);
$scope.yammerListName = "Sorry we couldn't post to that page, please make sure your column names are EXACTLY the same!"
$scope.gettingData = false;
throw e;
});
And this is my service, i get the error: "Unable to get property 'then' of undefined or null reference". I know it's because i'm not returning the promise properly but I can't figure out how to do it correctly. Please help, thanks in advance.
app.service("postToSP", function($http) {
//Submit to SP function
this.post = function(originalurl,data){
console.log(data);
var url = originalurl.split("Lists/")[0];
var listname = originalurl.split("Lists/")[1].split("/")[0];
//if the row is checked send it, if not jump to the next row
//run the function, continue until the end and break
var i = 0;
return letsPost(i);
function letsPost (i) { //i<data.length; i++
if (data[i].checked == false) {
i++;
return letsPost(i);
} else {
var formattedText = document.getElementById("text"+i).innerHTML.toString() ;
var formattedCreated = document.getElementById("created"+i).innerHTML.toString();
var formattedLikes = document.getElementById("likes"+i).innerHTML.toString();
var formattedLinks = document.getElementById("links"+i).innerHTML.toString();
var uploadData = { //change this for input data
'__metadata': { 'type': 'SP.Data.' + listname + 'ListItem' },
'Title': i + "",
'Likes': formattedLikes,
'Post_x0020_Date': formattedCreated,
'Post_x0020_Links' : formattedLinks,
'Post_x0020_Text': formattedText
};
console.log(uploadData);
createListItem(url, listname, uploadData)
.done(function (columnData) {
console.log('Added row' + i);
// if there is more data
if (i < data.length) {
i++;
return letsPost(i);
//add new data and continue the function
} else {
return;
}
})
.fail(function (error) {
console.log(JSON.stringify(error));
alert("Error:" + JSON.stringify(error));
throw error;
});
//Function to get form digest token
function getFormDigest(webUrl) {
return $.ajax({
url: webUrl + "/_api/contextinfo",
method: "POST",
headers: { "Accept": "application/json; odata=verbose" }
});
};
//Function to create the list item
function createListItem(webUrl, listName, itemProperties) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listName + "')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
console.log(data.d.results);
},
error: function (data) {
console.log(data);
}
});
return getFormDigest(webUrl).then(function (data) {
return $.ajax({
url: webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": data.d.GetContextWebInformation.FormDigestValue
}
});
});
};
};
};
};
});
in your function declare the promise first
this.post = function(originalurl,data){
var deferred = $q.defer();
the data that you want to return use
deferred.resolve(dataToReturn)
and at the end of your function add
return deferred.promise;
From what I understand your code, mistake you are doing is you are returning the promise returned from getFormDigest but also applying then function on it and returning another promise. If you dont return getFormDigest nothing will be returned since its async.
To solve it you can use angular $q library and return and independent promise. Resolve that promise in your then function where you are returning a promise and no need to return getFormDigest so only one promise will be returned and hopefully your problem will be resolved.
In simple way you can achieve it..i hope it make sense
//in your controller
yourService.addData(yourPayload);
.then(function (cou) {
$scope.data = cou.data;
});
//in your service
this.addData = function (data) {
var response = $http({
method: "POST",
url: 'your url',
data: data,
dataType: "json"
});
return response;
}

AJAX and jQuery trigger setInterval on click to update rendered XML data

I have two scripts, the first one loads a particular set of child nodes from an XML file via AJAX in order to render a menu in the form of a list of buttons in #loadMe. The great thing about this first script is that I have implemented the setInterval function which updates the list of buttons automatically anytime the XML file changes. The first script's rendered buttons are written to trigger the second script on mouse click, which renders a div filled with the desired node's sibling nodes in #toadMe. This second script also works, but only upon mouse click does it ensure updated data. In other words the setInterval function does not work on the second script because it is expecting a mouse click. How do I make the second script auto update if once it is displayed via mouse click?
setInterval(itemMenu,1500);
function itemMenu() {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$("#loadMe").empty();
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
$('<button type="button" onclick="itemContent(this.value)"></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
//setInterval(itemContent,1500);
function itemContent(q) {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
if(q==fullName) {
$("#toadMe").empty();
firstName = $(this).siblings('firstName');
lastName = $(this).siblings('lastName');
age = $(this).siblings('age');
hometown = $(this).siblings('hometown');
job = $(this).siblings('job');
$('<h1></h1>').html(firstName).appendTo('#toadMe');
$('<h1></h1>').html(lastName).appendTo('#toadMe');
$('<h1></h1>').html(age).appendTo('#toadMe');
$('<h1></h1>').html(hometown).appendTo('#toadMe');
$('<h1></h1>').html(job).appendTo('#toadMe');
}
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
Is this what you want?
setInterval(itemMenu,1500);
function itemMenu() {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$("#loadMe").empty();
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
$('<button type="button" onclick="itemContent(this.value)"></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
itemContent(fullName);
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
//setInterval(itemContent,1500);
function itemContent(q) {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
if(q==fullName) {
$("#toadMe").empty();
firstName = $(this).siblings('firstName');
lastName = $(this).siblings('lastName');
age = $(this).siblings('age');
hometown = $(this).siblings('hometown');
job = $(this).siblings('job');
$('<h1></h1>').html(firstName).appendTo('#toadMe');
$('<h1></h1>').html(lastName).appendTo('#toadMe');
$('<h1></h1>').html(age).appendTo('#toadMe');
$('<h1></h1>').html(hometown).appendTo('#toadMe');
$('<h1></h1>').html(job).appendTo('#toadMe');
}
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
Or you can create use another function so that you don't have to make another ajax call and something like this.
setInterval(itemMenu,1500);
function itemMenu() {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$("#loadMe").empty();
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
$('<button type="button" onclick="itemContent(this.value)"></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
update($(this));
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
function update(obj){
$("#toadMe").empty();
firstName = $(obj).siblings('firstName');
lastName = $(obj).siblings('lastName');
age = $(obj).siblings('age');
hometown = $(obj).siblings('hometown');
job = $(obj).siblings('job');
$('<h1></h1>').html(firstName).appendTo('#toadMe');
$('<h1></h1>').html(lastName).appendTo('#toadMe');
$('<h1></h1>').html(age).appendTo('#toadMe');
$('<h1></h1>').html(hometown).appendTo('#toadMe');
$('<h1></h1>').html(job).appendTo('#toadMe');
}//update
//setInterval(itemContent,1500);
function itemContent(q) {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
if(q==fullName) {
$("#toadMe").empty();
firstName = $(this).siblings('firstName');
lastName = $(this).siblings('lastName');
age = $(this).siblings('age');
hometown = $(this).siblings('hometown');
job = $(this).siblings('job');
$('<h1></h1>').html(firstName).appendTo('#toadMe');
$('<h1></h1>').html(lastName).appendTo('#toadMe');
$('<h1></h1>').html(age).appendTo('#toadMe');
$('<h1></h1>').html(hometown).appendTo('#toadMe');
$('<h1></h1>').html(job).appendTo('#toadMe');
}
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
Here is a fiddle. http://jsfiddle.net/8xLk4/ Watch the last name. It will autoupdate.

JQPlot, JSON and 'No data specified' Error

I am trying to use JQPlot within a VB.NET application under .NET 3.5. On a button click, using jquery, I am trying to populate the JQPlot Chart with JSON derived data using a ASP.NET Webservices Source file (which is part of the solution).
The JSON data is sent by the web service but when it is presented to JQPlot I get the javascript error 'No Data Specified' which is generated by JQPlot code.
My code listing is as follows:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
Javascript code outside the 'document.ready' function:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
//url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
var ret = response.d;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
return ret;
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var jsonurl = "./jsondata.txt";
function getElectricDataJSON() {
var ret = ajaxDataRenderer();
var plot1 = $.jqplot('chart2', jsonurl, {
title: "AJAX JSON Data Renderer",
dataRenderer: ret, //$.jqplot.ciParser
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
}
The JSON data format is as follows:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220429.41 }, ... ]
Any help or advice will be appreciated.
Thanks to #Fresh for their quick response. Here is the complete solution to my problem:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
JS function to get the data from a web service:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
ret = response.d; // return response string object
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
Data structure outputted by the web service is:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7,095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1,137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220,429.41 }, ... ]
Data structure that is expected by JQPlot:
[ [ "2013-09-23T00:00:00", 7095.65 ] , [ "2013-08-22T00:00:00", 1137.96 ], [ "2013-07-24T00:00:00", 220429.41 ], ... ]
Note the removal of the comma's in the 'expected data' Bill field.
And finally, the function getElectricDataJSON() that is being called by btnASMX1 where 'chart2' is the ID of the div tags where the chart will be drawn.
function getElectricDataJSON() {
// Get JSON 'string' object
var ret = ajaxDataRenderer();
// If JSON string object is null, stop processing with friendly message
if (ret == null) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>CHARTS ARE NOT AVAILABLE AT THIS TIME</div>");
return false;
}
// Now push required data into a JSON array object
var sampleData = [], item;
$.each(ret, function (key, value) {
sampleData.push([value.todate, parseFloat(value.Bill.replace(/,/g, ""))]);
});
var plot = $.jqplot('chart2', [sampleData], {
title: 'AJAX JSON Data Renderer',
dataRenderer: sampleData,
...
});
}
The method signature for your datarender (i.e. ajaxDataRender) is wrong. The signature should look like this:
function(userData, plotObject, options) { ... return data; }
(See the documentation here)
In your example you are passing the datarenderer "ret" which is not a function with the correct datarender signature. Also the jsonurl you are passing to getElectricDataJSON() is redundant as at no point in your code is the data from "AccountsService.asmx/GetJSONData" persisted to "./jsondata.txt".
Hence you should change your code to this:
$(document).ready(function(){
function ajaxDataRenderer(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType: "json",
success: function (response) {
var ret = response;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var url = "AccountsService.asmx/GetJSONData";
function getElectricDataJSON() {
var plot1 = $.jqplot('chart2', url, {
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
});
}

Want to get an access_token from Twitter Oauth api using oauth.js plugin

I am trying to get a Twitter access token from their oauth api. The plugin I am using is this https://code.google.com/p/oauth/source/browse/#svn%2Fcode%2Fjavascript. So far I only get "401 failed to validate signature and token".
Strange thing is that my ajax call becomes 'GET' request even though I set type:'POST'. Seems like jquery is changing the type from POST to GET. I don't know why it does that. I am running it on my Mac. I appreciate your help/hints/suggestions/advises. Thanks!
$(function() {
function myCallback(resp) {
console.log(resp);
}
var TwitterAPI;
TwitterAPI = (function() {
var consumer_key = null;
var consumer_secret = null;
function TwitterAPI(cons_key, cons_secret) {
this.consumer_key = cons_key;
this.consumer_secret = cons_secret;
}
TwitterAPI.prototype._url = function (data) {
if (typeof data == 'array') {
return array_map([ // TODO
this, '_url'], data);
} else if ((/boolean|number|string/).test(typeof data)) {
return encodeURIComponent(data).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
} else {
return '';
}
}
TwitterAPI.prototype.myCallback = function(resp) {
console.log(resp);
}
TwitterAPI.prototype.getRequestToken = function() {
var accessor = {
consumerSecret: this.consumer_secret, //this.consumer.consumerSecret,
tokenSecret: ''
};
var message = {
method: "POST",
action: "https://api.twitter.com/oauth/request_token",
parameters: {
oauth_signature_method: "HMAC-SHA1",
oauth_consumer_key: this.consumer_key, //this.consumer.consumerKey
oauth_callback: this._url("http://127.0.0.1/foobar/libs/oauth/wtf.html"),
}
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var target = OAuth.addToURL(message.action, message.parameters);
message.parameters.oauth_signature = this._url(message.parameters.oauth_signature);
console.log(message.parameters);
$.ajax("https://api.twitter.com/oauth/request_token",
{ url: "https://api.twitter.com/oauth/request_token",
type: 'POST',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: "myCallback",
data: message.parameters,
success: function(data, textResp, xhr) {
console.log(data);
},
error: function(xhr, text, err) {
console.log(text);
}
});
};
return TwitterAPI;
})();
api = new TwitterAPI(key, secret);
$('button#request').on('click', function(e) {
e.stopPropagation();
api.getRequestToken();
});

Categories