Does JSONP require server modifications? - ajax

I understand that jsonp is a technique to get around the same origin policy. You basically refer to your json serving server endpoint in a script tag, because script tags are exempt from the SO policy.
My question is: Assuming a server has an endpoint that serves up json, are there any modifications necessary on the server to make use of jsonp in the client?
I think no, but want to be sure....

Yes, JSONP is slightly different when it renders, so your server needs to support it.
JSON looks like this:
{ "name": "value" }
Whereas JSONP looks like this:
functionName({ "name": "value" });
If whatever you're using supports it you're covered, but it's not the same as supporting just JSON. When the server gets a request, for example: http://example.com/json?callback=functionName, the above is what you should render, because how it looks in the page is this:
<script type="text/javascript" src="http://example.com/json?callback=functionName"></script>
This means something that runs needs to be returned, as an illustration, this is valid:
<script type="text/javascript">
functionName({ "name": "value" });
</script>
If your server didn't support JSONP it would effectively be this:
<script type="text/javascript">
{ "name": "value" }
</script>
...and you'll get syntax errors, since that's not valid JavaScript.

Related

Django ajax response contains cloudflare script

I am learning Django by developing a web application. I have added the site to cloudflare CDN's free service. After a long learning curve i am able to send request to Django application using ajax, but strangely the response contains the script from cloudflare embedded as part of it.
Example ajax response:
<html><body>No arguments passed<script type="text/javascript">
//<![CDATA[
try{if (!window.CloudFlare) {var CloudFlare=[{verbose:0,p:0,byc:0,owlid:"cf",bag2:1,mirage2:0,oracle:0,paths:{cloudflare:"/cdn-cgi/nexp/dok3v=1613a3a185/"},atok:"b4c8a1a8481c9535dc367c9b4c8c52ab",petok:"e3070e55a3a1fceb44356d479cfa086f3dd56bbe-1429555139-1800",zone:"mydjango.in",rocket:"0",apps:{}}];CloudFlare.push({"apps":{"ape":"0c86dff90b5e1a63e6c69c775ca3d309"}});!function(a,b){a=document.createElement("script"),b=document.getElementsByTagName("script")[0],a.async=!0,a.src="//ajax.cloudflare.com/cdn-cgi/nexp/dok3v=7e13c32551/cloudflare.min.js",b.parentNode.insertBefore(a,b)}()}}catch(e){};
//]]>
</script>
</body></html>
The views.py code to return the response:
def send_response(request):
inpval = request.GET.get('inputval','')
if not inpval:
html = "<html><body>No arguments passed</body></html>"
else:
html = "<html><body> %s </body></html>" % inpval
return HttpResponse(html)
Can anyone help me understand how to remove this extra script from cloudflare?
Well, i figured out the issue, cloudflare is adding its own <script> tag just before </body>. So, instead of returning the result with html tags, just retrieved the values and processed them in the client.
Example:
if not inpval:
html = "No arguments passed"

using ajax to request information from MongoDB

Here's the thing. I decided to start learning Html/CSS/JS this summer and now that I already dominate Static webpages I'm trying to get over Dynamic webpages.
To learn it, I've decided to make a test website that will search (with some filters) books on a database. Since I don't need the database to be relational, I've decided to install MongoDB on my server and use AJAX to communicate with the server, but after some days reading tutorials and going further searching on google, I don't manage to get enough information to make a code that is able to read from the server.
First of all I added a simple JSON book on the database lets assume its url is something like 100.100.100.100:3000/library and the content is:
[
{
"_id":"book1",
"desc":"blablabladescription",
"cost":"15€"
}
]
and now I want to create a button on the html that calls a function to access the database. My general idea on how to do this is this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>mongoDB AJAX demo</title>
<script type='text/javascript' src='jquery-latest.min.js'></script>
<script type='text/javascript'>
function handler() {
var result;
$.ajax({
url: 'http://100.100.100.100:3000/library,
type: 'get',
dataType: 'jsonp',
jsonp: 'jsonp',
success: function (data) {
console.log('success', data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error', errorThrown);
}
});
return result;
}
</script>
</head>
<body>
<button type="button" onclick="handler()">click</button>
</body>
</html>
This code is a general idea I have on the structure on requesting from my server, but I know it's incomplete. I think I should make some new XMLHttpRequest(); variable.open("GET","something",true); variable.send() and also to use some callbacks to deal with async.
I hope you can help me with this doubts. I just need an explanation on how to do this or some website that has a deep tutorial, I've been using http://www.w3schools.com/ basically.
Thanks, bertri
Fortunately you can not access your database from your client-side application directly. You need to have a server-side application to access your MongoDB. Also see this post which is a near-duplicate: Client-side jQuery application with MongoDB
Based on what you feel most at home with (javascript?) the suggested choice for you would be Node.js. In Node.js you set up your connection to the database and a REST-interface to your client-application. If you want to make it really easy for yourself and just purely focus on the front-end I suggest you look into deployd.js on deployd.com. This sets up the whole back-end for you in a NoSQL database. Consequently you make ajax calls to your own API to persist, modify and retrieve objects.

How to update the value of a single datapoint using https

While the Xively API documentation and Libraries provide a good resource to read and write to Xively feeds and datastreams I cant seem to find a reference how to compose a https request to update a single datapoint.
For Example: To code a "button" on a web page that can change the value of a data point from 1 to 0, which triggers an action on the device that is connected to/with this Feed. i.e to compose a request directly in a browser to obtain the desired effect..
I am very new to this and any guidance to this would be appreciated.
You should use XivelyJS.
There is a full example of a webpage which uses WebSockets.
It's very easy to use.
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/xively-js/1.0.4/xivelyjs.min.js"></script>
<script>
// Set your API key first
xively.setKey( "YOUR_KEY_HERE" );
xively.datastream.update( "YOUR_FEED_ID", "test_datastream", 123, function( event, data ) {
console.log( data.current_value ); // Logs value changes in realtime
});
</script>

ajax form submit cross server

I have several servers on an intranet. I am passing data from one server to be processed on another server. Attempting to use ajax but I am a noob.
<script type="text/javascript" src="jquery-1.8.0.js"></script>
<script type="text/javascript">
function print(oForm){
var toggle = oForm.elements["toggle"].value;
var ticket_type_id = oForm.elements["ticket_type_id"].value;
var printer_id = oForm.elements["printer_id"].value;
var store_id = oForm.elements["store_id"].value;
var data = oForm.elements["data"].value;
var dataString = "toggle="+ toggle+ "&ticket_type_id="+ ticket_type_id+ "&printer_id="+ printer_id+ "&store_id="+ store_id+ "&data="+ data;
$.ajax(
{
type:"POST",
url:"http://192.168.12.103/crowncontrol/backend/processes/print.php",
data:dataString,
success: function(data){
alert("successful");
}
}
);
}
</script>
The above URL does not work.
But if I make the url:
"../../../backend/processes/print.php"
Which is the same location, it works fine.
Also if I send it via Anchor Get it works fine:
href="http://192.168.12.103/crowncontrol/backend/processes/print.php?etc"
The reason I am using ajax is, I want my print.php script to run with out the user noticing. The reason I can't use url:"../../../backend/processes/print.php" is because I will be sending information from one server to another servers on my intranet.
Any help would be appreciated. I've spent far too long trying to get it to work on my own.
AFTER help from the answers below instead of the entire ajax code I used:
$.getJSON('http://192.168.12.103/crowncontrol/backend/processes/print.php?callback=?',dataString,function(res){
//alert('Success');
});
also:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript">
This is a result of the same origin policy. You can not perform a normal AJAX requests cross-domain requests for security reasons (see the link about same origin policy).
Fortunately for you jQuery includes JSONP request support which uses script tag injection instead of XMLHttpRequest.
Instead of creating and using an xhr object (XMLHttpRequest which is how ajax is done) it creates a script tag with an src attribute set to your URL. it should work.
Try changing your code to :
$.ajax(
{
type:"POST",
url:"http://192.168.12.103/crowncontrol/backend/processes/print.php?callback=?",
data:dataString,
success: function(data){
alert("successful");
}
}
);
(notice the ?callback=? part)
Here is a jsonp tutorial for jQuery
Here is some information about jsonp and some information about the same origin policy
Easy way to deal with this problem is to make a script file in your server and then route the requests through that server request.Use this logic below:
Instead of making the AJAX request directly to cross domain, make the AJAX request to a new script on your server.
In that script file, get the request and make the required call(to that cross domain address).
Then recieve the response from the cross domain server and send it to the client.
Receive the result from your own server which has required data.
This diagram shows:

Why do I get this 501 Not Implemented error?

I am performing the following AJAX call:
$(document).ready(function() {
$.getJSON('https://sendgrid.com/api/user.stats.json',
{
'api_user': 'me#mydomain.com',
'api_key': 'MYAPIKEY',
'user': 'me#mydomain.com',
'category': 'MY_CATEGORY'
},
function(response){
alert('received response');
}
);
});
and I get no alert message as expected. Instead, Firebug says I get "501 Not Implemented."
Why? What do I need to do to fix this?
If I go to the URL corresponding to the AJAX call in Firebug, I get a JSON file as a download, and it contains the expected data.
One thing I've noticed is that firebug says OPTIONS instead of GET:
alt text http://grab.by/grabs/b1a13d92a4fc69aa310880a5d7a06b95.png
I don't know if this is related, but generally when requesting JSON on the client to a server in a different domain you'll need to use JSONP instead of JSON due to the Same Origin Policy. Unfortunately, it doesn't appear that their API supports using JSONP -- so they must expect you to interact with their site from your server. In that case you'll need proxy methods on your server to translate the calls to their API so that the client calls are made to a server in the same domain as the page.
As this is the top Google match for "jQuery 501 (Method not implement)" I thought I'd share what worked for me when experiencing this on the same domain (which is not your problem).
My problem was that I was not returning valid JSON, I was just returning "1". So to fix this, either:
Ensure you return valid JSON, or if you don't require a JSON response,
Swap your call to use $.ajax instead of $.getJSON, or
If you're already using &.ajax, remove type: "json"
Hope that helps some people.
I had the same problem, and realized it was an encoding problem. It was solved by encoding the values of the data sent to the server. Try something like:
$(document).ready(function() {
$.getJSON('https://sendgrid.com/api/user.stats.json',
{
'api_user': encodeURIComponent('me#mydomain.com'),
'api_key': encodeURIComponent('MYAPIKEY'),
'user': encodeURIComponent('me#mydomain.com'),
'category': encodeURIComponent('MY_CATEGORY')
},
function(response){
alert('received response');
}
);
});
end then decode the data on backend. Hope it helps someone.

Resources