Yahoo Unauthorized JSONP request with Django - javascript

I have template Test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name = "viewport" content = "width = device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
</head>
<body >
<h1>Stock Quotes AutoSuggest </h1>
<br><br>
<input style="width:800px; height:20px;" id="txtTicker" class="x"/>
<script type="text/javascript">
var YAHOO = {
Finance: {
SymbolSuggest: {}
}
};
$(".x").autocomplete({
source: function (request, response) {
var query=request.term;
$.ajax({
type: "GET",
url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
data: {query: query,region:'US',lang:'en-US'},
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback",
});
// call back function
YAHOO.Finance.SymbolSuggest.ssCallback = function (data) {
var suggestions = []; //alert(JSON.stringify(data.ResultSet.Result));
$.each(data.ResultSet.Result, function(i, val) {
suggestions.push(val.symbol+ " "+ val.name);
});
response(suggestions);
}
},
minLength: 1,
select: function (event, ui) {
//alert(ui.item.value.split("#")[1]);
$(this).val(ui.item.value.split(" ")[0]);
$("#stockvalue").val(ui.item.name);
return false;
},
});</script>
</body>
</html>
Javascript uses for autosuggest ticker names. After user input some letter in input field it sends ajax request to yahoo finance and should show the result.
If i open this html directly in browser - it works fine and shows some suggestions. But after i use it in my django project it shows nothing.
My views.py:
def home(request):
return render(request, 'Test.html')
What i found out in firefox console:
1) If i open html directly:
after placing a letter in input field JS sends request to YAHOO.Finance (the full link for letter a: http://d.yimg.com/autoc.finance.yahoo.com/autoc?callback=YAHOO.Finance.SymbolSuggest.ssCallback&query=a&region=US&lang=en-US&_=1467262652424) with method GET and it's working good, we have an answer in json.
2) If we use Django to render this template:
It sends request to YAHOO too (the full link for letter a: http://d.yimg.com/autoc.finance.yahoo.com/autoc?callback=YAHOO.Finance.SymbolSuggest.ssCallback&query=a&region=US&lang=en-US&_=1467263364507) but the status is 400 Bad Request. Inside the answer from yahoo i see this: /**/YAHOO.Finance.SymbolSuggest.ssCallback({"error":{"result":null,"error":{"code":"request-error","description":"Unauthorized JSONP request"}}});
What could be wrong?

I found answer for my question:
all you need is to add this in head:
<meta charset="UTF-8" name="referrer" content="no-referrer">

Related

ajax returns the html code of current page instead of json

I'm using the $.ajax function in JQuery to get JSON from a file. HTML, JavaScript and json files are in the same directory. The problem is that when i print the data returned from the success callback function it prints the HTML markup of the HTML page instead of the JSON.
Here is my data.json file content:
{
"products":[
{
"skuNum":"SKU# 105423-2",
"brand":"nike running shoes",
"section":"men > shoe > Running shoes",
"img":"392232_004_ss_01.jpg",
"price":500
},
{
"skuNum":"SKU# 105423-2",
"brand":"south face jacket",
"section":"women > Apparel > jackets",
"img":"jacket.jpeg",
"price":800
}
]
}
my JQuery:
$(function () {
$.ajax({
type: 'GET',
URL:'data.json',
success:function (data) {
console.log(data);
},
error:function (error) {
console.log('error')
}
});
});
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="ajax.css">
<script src="jquery-3.3.1.js"></script>
</head>
<body>
<nav>
Home
Products
Help
</nav>
<div class="container">
</div>
<script src="ajax.js"></script>
</body>
</html>
And here is a snippet of the output:
Javascript is case sensitive. The correct property for URL is url in $.ajax options object
When you provide an incorrectly spelled property it will get ignored and the proper property will return undefined.
In this case since it is URL the request would get made to current page since no url is available in the options
Change:
URL:'data.json',
To
url:'data.json',

Convert JSON string in html into JSON object

I've retrieved some data in JSON format from MarkitOnDemand API, the JSON content I want is inside the body tag of the html string like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Autocompelete</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
{"Status":"SUCCESS","Name":"Apple Inc","Symbol":"AAPL","LastPrice":109.59,"Change":1.91,"ChangePercent":1.77377414561664,"Timestamp":"Wed Mar 30 15:59:00 UTC-04:00 2016","MSDate":42459.6659722222,"MarketCap":607630850970,"Volume":3211276,"ChangeYTD":105.26,"ChangePercentYTD":4.11362340870226,"High":110.41,"Low":108.6,"Open":108.64}</body>
</html>
The above code of html string is in the "data" string of my AJAX call below:
$(function(){
$('#searchform').on('submit', function(event){
event.preventDefault();
var requestdata = 'symbol=' + $('#query').val();
$.ajax({
url: "receivesearch.php",
method: "get",
data: requestdata,
success: function(data){ //html string in this data parameter
//CONFUSED HERE
}
});
});
});
But I failed to get the JSON string out of the body tag and parse it into JSON object...
Could anyone please help me with this problem? Thank you so much!!
Here is my php code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Autocompelete</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<?php
if(isset($_GET['symbol'])){
$lookupURL = "http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=" . $_GET['symbol'];
$jsonhtml = file_get_contents($lookupURL);
echo $jsonhtml;
}
?>
</body>
</html>
The Markit On Demand API supports JSON, so there's something wrong with your original query.
Have a look at this URL for an example: http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=AAPL
It returns pure JSON data, which can be processed using $.parseJSON(data)
UPDATE: Try this code for example:
var requestData = 'symbol=AAPL';
$.ajax({
url: "http://dev.markitondemand.com/MODApis/Api/v2/Quote/json",
method: "get",
data: requestdata,
success: function(data){ //html string in this data parameter
$symbolResponse = $.parseJSON(data);
}
});
UPDATE 2: Use this PHP Code: (Just this code and nothing else)
<?php
if (isset($_GET['symbol'])) {
header('Content-Type: application/json');
$lookupURL = "http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=" . $_GET['symbol'];
$jsonhtml = file_get_contents($lookupURL);
echo $jsonhtml;
}
?>
You need to parse the result twice: once as HTML using $.parseHTML(), then you can get the text from that and pass this into $.parseJSON().
Something along these lines:
success: function(data){ //html string in this data parameter
var html = $.parseHTML(data);
var body = $(html).text();
var json = $.parseJSON(body);
// use the JSON data here
}
You have the option of JSON.parse(data), $.parseJSON(data), or the un-advised eval(data).

I can't pass a variable from my jQuery code to my PHP code

I'm trying to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST, but I get the error message "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on line 9".
I'm using XAMPP, I'm running the code in localhost, I'm using Mozilla Firefox and here's my HTML/PHP code (test1.php):
<!DOCTYPE html>
<html lang="hu">
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
</head>
<body>
<?php echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";?>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
And here's my jQuery code (script1.js):
$(document).ready(function() {
var temporaryVariable = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
alert('success');
}
}).done(function() {
$('.testParagraph').addClass( temporaryVariable );
});
});
What I tried changing so far (but didn't work of course):
test1.php:
charset was previously iso-8859-2
GET instead of POST in both codes
commenting out the script tag includes
script1.js:
commenting out the $(document).ready(function() {... lines
in data: I tried changing the quote symbols from ' to " or no quote symbols at all
commenting out the success: function... line and the two lines below it
Also, when I run the PHP code, the p tag gets the temporaryVariable class from the jQuery code.
Still, I get the error message written above. I would appreciate any help I get.
Change your test1.php to:
<!DOCTYPE html>
<html lang="hu">
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
</head>
<body>
<p id='testParagraph'> </p> <!-- You receive the value by jquery not from PHP. -->
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
And your script1.js to:
$(document).ready(function() {
var temporaryVariable = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
alert('success');
}
}).done(function() {
$('#testParagraph').html(temporaryVariable); //The value is inserted into the paragraph.
});
});
Hope works for you.
Unless you are getting the php page from a post request, using $_POST['testData'] will be of no use and will always give an index not found error. If you want to set the value in the p tag from jquery, you could use $('.testParagraph').html( temporaryVariable ) instead of .addClass
Use data : 'testData=2',
Instead of data : {testData:"2"},
Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php
on line 9
means your
data: { testData:"2" },
is wrong.
Didn't test it, but this should work:
data: [ testData:"2" ],
because $_POST is an Array
It sounds like you're posting test1.php to itself, and it's not clear why you would do that.
As #Rasclatt has pointed out in the comments check to see if the data exists before you try to access it.
Change:
<?php echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";?>
To:
<?php
if( isset( $_POST['testData'] ) ) {
echo "<p class='testParagraph'>" . $_POST['testData'] . "</p>";
}
?>
If, however, test1.php is a different script altogether then make the following changes:
Include a placeholder for the ajax content in your HTML:
<p class="tetParagraph"></p>
Trim and edit your JavaScript to the following:
$(document).ready(function() {
var tempVal = "temporary variable";
$.ajax({
type: "POST",
url: "test1.php",
data: { testData:"2" },
success: function (result) {
tempVal = result;
$('.testParagraph').html( tempVal );
alert('success');
}
});
});

How to write an HTML JSON AJAX test harness with prettify, syntax highlighted JSON result?

I've written a JSON API, but I won't be working on the views.
How do I test the JSON API with a simple webpage with prettify, syntax highlighted JSON result?
Let's use the following GET API call as an example:
http://www.google.com/calendar/feeds/developer-calendar#google.com/public/full?alt=json
NOTE: this question is meant to be instructional, answer will be provided. I searched and didn't find a similar answer.
Here's the entire HTML file with in-line javascript.
I used jQuery and highlight.js in the solution.
I ran the result on Chrome, I don't believe it works properly in IE.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/7.3/highlight.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/7.3/styles/default.min.css" />
<script>
$(document).ready(function() {
hljs.initHighlightingOnLoad();
$.ajax({
url: "http://www.google.com/calendar/feeds/developer-calendar#google.com/public/full",
dataType: "json",
//contentType: "application/json; charset=utf-8", // NOTE: use this parameter when calling your host server, but doesn't work with this google api
type: "GET",
data : { alt: "json" },
complete: function(xhr, textStatus) {
// set status
$("#status").html(textStatus);
// set plaintext
$("#result").val(xhr.responseText);
// set prettytext
var data = JSON.parse(xhr.responseText);
var stringify = JSON.stringify(data, undefined, 2);
var prettify = hljs.highlightAuto(stringify).value;
prettify = hljs.fixMarkup(prettify);
$("#prettyResult").html(prettify);
}
});
});
</script>
</head>
<body>
<tt>Status: <span id="status">waiting ...</span></tt><br /><br />
<textarea id="result" style="width: 1024px; height: 100px;"></textarea>
<pre><code id="prettyResult" class="json" style="width: 1024px;"></code></pre>
</body>
</html>

django-ajax json response

I have a django url : '127.0.0.1:8000/showsym' mapped to view returning json response
def get_symptoms(request):
bp=BodySubPart.objects.get(body_subpart="head")
data1=bp.symptoms.all()
data = serializers.serialize('json', data1)
return HttpResponse(data,mimetype='application/json')
now i am trying to parse this in ajx_form.html and code for that is :
<html>
<head>
<title>Hist</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
(function() {
$.get('127.0.0.1:8000/showsym/', function(data1) {
alert(data1);
});
});
</script>
</body>
</html>
but it is not giving me any output
the page is coming blank
please help me here somebody
It is because your code tries to get the url: /127.0.0.1:8000/showsym/
Change 127.0.0.1:8000/showsym/ to /showsym/.
I suggest you use $.getJSON and name urls, assuming the url name of /showsym is showsym:
$(document).ready(function() {
$.getJSON('{% url showsym %}', function(data, textStatus, jqXHR) {
alert(data);
})
})

Categories

Resources