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).
Related
I have a validation in my site that uses a large table (in csv format).
I've tried the following code:
let styleurl = document.getElementById("isthisthestore");
styleurl = styleurl.getAttribute("data-stylesheeturl")
console.log(styleurl);
let data;
$.ajax({
type: "GET",
url: styleurl + "/tambour.csv",
dataType: "text",
success: function(response)
{
data = $.csv.toArrays(response);
console.log(data);
}
});
I'm getting the url from an element i have on the page (I'm sure therre is a better way but that's not the problem...)
I'm getting an error that says:"GET https://correct-file-url/tambour.csv 404"
Any idea why that is?
I have created a file for you see an easy code that work, but an observation is to check the complete "url", for example, when the var will printed on console, copy this url and check it, very important are that dont have any spaces white, or doubles slashs (//), see the example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>An Example for correct csv.toArrays</title>
</head>
<body>
<div id="isthisthestore" style="display: none;" data-id="https://yousiteweb.test/"> </div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.11/jquery.csv.min.js" integrity="sha512-Y8iWYJDo6HiTo5xtml1g4QqHtl/PO1w+dmUpQfQSOTqKNsMhExfyPN2ncNAe9JuJUSKzwK/b6oaNPop4MXzkwg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
var styleurl = $('#isthisthestore').attr('data-id'); //use jquery to get an url
var styleurl = styleurl+"tambour.csv"; //dont put slashes in the file name if your var url have a slash in the end of string, like data-id="https://yoursiteweb.test/"
console.log('the complete url is: '+styleurl); // check if your url+file is available
let data;
$.ajax({
type: "GET",
url: styleurl, //the var with the csv file
dataType: "html", //type html for use jquery.csv
success: function(response)
{
data = $.csv.toArrays(response);
console.log(data);
}
});</script>
</body>
</html>
King Regards
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',
I am building a game using phaser game development and I want to send the score into mySQL database but JS and PHP don't directly communicate. I am using AJAX but I'm stuck. Here is my code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Star Runner</title>
<script>window.score=0;</script>
<script src="phaser.js"></script>
</head>
<body>
<script type="text/javascript">
// game goes here
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$(document).ready(function(){
$.ajax({
url: "inscore.php",
type: 'POST',
data: 'score='+score,
cache: false,
success: function(data) {
alert(data);}
});
});
</script>
<h1 style="color:white">Star Runner</h1
</body>
</html>
My php file 'inscore.php' would be:
<?php
include 'login.php';
$score = $_GET['score'];
echo "<p>". $score. "</p>";
//SQL queries
?>
I'm not sure if I should link this page to the php page because I just want the score to update into my database immediately after the game is done. Can someone please help me?
First, there is a little mistake in your code.
Your Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
// code here will not run
$(document).ready(function() {
$.ajax({
// ...
});
});
</script>
It suppose to be:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
// ...
});
});
</script>
And here is a example for you:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Star Runner</title>
<script src="phaser.js"></script>
</head>
<body>
<h1 style="color:white">Star Runner</h1>
<div>
Game stage ...
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// game goes here
var Game = {
score: 0,
run: function() {
// your awesome code
if (true) {
this.gameOver();
}
},
gameOver: function() {
var _this = this;
// send the request
$.ajax({
url: "inscore.php",
type: 'POST',
data: 'score=' + this.score,
cache: false,
success: function(data) {
// balabala
console.log(_this);
}
});
}
};
// Run the game
Game.run();
</script>
</body>
</html>
It is better to use OOP (Object Oriented Programming), especially in the game project.
Since you are posting data on your ajax, you should get the data on PHP's $_POST global variable
<?php
include 'login.php';
$score = $_POST['score'];
echo "<p>". $score. "</p>";
//SQL queries
?>
And try to use a php framework like laravel or symfony for this project, even a simplier one like slim would be better for you to get things done
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®ion=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®ion=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">
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');
}
});
});