how to call REST API from javascript - javascript

I have a url which gives json data...
I want to hit that URL from javascript but I am getting this error :
character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature
Code :
function a(){
$.getJSON(url,function(data) { alert(data);});
}
full code :
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta>
<script language="JavaScript" type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
function a(){
$.getJSON(url,function(data) { alert(data);});
}
</script>
</head>
<body>
<input type="text"/>
<input type="submit" value="search" onclick="a()"/>
</body>
</html>

Your code seems correct.
Are you making a fully qualified URL call?
If you are making a fully qualified URL call, make sure of the following.
You are calling the same domain(same server). You can not make a
simple JSON call to another domain.
If you want to use a cross domain call, you'll have to use JSONp
Update:
This is not working since it is a cross domain call.
Work around for this
JavaScript
Create a function
function getMyData(data) {
alert(data);
//Do the magic with your data
}
Server side
On server end wrap your data inside function syntax
getMyData("Enter your data here");
JavaScript
Then create a script tag and add a link to your cross-domain page
<script type="text/javascript"
src="cross ref url">
</script>
For reference: wikipedia
EDIT: Another option is Create a proxy on your domain. ie create a page in your domain which internally calls the cross-domain page and return the same data to your Ajax call.

Related

GET in HTML and Not PHP

I want to process a GET extension in a HTML page and not a PHP page.
I have looked through the internet and not found anything.
URL = examplesite.com?id=1234
I assume this would go to the index page on the domain. As the index page is a HTML page, is there a way to get the details of the extension transferred to another link I have in the html script that emails me when someone looks at the site.
<script src="trigger.php">
</script>
This way I can customise the extension to know where the person found me. id=1234 is from twitter, id=2345 from FB etc.
Then i could place the extension onto the script to send me the email.
<script src="trigger.php?id=1234">
</script>
Is there a way to get the HTML page to process extension and pass it on in a variable of some sort.
Thanks in advance
Robert
You can do it in Javascript in the HTML. window.location.search contains the query string from the URL.
You can then use an AJAX request to send the query string to your server script.
<script>
$(document).ready(function() {
var script = 'trigger.php' + window.location.search;
$.get(script);
});
</script>
This is not possible with plain HTML. By definition, HTML is not dynamic. It can't process anything you want. However, there are three options.
Firstly, you can use JavaScript and AJAX calls to make another HTTP request to examplesite.com/processID.php (or another PHP page) which will process the request.
Another way to use JavaScript would be to use a client side API such as MailChimp to send the email directly from the users computer.
Or you could just redirect your root page for your domain examplesite.com to lead to index.php. I'm sure that's very easy to configure in mainstream servers such as Apache or Nginx. Otherwise please ask another question on Server Fault about how to set this up using your server.
If you are using a PHP hosting provider, they should also be able to help redirect the root page. If you don't have any access to PHP on your hosting provider, you're out of luck. You must only use the second option.
Do it with ajax
<form id="form1">
<input type="text" />
<button type="submit" id="sendforms">send</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#sendforms").click(function() {
var combinedFormData = $("#form1").serialize();
$.get(
"trigger.php",
combinedFormData
).done(function(data) {
//alert("Successfully submitted!");
$("#result").html(data);
}).fail(function () {
//alert("Error submitting forms!");
})
});
});
</script>

JQuery AJAX $.post failure to return data

I am having difficulty with a specific JQuery $.post call to a PHP-based processor. I created a test page with the code below located here: http://goo.gl/Bg7H2u
Note this is located on a subdomain, but we are not doing cross-domain posting. Everything should be included on the subdomain.
There do not seem to be any JS errors as reported in the error console.
The processor /get-data.html is the general purpose PHP processor, and, if you load the processor page with the right value, it returns a dataset from the MySQL database in JSON format. We have this working on the main domain without issue, and other $.post calls seem to work OK from this subdomain (not to this /get-data.html processor, but other processors that process form content).
See the actual processor output here: http://goo.gl/yOzrm2
I must be missing something obvious, but I am coming up empty. Thoughts?
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320px, initial-scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var prices;
$(document).ready(function(){
$.post( "/get-data.html", { table: 'prices' },
function( data ) {
prices = data;
alert(prices);
}, 'json');
});
</script>
</head>
<body>
<div style="overflow-x: hidden;" id="divMain">
</div>
</body>
</html>
Thanks for any advice you can provide.
If you do View Source on the processor output, you'll see that your script is returning:
<p>{"Basic Plan":["349"],"Basic":["349"],"Premium Plan":["549"],"Premium":["549"],"Standard Plan":["429"],"Standard":["429"],"Bonus Plan":["175"],"Additional Central AC System":["99"],"Additional central heating system":["99"],"Central Vacuum":["99"],"Whole home humidifier":["49"],"Pool (in-ground)":["179"],"Spa (in-ground)":["179"],"Septic System":["99"],"Sump Pump":["99"],"Well pump":["99"],"Whole home water softener":["99"],"Lawn sprinkler system (in-ground)":["99"],"Wine refrigerator":["49"],"Ice maker (free standing)":["49"],"Home phone (unlimited)":["49"],"TV Protection (Flat screen up to 60 inches)":["99"],"PC Protection (laptop or desktop)":["49"]}</p>
There's <p> at the beginning and </p> at the end. This is not valid JSON. You need to fix the server script so that it doesn't print anything other than the JSON (whitespace is OK, that's it).
1.confirm that /get-data.html is the correct relational url for your file location.
If you navigate directly to the /get-data.html, does it produce the results that you are after.
try running the same code without , 'json' and see if it works.
hope this helps

Trying to use youtube api on html page

Here is my code:
<!DOCTYPE html>
<html lang="en" >
<head>
<script type="text/javascript">
function showResponse(response){
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad(){
gapi.client.load('youtube','v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad(){
gapi.client.setApiKey('MyActualKey');
search();
}
function search(){
var request = gapi.client.youtube.search.list({
part: 'snippet'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response){
showResponse(response);
}
</script>
<title></title>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
</head>
<body>
<div id="response"></div>
</body>
</html>
This code is from Codecademy, and I thought I can use it on an html page and it would work.
I got an API key from google and I set my Youtube data api v3 setting to enabled in my google developers console, but this code gives me a blank page.
What am I doing wrong?
There are a few missing pieces, code snippets which codecademy likely took for granted but which are essential when placing it in your own server outside of their app. First of all, you need a line that actually loads the gapi library from google. You can put this in your code, just before the closing :
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
In short, this will get the library from Google's servers, and when it's loaded the library will automatically call your onClientLoad method, kicking off your app.
Next, you say you have an API key; make sure you put that key into your code by replacing this:
gapi.client.setApiKey('MyKey');
with this:
gapi.client.setApiKey('{WHATEVER_YOUR_ACTUAL_KEY IS');
Finally, as the commenters mentioned, your body is empty, so when your code executes the showResponse method there's no place to put what comes back. Add this:
<div id="response"></div>

How can I embed a CSRF token in a JavaScript file?

I have a Node.js application in which I have implemented CSRF. It's working fine, and when I had some JavaScript inline in a JADE file, I simply used #{token} to get the token into the JavaScript.
However, I've now moved my JavaScript into external files, and can't figure out a simple way to input the CSRF token into the code. How can I do so?
You can simply implant your token into one dom element, say, a hidden div.
And use javascript to get that element and read the token.
Consider to use a META-element in the document's head to hold the CSRF token. Then use this token in AJAX requests. If your server returns a new token, replace the contents of the META-element.
HTML:
<html>
<head>
<!-- generate this server-side -->
<meta name="csrf" content="A_VALUE">
</head>
<body>
<form>
<input type="text" name="something">
<input type="submit" value="Send">
</form>
<body>
</html>
JAVASCRIPT
(function($) {
var csrf = $("meta[name='csrf']").attr("content");
$("form").submit(function (evt) {
evt.preventDefault();
alert("CSRF: " + csrf);
});
})(jQuery);
(http://jsfiddle.net/ZmesY/1/)
Just write an inline script with a global token var which you can reference from any other scripts.
script
| window.myApp.token = #{token};
And in your js:
$.ajax({ data: { _csrf: window.myApp.token }, ...});
(The exact syntax might be wrong, was a long time since i used jade, but I'm sure you get the general idea).

JavaScript window.opener call parent function

I am trying to call a javascript function defined in a parent from a child window. I have two files like this:
Parent:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function foo () {
alert ("Hello from parent!");
}
function doStuff () {
var w = window.open("testa.html");
}
</script>
</head>
<body>
<input type="button" value="open" onClick="doStuff();" />
</body>
</html>
And child:
<html>
<head>
<title>Test A</title>
<script type="text/javascript">
function get() {
window.opener.foo();
}
</script>
</head>
<body>
<input type="button" value="Call Parent" onClick="get();" />
</body>
</html>
I can not, for the life of me, call the function foo from the child process. I thought this should be possible with the window.opener object, but I can not seem to make this work. Any suggestions?
Ensure you are accessing this via http:// so the Same origin policy passes and you can access opener from the child. It won't work if you're just using file://.
Answering Rahul's question:
Every browser can load pages from server or from local filesystem. To load file from local filesystem you should put to the browser the address like this file://[path], where [path] is the absolute path to the file in filesystem (including drive letter on Windows, see http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx for details).
To load file from local HTTP server (if you have one) you should put to address something like this http://localhost:[port]/[path], where [port] is the port where your server is running (default is 80) and [path] is the path of the file relative to the server's document root folder. Document root folder depends on the server configuration.
So, as you see, the same local file can be loaded to the browser in two ways. There is however big difference between these two ways. In the first case the browser doesn't use HTTP protocol to load the file and therefore is missing many things necessary for different mechanisms to work properly. For example AJAX doesn't work with local files, as HTTP response status is not 200, etc.
In this particular example the browser security mechanism didn't get the origin information and was preventing from accessing the parent window.

Categories

Resources