Google maps JSON markers load asynchronously? - json

I found some code to load Google Map marker data from a JSON file here: http://snippetrepo.com/snippets/multiple-markers-using-json-with-google-maps-api
It's working great, but I am getting a warning in the developer console:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
I did some research on this issue and it appears that the problem is that this code has 'async': false. I tried to just change that value to true but then I was getting another error with my function that displays the closest results to the user, because the marker array was empty when that function fired.
Is it possible to make this work asynchronously? Is there anything wrong with disabling async?
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "js/hotels.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();

Related

Convert html page (with jquery ajax calls) to pdf

I am trying to save html page to pdf using evopdf htmlToPdfConverter. The html page is using jquery ajax to get the data from web api. Any static html content in the html page is printed in the pdf but the tables showing the data from the api are not getting populated.
The url in the code below opens correctly and loads the data from api when opened in browser.
Here is the code in the Console Application that I created that references the URL and should save the html page as pdf.
//console application
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // cP7t/+rv/+zo6Oj/5/Hv/+zu8e7t8ebm5ub/7w== // HpCAkYKCkYKDiZGIn4GRgoCfgIOfiIiIiJGB
htmlToPdfConverter.LicenseKey = "HpCxxxxxxxxxxxxxxxxxxx";
htmlToPdfConverter.MediaType = "print";
htmlToPdfConverter.HtmlViewerWidth = 1024;
htmlToPdfConverter.PdfDocumentOptions.SinglePage = true; // SinglePagePdf.Checked;
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Landscape;
htmlToPdfConverter.JavaScriptEnabled = true;
htmlToPdfConverter.ConversionDelay = 15;
string url = "https://localhost:44354/trm/test.html?pid=231";
string fileName = #"C:\QSaves\test.pdf";
htmlToPdfConverter.ConvertUrlToFile(url, fileName);
/////////////////////////////////////////
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
function main() {
$.ajax({
url: 'api/csheet/?ID=' + 10,
type: 'get',
dataType: 'json',
success: function (data) {
$('#CTable').removeClass('w3-hide');
var tbl = $("#CompanyTable").dataTable({
destroy: true,
searching: false,
fixedHeader: {
header: true,
footer: true
},
data: data.Items,
sScrollX: true,
scrollH: true,
sScrollXInner: '100%',
processing: true,
bPaginate: false,
dom: 'Bfrtip',
columns: [
{
'data': 'Name',
},
]
});
}
});
}
main();
});
</script>
Your code shows the hint why it's not printing the table data.
You have document ready function which will init as soon its ready and then inside this function the Ajax will call API to load the data and populate it inside the table. Please modify the Ajax request to call in sync mode. By default Ajax requests are async that means it will call the API and will execute the further code before populating the table data.
Refer this doc for more better understanding about ajax request calls:
AJAX Request Calls
Do modify your ajax request to sync mode and then at finally call function to create the PDF.
Right now its working as below:
Page load
Document Ready Function get called
Ajax calls the API in async mode and executes further code which executes the PDF creation code before Ajax request populates the table with data, and thus you are getting PDF with empty table data.
How to get it correct:
Page load
Document ready function get called
Ajax calls the API in sync mode and executes it.
Add PDF generation code after the AJAX calls finish its data population to table.

IBM Worklight JSONStore - Add and get data

I am using worlight JSONstore. I am new to it. I tried searching that read all docs but didn't get much idea.
I have one login page from that I get some json data I want to store that data using jsonstore. and get that afterwards.
I made jsonstore adapter.
Json-Store-Impl.js
function getJsonStores(custData) {
var data = custData;
return data;
//custdata is json
}
function addJsonStore(param1) {
var input = {
method : 'put',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function updateJsonStore(param1) {
var input = {
method : 'post',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function deleteJsonStore(param1) {
var input = {
method : 'delete',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
after that I Create a local JSON store.
famlCollection.js
;(function () {
WL.JSONStore.init({
faml : {
searchFields: {"response.mci.txnid":"string","response.mci.scrnseqnbr":"string","response.loginUser":"string","request.fldWebServerId":"string","response.fldRsaImageHeight":"string","request.fldRequestId":"string","request.fldTxnId":"string","response.fldDeviceTokenFSO":"string","response.fldRsaCollectionRequired":"string","response.datlastsuccesslogin":"string","response.fldRsaUserPhrase":"string","response.fldRsaAuthTxnId":"string","response.rc.returncode":"string","response.datcurrentlogin":"string","response.mci.deviceid":"string","response.customername":"string","request.fldDeviceId":"string","response.fldRsaUserStatus":"string","request.fldScrnSeqNbr":"string","response.fldRsaImageWidth":"string","request.fldLangId":"string","response.fldTptCustomer":"string","response.encflag":"string","response.rc.errorcode":"string","response.fldRsaImagePath":"string","response.mci.appid":"string","response.mci.requestid":"string","response.rc.errormessage":"string","response.mci.appserverid":"string","response.fldRsaCollectionType":"string","request.fldAppId":"string","response.fldRsaImageId":"string","request.fldLoginUserId":"string","response.mci.sessionid":"string","response.mci.langid":"string","response.mci.remoteaddress":"string","request.fldAppServerId":"string","response.mci.webserverid":"string","response.fldRsaImageText":"string","response.fldRsaEnrollRequired":"string","response.fldRsaActivityFlag":"string"},
adapter : {
name: 'JsonStore',
replace: 'updateJsonStore',
remove: 'deleteJsonStore',
add: 'addJsonStore',
load: {
procedure: 'getJsonStores',
params: [],
key: 'faml'
},
accept: function (data) {
return (data.status === 200);
}
}
}
}, {
password : 'PleaseChangeThisPassword'
})
.then(function () {
WL.Logger.debug(['Take a look at the JSONStore documentation and getting started module for more details and code samples.',
'At this point there is no data inside your collection ("faml"), but JSONStore is ready to be used.',
'You can use WL.JSONStore.get("faml").load() to load data from the adapter.',
'These are some common JSONStore methods: load, add, replace, remove, count, push, find, findById, findAll.',
'Most operations are asynchronous, wait until the last operation finished before calling the next one.',
'JSONStore is currently supported for production only in Android and iOS environments.',
'Search Fields are not dynamic, call WL.JSONStore.destroy() and then initialize the collection with the new fields.'].join('\n'));
})
.fail(function (errObj) {
WL.Logger.ctx({pretty: true}).debug(errObj);
});
}());
When I clicked on login button I call getJsonStores like this -
getJsonStores = function(){
custData = responseData();
var invocationData = {
adapter : "JsonStore",
procedure : "getJsonStores",
parameters : [custData],
compressResponse : true
};
//WL.Logger.debug('invoke msg '+invocationData, '');
WL.Client.invokeProcedure(invocationData, {
onSuccess : sucess,
onFailure : AdapterFail,
timeout: timeout
});
};
I followed these steps
Is this right way? and how can I check jsonstore working locally or not? and how can I store my jsondata in JSONStore? Where should I initialize the wlCommonInit function in project?
plz Help me out.
Open main.js and find the wlCommonInit function, add the JSONStore init code.
WL.JSONStore.init(...)
You already have an adapter that returns the data you want to add to JSONStore, call it any time after init has finished.
WL.Client.invokeProcedure(...)
Inside the onSuccess callback, a function that gets executed when you successfully get data from the adapter, start using the JSONStore API. One high level way to write the code would be, if the collection is empty (the count API returns 0), then add all documents to the collection.
WL.JSONStore.get(collectionName).count()
.then(function (countResult) {
if(countResult === 0) {
//collection is empty, add data
WL.JSONStore.get(collectionName).add([{name: 'carlos'}, {name: 'mike'}])
.then(function () {
//data stored succesfully
});
}
});
Instead of adding [{name: 'carlos'}, {name: 'mike'}] you probably want to add the data returned from the adapter.
Later in your application, you can use the find API to get data back:
WL.JSONStore.get(collectionName).findAll()
.then(function (findResults) {
//...
});
There is also a find API that takes queries (e.g. {name: 'carlos'}), look at the getting started module here and the documentation here.
It's worth mentioning that the JSONStore API is asynchronous, you must wait for the callbacks in order to perform the next operation.

viewbag data is empty in $.ajax

Iam using asp.net mvc4 and facing some problem in accessing viewbag.price.
This is what i am doing:-
[HttpPost]
public ActionResult FillModel(int id)
{
var vehModel = db.Vehicle_Model.Where(vehMod => vehMod.MakeID == id).ToList().Select(vehMod => new SelectListItem() { Text = vehMod.Model, Value = vehMod.pkfModelID.ToString() });
ViewBag.Price = 100;
return Json(vehModel, JsonRequestBehavior.AllowGet);
}
i am calling above using below:-
$.ajax({
url: '#Url.Action("FillModel","Waranty")',
type: 'post',
data: { id: id },
dataType: 'json',
success: function (data) {
$('#ddModel').empty();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.Value).text(val.Text);
$('#ddModel').append(optionTag);
});
var a = '#ViewBag.Price';
},
error: function () {
alert('Error');
}
});
But i am not able to access ViewBag.Price.
Anyone know the reason??
thanks
The reason you aren't able to access items from the ViewBag inside your ajax success function is because the view that contains your script has already been rendered by the Razor view engine, effectively setting the variable a to whatever the value of #ViewBag.Price was at the time the page was rendered.
Looking at the process flow might be helpful:
(1) The request comes in for the view that has your script fragment in it.
(2) The controller method that returns your view is called.
(3) The Razor view engine goes through the view and replaces any references to #ViewBag.Price in your view with the actual value of ViewBag.Price. Assuming ViewBag.Price doesn't have a value yet, the success function in your script is now
success: function (data) {
$('#ddModel').empty();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.Value).text(val.Text);
$('#ddModel').append(optionTag);
});
var a = '';
}
(4) The rendered html gets sent to the client
(5) Your ajax request gets triggered
(6) On success, a gets set to the empty string.
As you had mentioned in the comments of your question, the solution to this problem is to include a in the Json object returned by your action method, and access it using data.a in your script. The return line would look like
return Json(new {
model = vehModel,
a = Price
});
Keep in mind that if you do this, you'll have to access model data in your ajax success function with data.model.Field. Also, you shouldn't need to specify the JsonRequestBehavior.AllowGet option, since your method only responds to posts and your ajax request is a post.

FineUploader OnComplete method not firing

So, I'm using FineUploader 3.3 within a MVC 4 application, and this is a very cool plugin, well worth the nominal cost. Now, I just need to get it working correctly.
I'm pretty new to MVC and absolutely new to passing back JSON, so I need some help getting this to work. Here's what I'm using, all within doc.ready.
var manualuploader = $('#files-upload').fineUploader({
request:
{
endpoint: '#Url.Action("UploadFile", "Survey")',
customHeaders: { Accept: 'application/json' },
params: {
//variables are populated outside of this code snippet
surveyInstanceId: (function () { return instance; }),
surveyItemResultId: (function () { return surveyItemResultId; }),
itemId: (function () { return itemId; }),
imageLoopCounter: (function () { return counter++; })
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp']
},
multiple: true,
text: {
uploadButton: '<i class="icon-plus icon-white"></i>Drop or Select Files'
},
callbacks: {
onComplete: function(id, fileName, responseJSON) {
alert("Success: " + responseJSON.success);
if (responseJSON.success) {
$('#files-upload').append('<img src="img/success.jpg" alt="' + fileName + '">');
}
}
}
}
EDIT: I had been using Internet Explorer 9, then switched to Chrome, Firefox and I can upload just fine. What's required for IE9? Validation doesn't work, regardless of browser.
Endpoint fires, and file/parameters are populated, so this is all good! Validation doesn't stop a user from selecting something outside of this list, but I can work with this for the time being. I can successfully save and do what I need to do with my upload, minus getting the OnComplete to fire. Actually, in IE, I get an OPEN/SAVE dialog with what I have currently.
Question: Are the function parameters in onComplete (id, filename, responseJSON) getting populated by the return or on the way out? I'm just confused about this. Does my JSON have to have these parameters in it, and populated?
I don't do this (populate those parameters), and my output method in C# returns JsonResult looking like this, just returning 'success' (if appropriate):
return Json(new { success = true });
Do I need to add more? This line is after the saving takes place, and all I want to do is tell the user all is good or not. Does the success property in my JSON match up with the responseJSON.success?
What am I missing, or have wrong?
Addressing the items in your question:
Regarding restrictions inside of the "select files" dialog, you must also set the acceptFiles validation option. See the validation option section in the readme for more details.
Your validation option property in the wrong place. It should not be under the request property/option. The same is true for your text, multiple, and callbacks options/properties. Also, you are not setting your callbacks correctly for the jQuery plug-in.
The open/save dialog in IE is caused by your server not returning a response with the correct "Content-Type" header. Your response's Content-Type should be "text/plain". See the server-side readme for more details.
Anything your server returns in it's response will be parsed by Fine Uploader using JSON.parse when handling the response client-side. The result of invoking JSON.parse on your server's response will be passed as the responseJSON parameter to your onComplete callback handler. If you want to pass specific information from your server to your client-side code, such as some text you may want to display client-side, the new name of the uploaded file, etc, you can do so by adding appropriate properties to your server response. This data will then be made available to you in your onComplete handler. If you don't have any need for this, you can simply return the "success" response you are currently returning. The server-side readme, which I have linked to, provides more information about all of this.
To clarify what I have said in #2, your code should look like this:
$('#files-upload').fineUploader({
request: {
endpoint: '#Url.Action("UploadFile", "Survey")',
customHeaders: { Accept: 'application/json' },
params: {
//variables are populated outside of this code snippet
surveyInstanceId: (function () { return instance; }),
surveyItemResultId: (function () { return surveyItemResultId; }),
itemId: (function () { return itemId; }),
imageLoopCounter: (function () { return counter++; })
}
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp']
},
text: {
uploadButton: '<i class="icon-plus icon-white"></i>Drop or Select Files'
}
})
.on('complete', function(event, id, fileName, responseJSON) {
alert("Success: " + responseJSON.success);
if (responseJSON.success) {
$('#files-upload').append('<img src="img/success.jpg" alt="' + fileName + '">');
}
});

Help using Mootools and JSONP

I am having a really hard time trying to get this to work. All I require is to console log the object that is returned. I see nothing at all in the log although the script tag is getting injected into the head.
JSON:
jsonFeed({
"results":{
"loggedin": "No",
"username": "",
"company": ""
}
});
JS:
function jsonFeed() {
}
window.addEvent('domready', function() {
new Request.JSONP({
url: <correcturl>,
onComplete: function(data){
console.log(data); // Nothing returned
}
}).send();
});
Any help is greatly appreciated.
UPDATE
I have removed the jsonFeed function at the top and changed the existing code to:
new Request.JSONP({
log: true,
url: loginstatus,
callbackKey: 'jsonFeed',
onComplete: function(data){
console.log(data); // Nothing returned
}
}).send();
In the log I get:
JSONP retrieving script with url:http://thedomain/LoggedStatus.aspx?jsonFeed=Request.JSONP.request_map.request_0
jsonFeed is not defined
In the this gets injected:
<script type="text/javascript" async="true" src="http://thedomain/LoggedStatus.aspx?jsonFeed=Request.JSONP.request_map.request_0">
-- if I expand this I see the JSON --
</script>
so a) I'm getting the jsonFeed not defined error and b) the onSuccess isn't firing :(
I really do appreciate all your help guys. And I am sorry if I am missing the point :(
UPDATE
added:
this.jsonFeed = function(data) {
console.log(data);
};
.. and it works. Thank you #Dimitar
I still don't quite understand it but now it works it helps when working it out.
it does not work because your callback function name ignores the one that Request.JSONP sends and returns jsonFeed instead.
http://mootools.net/docs/more/Request/Request.JSONP
callbackKey (string: defaults to callback) the key in the url that the server uses to wrap the JSON results. So, for example, if you used callbackKey: 'callback' then the server is expecting something like http://..../?q=search+term&callback=myFunction; This must be defined correctly.
here's an example class i wrote that gets stuff off of flickr - who use a custom callback key - it's fine. http://fragged.org/mootools-flickr-api-class-via-request-jsonp_1042.html (p.s. jsfiddle may be slow atm, friday 13th thing!)
the other thing is, if the remote end CONTINUES not to work with you and refuses to send data in the correctly wrapped format, eg:
Request.JSONP.request_map.request_0({data})
then you need to actually make sure that
this.jsonFeed = function(data) {
console.log(data);
};
where this is the global object (eg, window) - you cannot scope this, so careful where the function is defined.
if doing the latter, jsonFeed will then take the role of a callback oncomplete function.
another way is to do this, which will map the native callback function defined by the class and export it to the one your remote host likes:
onRequest: function() {
var lastCallback;
Object.each(Request.JSONP.request_map, function(el) {
lastCallback = el;
});
window.jsonFlickrApi = lastCallback;
},
onComplete: function(data) {
...
}
jsonFeed(
return //or anything else that will make this piece of data recognizable on your page
{
"results":{
"loggedin": "No",
"username": "",
"company": ""
}
});
new Request.JSONP({
url: <correcturl>,
callbackKey: 'jsonFeed'
onComplete: function(data){
console.log(data); // Nothing returned
}
}).send();