I included locally in javascript a list of commonly used terms, and then I would also like to get json response from the server through ajax response. How can it be done?
var projects = ["apple", "orange"];
$('#search').autocomplete({
source: projects
});
then append the result from ajax?
The way you would go about this would be to combine the results you get back from the server with the local results array. You can accomplish this by passing a function to the source option of autocomplete:
There are three steps you'll have to perform:
Make the AJAX request and get results from the server.
Filter the local array
Combine the results
This should be pretty simple. Something like this would work:
$("input").autocomplete({
source: function(request, response) {
/* local results: */
var localResults = $.ui.autocomplete.filter(localArray, request.term);
/* Remote results: */
$.ajax({
/* AJAX options omitted... */
success: function(data) {
/* Process remote data using $.map, if necessary, then concatenate local
* and remote results.
*/
response(data.concat(localResults));
}
});
}
});
I've worked up a full example here: http://jsfiddle.net/FZ4N4/
Related
I'm trying to learn just the bare basics about suitelets in my NetSuite environment.
I have copy/pasted this code from the Help Center and I am receiving this error when clicking the URl "An unexpected error has occurred. Please click here to notify support and provide your contact information."
/**
* #NApiVersion 2.x
* #NScriptType Suitelet
*/
define([], function() {
function onRequest(context) {
var html = '<html><body><h1>Hello World</h1></body></html>';
context.response.write(html);
context.response.setHeader({
name: 'Custom-Header-Demo',
value: 'Demo'
});
}
return {
onRequest: onRequest
};
});
I have tried putting log.debugs within the script but I'm not getting anything in the execution log. I have uploaded the script, deployed, and released the suitelet but I'm still getting this error.
Error Screenshot
Tips For Success With Suitlets
1. Think like you're coding Node Express / Nextjs APIs
Set up your code to handle each request method type
/**
* #NApiVersion 2.1
* #NScriptType Suitelet
*/
define(["N/cache"], /**
* #param {cache} cache
*/
(cache) => {
/**
* Defines the Suitelet script trigger point.
* #param {Object} scriptContext
* #param {ServerRequest} scriptContext.request - Incoming request
* #param {ServerResponse} scriptContext.response - Suitelet response
* #since 2015.2
*/
const onRequest = (scriptContext) => {
let sc = scriptContext;
let req = sc.request;
let res = sc.response;
let { method, parameters, body, clientIpAddress, headers } = req;
let { write, setHeader } = res;
switch (method) {
case "GET":
// Run logic for each specific request type (Save creating files for each operation)
// Set header first then return
setHeader({
name: "Content-Type",
value: "application/json",
});
// return your server response
write({
output: "Hello World",
});
break;
case "POST":
// Add logic here for POST
break;
default:
log.error({ title: `❌ method: ${method} not supported` });
}
};
return { onRequest };
});
2. Utilize WebStorm & The SuiteCloud IDE Plugin
This will help you template out files faster and import modules and their JSDocs automatically along with giving you better IntelliSense. Along with instantly uploading your file instead of having to do it through the UI of NetSuite every time.
3. Use 2.1 Where its supported
Using 2.x is similar to ES2012 which is not the best for using let, const, and all the new ES6 functions natively available to us. Along with using string templating or literals as in the example above.
4. Use N/cache If possible
If you're fetching data like a record or ID to retrieve. Using N/cache will make the suitelet's execution much faster.
Related to your error
Try what I suggested in the code snippet. You want to set your header first before you return your response. As you're trying to set a header where the response has already been sent. Also NetSuite don't understand half the time the type of data you're sending/returning. So setting the Content-Type header will allow your response to be displayed as expected.
// If you're trying to send JSON you stringify it first before you send the data
write({
output: JSON.stringify({
text: 'Hello World'
})
});
If you are sending HTML as a response you would do the following
// Set header first for content return define
setHeader({
name: "Content-Type",
value: "text/html",
});
write({
output: '<html><body><h1>Hello World</h1></body></html>'
});
Hope this helps! 🚀
I ran the script on my Netsuite account and I didn't get the error.
Which role user did you use it to create the script and view the results? Try with the Administrator role and for sure that error is not going to be throw.
I'm processing a table of banking/statement entries that have been exported from another system via a CSV file. They are imported into a view and checked for duplicates before being presented to the user in a HTML table for final review.
Once checked they are sent via AJAX to the server so they can be added into a Django model. Everything is working OK including CSRF but I cannot access the POSTed variable although I can see it!
Unfortunately making a hidden form isn't viable as there are 80+ rows to process.
My Javascript looks like:
$.ajax({
type: 'POST',
url: '......./ajax/handleImports/',
data: entriesObj,
success: function (data) {
if (data.response && data.response) {
console.log("Update was successful");
console.log(data.entries)
} else { ... }
},
error: function() { ... }
where entriesObj is
var entriesObj = JSON.stringify({ "newentries": newEntries });
console.log(entriesObj)
and when dumped to console.log looks like:
{"newentries":[{"Include":"","Upload ID":"0","Date":"2019-01-09", ... }
Now in view.py when I return the whole request.POST object as data.entries using
context['entries'] = request.POST
return JsonResponse(context)
I get
{"{"newentries":[{"Include":"","Upload ID":"0","Date":"2019-01-09", ... }
but if I try and retrieve newentries with:
entries = request.POST.get('newentries', None)
context['entries'] = entries
return JsonResponse(context)
the console.log(data.entries) will output null?
How am I supposed to access the POSTed entriesObj?
The data is JSON, you need to get the value from request.body and parse it.
data = json.loads(request.body)
entries = data.get('newentries')
I am trying to get a response from a web service, specifically to add two WFS layers from geoserver to a leaflet web map. The first layer gets added no problem every time, but most of the time, the second layer fails, complaining that the callback function is not defined:
ReferenceError: getJson is not defined
But what is very strange to me is that the second layer will be added, only sometimes. Refreshing the page and trying again will almost always fail.
This is the code making the ajax call:
$(document).ready(function() {
...
$("#add-network-button").on("click", function() {setLocation("Moscow")})
function setLocation(locationName) {
var networkParameters = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'netex:' + locationData[locationName].networkWFSName,
maxFeatures: 99999,
outputFormat: 'text/javascript',
format_options: 'callback: getJson'
};
addWebService(map, WFSURL, networkParameters)
var buildingParameters = {
service: 'WFS',
version: '1.0.0',
request: 'GetFeature',
typeName: 'netex:' + locationData[locationName].buildingWFSName,
maxFeatures: 99999,
outputFormat: 'text/javascript',
format_options: 'callback: getJson'
};
addWebService(map, WFSURL, buildingParameters)
}
And here is the addWebService function:
var addWebService = function(map, WFSURL, WFSParameters) {
var leafletWFSParameters = L.Util.extend(WFSParameters);
console.log(WFSURL + L.Util.getParamString(leafletWFSParameters));
$.ajax({
url: WFSURL + L.Util.getParamString(leafletWFSParameters),
dataType: 'jsonp',
jsonpCallback: 'getJson',
success: handleJson,
cache: false
});
// TODO: add style
function handleJson(data) {
L.geoJson(data, {}).addTo(map);
}
}
You're using jsonp, which means the data you're getting back is not JSON, but javascript code that makes a call to a globally-defined function (which name is defined by jsonpCallback).
jQuery automagically creates a function with that name, performs the network request, and when that function runs, it destroys its own reference from the global scope.
You're performing two calls to addWebService() in quick succession, which trigger two jQuery $.ajax({jsonpCallback: 'getJson'}) calls. The second call is overwriting the globally-defined getJson callback function. When the first jsonp payload is received by your browser, the globally-defined getJson callback is destroyed. When the second jsonp payload is received, it tries to call a globally-defined getJson function, and failing. A classic race condition.
Let me quote jQuery's documentation for the jsonpCallback parameter on $.ajax(), empasis mine:
jsonpCallback
Type: String or Function()
Specify the callback function name for a JSONP request.
This value will be used instead of the random name
automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests.
I suggest you either use other transport format than JSONP, or use different callback names for each request.
I am using wordpress and php along with ajax to create a random loading of customer reviews on our main page
function loadContent() {
$.ajax({
type: "GET",
url: 'http://skillsetsonline.ssosv.com/contentLoader.php',
data: {
company: 1
},
success: function(data) {
alert(data);
var currReview = document.getElementById('reviewRand');
currReview.innerHTML = data;
}
});
}
setTimeout(loadContent, 10000); // milliseconds, so 10 seconds = 10000ms
<div id="reviewRand" class="elementToFadeInAndOut" style="font-color:#FFF;">Hi how are you</div>
I pasted the ajax command in from a stackoverflow posting that was an accepted answer but may not have it exactly right this does not include the fading CSS code I use but that is working I just need to change the content.
Currently "Hi how are you" fades in every 10 seconds. One thing I have not learned about yet with this ajax command is the
data:{company:1}
I know it simply passes &company=1 to the GET URL but in my case I do not need to send anything and since it should not break anything if it is sent I left it alone not sure if
data:{}
would work and be cleaner
I have verified that the url used does get a random review
formatted like this
I love this program.blah blah.<br>
A USER<br>
A location<br>
June 2016<br>
Each line is formatted in CSS via a class tag
Any ideas would be greatly appreciated
Since the domain you're making the AJAX request to is on a different domain/origin, what you're running in to is a CORS issue. By default, the client will not allow you to update the page with data from an AJAX request that is served on a different origin than the site where the request originated. You can read about making CORS changes here https://enable-cors.org/
A common way around this is to serve the response via JSONP. You can do this in your script at http://skillsetsonline.ssosv.com/contentLoader.php if you have access to change that file. There are also third-party sites that will request that URL for you and create a proxy that serves the response via JSONP, then you can use it on your website.
Here's an example utilizing a JSONP proxy on https://crossorigin.me
function loadContent() {
$.ajax({
type: "GET",
url: 'https://crossorigin.me/http://skillsetsonline.ssosv.com/contentLoader.php',
success: function(data) {
var currReview = document.getElementById('reviewRand');
currReview.classList.add('ready');
currReview.innerHTML = data;
}
});
}
setTimeout(loadContent, 0); /* changed this for the demo */
#reviewRand:not(.ready) {
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reviewRand"><img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif"></div>
I've got an arduino uploading sensor data to cosm.com. I made a simple webpage on my local web server to query the cosm.com API and print out the values.
The problem is that if I am not logged into cosm.com in another tab, I get this popup.
The solution is to pass my public key to cosm.com, but I am in way over my head here.
The documentation gives an example of how to do it in curl, but not javascript
curl --request GET --header "X-ApiKey: -Ux_JTwgP-8pje981acMa5811-mSAKxpR3VRUHRFQ3RBUT0g" https://api.cosm.com/v2/feeds/120687/datastreams/sensor_reading
How do I pass my key into the url?:
function getJson() {
$.ajax({
type:'GET',
url:"https://api.cosm.com/v2/feeds/120687/datastreams/sensor_reading",
//This line isn't working
data:"X-ApiKey: -Ux_JTwgP-8pje981acMa5811-mSAKxpR3VRUHRFQ3RBUT0g",
success:function(feed) {
var currentSensorValue = feed.current_value;
$('#rawData').html( currentSensorValue );
},
dataType:'jsonp'
});
}
UPDATE:
It must be possible because hurl.it is able to query the api
http://www.hurl.it/hurls/75502ac851ebc7e195aa26c62718f58fecc4a341/47ad3b36639001c3a663e716ccdf3840352645f1
UPDATE 2:
While I never did get this working, I did find a work around. Cosm has their own javascript library that does what I am looking for.
http://cosm.github.com/cosm-js/
http://jsfiddle.net/spuder/nvxQ2/5/
You need to send it as a header, not as a query string, so try this:
function getJson() {
$.ajax({
type:'GET',
url:"https://api.cosm.com/v2/feeds/120687/datastreams/sensor_reading",
headers:{"X-ApiKey": "-Ux_JTwgP-8pje981acMa5811-mSAKxpR3VRUHRFQ3RBUT0g"},
success:function(feed) {
var currentSensorValue = feed.current_value;
$('#rawData').html( currentSensorValue );
},
dataType:'jsonp'
});
}
It should be much easier to get it to work using CosmJS. It is an officially supported library and provides full coverage of Cosm API.