Trying to pull xml / json - javascript

Im having issues using trying to pull the first 15 words out of the file from the API. I have tried both as an XML and JSON and still seem to be getting this error:
XMLHttpRequest cannot load
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Im using the We feel fine API.
Here is my code:
<script type="text/javascript">
(function() {
var WeFeelAPI = "http://api.wefeelfine.org:8080/ShowFeelings?display=json&returnfields=feeling,conditions&limit=15";
$.getJSON( WeFeelAPI,function (json){
var feel = json.results[15];
console.log('Our feelings : ', feel);
});
})();
</script>
Any help would be appreciated i'm very new to all this, thanks

Reading up on the We Feel Fine APIs, it doesn't seem like they support JSONP, or even JSON from what I can see.
The issue preventing you from calling it is known as the Same Origin Policy. It prevents a domain from making an illegal request to another domain because of the security concerns it poses. You can read on it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript
JSONP (JSON with Padding) is a way for sites to work around it by loading the response a an external script that then triggers a callback function to validate the response content. This actual provides good info on SOP and JSONP: http://www.codeproject.com/Articles/42641/JSON-to-JSONP-Bypass-Same-Origin-Policy.
Unfortunately, the API you're using doesn't look to support JSONP so it would require the proxy approach. There is a clever/creative/maybe hackish(opinion) approach using something called Yahoo Query Language (YQL). YQL allows you to perform a x-domain request by using Yahoo's query service as the "proxy." You pass a request with a SQL-like query to it and Yahoo handles the JSONP approach. You can read about that here: http://developer.yahoo.com/yql/ (sorry for all the reading.)
And now for some code to demonstrate this. Note the QUERY being used to retrieve your XML and the fact that it must be encoded for URI use:
(function () {
var url = 'http://api.wefeelfine.org:8080/ShowFeelings?display=xml&returnfields=feeling,conditions&limit=15'
// using yahoo query
var query = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + url + '"') +
'&format=json&callback=?';
// make request via YQL and show data
$.getJSON( query, function(data) {
console.log(data);
// yql returns "results" in "query" from data
console.log(data.query.results);
});
})();
Play with the fiddle: http://jsfiddle.net/Ty3y2/
This same approach can actually be used to load HTML, and in fact is probably used for that more. The key is "select * from xml where..." which tells it to select everything inside the XML element found at the requested URL. Remember that XML data has a XML element at the root. Most times you will see this as "select * from html where..." because a typical web request returns HTML which is a HTML element at the root.
I have used this approach for a couple projects, though most of mine use a proxy via PHP or C#. However, I have had good success with this and it's useful when you don't want/need to put together a proxy for it.

Here's a simple PHP proxy you can run along-side your page with the JavaScript
<?php
// Saved as ShowFeelings-proxy.php
$options = array_merge($_GET, ['display' => 'xml']);
// if you don't have PHP 5.4+, you need to use the legacy array literal syntax, eg
// array('display' => 'xml')
$uri = 'http://api.wefeelfine.org:8080/ShowFeelings?' . http_build_query($options);
$xml = simplexml_load_file($uri);
// assuming you'd rather work with JSON (I know I would)
$data = [];
foreach ($xml->feeling as $feeling) {
$entry = [];
foreach ($feeling->attributes() as $attr => $val) {
$entry[$attr] = (string) $val;
}
$data[] = (object) $entry;
}
header('Content-type: application/json');
echo json_encode($data);
exit;
Then in your JavaScript...
+function($) {
var url = 'ShowFeelings-proxy.php',
options = {
'returnfields': 'feeling,conditions',
'limit': 15
};
$.getJSON(url, options, function(data) {
var feeling = data[14]; // array is zero-based
console.log(feeling);
});
}(jQuery);

Related

How to receive HTTP POST parameters on vue.js? [duplicate]

I am trying to read the post request parameters from my HTML. I can read the get request parameters using the following code in JavaScript.
$wnd.location.search
But it does not work for post request. Can anyone tell me how to read the post request parameter values in my HTML using JavaScript?
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:
var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;
Then just access the JavaScript variable in the normal way.
Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.
JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.
Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.
Use sessionStorage!
$(function(){
$('form').submit{
document.sessionStorage["form-data"] = $('this').serialize();
document.location.href = 'another-page.html';
}
});
At another-page.html:
var formData = document.sessionStorage["form-data"];
Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Why not use localStorage or any other way to set the value that you
would like to pass?
That way you have access to it from anywhere!
By anywhere I mean within the given domain/context
If you're working with a Java / REST API, a workaround is easy. In the JSP page you can do the following:
<%
String action = request.getParameter("action");
String postData = request.getParameter("dataInput");
%>
<script>
var doAction = "<% out.print(action); %>";
var postData = "<% out.print(postData); %>";
window.alert(doAction + " " + postData);
</script>
You can read the post request parameter with jQuery-PostCapture(#ssut/jQuery-PostCapture).
PostCapture plugin is consisted of some tricks.
When you are click the submit button, the onsubmit event will be dispatched.
At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.
I have a simple code to make it:
In your index.php :
<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>
In your main.js :
let my_first_post_param = $("#first_post_data").val();
So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.
POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
$val = json_encode($value); // Escape value
$vars .= "var $field = $val;\n";
}
echo "<script>\n$vars</script>\n";
}
?>
</script>
Or use it to put them in an dictionary that a function could retrieve:
<script>
<?php
if($_POST) {
$vars = array();
foreach($_POST as $field => $value) {
array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
}
echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>
Then in JavaScript:
var myText = post['text'];
// Or use a function instead if you want to do stuff to it first
function Post(variable) {
// do stuff to variable before returning...
var thisVar = post[variable];
return thisVar;
}
This is just an example and shouldn't be used for any sensitive data like a password, etc. The POST method exists for a reason; to send data securely to the backend, so that would defeat the purpose.
But if you just need a bunch of non-sensitive form data to go to your next page without /page?blah=value&bleh=value&blahbleh=value in your url, this would make for a cleaner url and your JavaScript can immediately interact with your POST data.
You can 'json_encode' to first encode your post variables via PHP.
Then create a JS object (array) from the JSON encoded post variables.
Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
One option is to set a cookie in PHP.
For example: a cookie named invalid with the value of $invalid expiring in 1 day:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
Then read it back out in JS (using the JS Cookie plugin):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
You can now access the value from the invalid variable in JavaScript.
It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language.
So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
And therefrom use post['key'] = newVal; etc...
POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.
SITE A: has a form submit to an external URL (site B) using POST
SITE B: will receive the visitor but with only GET variables
$(function(){
$('form').sumbit{
$('this').serialize();
}
});
In jQuery, the above code would give you the URL string with POST parameters in the URL.
It's not impossible to extract the POST parameters.
To use jQuery, you need to include the jQuery library. Use the following for that:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
We can collect the form params submitted using POST with using serialize concept.
Try this:
$('form').serialize();
Just enclose it alert, it displays all the parameters including hidden.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.

Parsing JSON from a file path is not working properly

I am trying to parse a list of JSON files iteratively. Using PHP I have managed to compile the list of JSON files in a directly into a a single JSON object. Now I would like to parse each of these objects and output a property from each of them in HTML. I am sure that the JSON I am initially passing works. Any ideas? here is the error and the function.
$(document).ready(function(){
console.log("something")
for(var i = 2; i < Object.keys(jsTrips).length; i++){
var data_file = "http://localhos:8080/trips/" + jsTrips[i];
var currTrip = JSON.parse(data_file)
document.getElementsByClassName(i).innerHTML = currJSON.start_time;
}
console.log("finished")
});
ignore the missing t in localhost. The problem persists even when the typo is fixed
Thanks in advance!!
UPDATE:
The Javascript object jsTrips is formatted like this:
{2: name.json, 3:name.json, 4:name.json}
The the JSON files named in jsTrips are formatted like this:
{start_time: some start time, coords: [{lat: ##, long: ##}, {lat: ##, long: ##}...], end_time: some end time}
To address the error you see:
SyntaxError: JSON.parse: Unexpected character at Line 1 Column 1
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. You are feeding it a URL when it is expecting [ or { as the first character. So h causes a Syntax Error.
Assuming you define the Object jsTrips someplace in your code, and this is a more basic object, I would suggest the following:
$(function(){
console.log("Start jsTrips");
var i = 0;
$.each(jsTrips, function(k, v){
if(i >= 2){
$.getJSON("http://localhos:8080/trips/" + v, function(data_file){
$("." + i).html(data_file.start_time);
});
}
i++;
}
console.log("Finished");
});
This code also assumes there are HTML Elements with attributes like class="2". It would be better to update your Post with an example of the Objects and an example of the JSON being returned.
Now, if the Index of the Object is the class name, then it might look more like:
$.getJSON("http://localhos:8080/trips/" + v, function(data_file){
$("." + k).html(data_file.start_time);
}
Again, need to know what you're sending and what you expect to get back.
jQuery.getJSON() Load JSON-encoded data from the server using a GET HTTP request.
See More: https://api.jquery.com/jquery.getjson/
Update
Now using JSONP method via $.getJSON(), this will help address CORS:
$(function() {
var jsTrips = {
2: "file-1.json",
3: "file-2.json",
4: "file-3.json"
};
console.log("Start jsTrips");
$.each(jsTrips, function(k, v) {
var url = "http://localhos:8080/trips/" + v;
console.log("GET " + url);
$.getJSON(url + "?callback=?", function(json) {
$("." + k).html(json.start_time);
});
});
console.log("Finished");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
As you can see, this builds the new URL from your jsTrips as expected. You can get the start_time from the JSON directly. You don't need to parse it when JSON is expected.
In regards to the new CORS issue, this is more complicated. Basically, you're not calling the same URI so the browser is protecting itself from outside code.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.
An example of a cross-origin request: The frontend JavaScript code for a web application served from http://domain-a.com uses XMLHttpRequest to make a request for http://api.domain-b.com/data.json.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request HTTP resources from the same origin the application was loaded from, unless the response from the other origin includes the right CORS headers.
See more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS & https://www.sitepoint.com/jsonp-examples/
If you are unable to change the port being used for the target JSON files, which I suspect is creating the CORS issue, you can consider using JSONP method versus GET method. Comment and let me know if this is the case, and I can update the answer. Example included in update.
Hope that helps.
This will not probably be a complete answer, because I don't really understand the question. But maybe it will help.
You told us you compiled in PHP one file from several JSON files, in general, if you have object in JSON file, it will look like { ...some key-values here... }, if you have array there, it will be [ ...some key-values here... ].
So when you compile several files with objects into one, you'll get {...some key-values here...} {...some key-values here...} and JSON does not know how to parse those, it will throw error:
console.log(JSON.parse('{"key": "value"}{"key": "value"}'))
This will work just fine, only one object there:
console.log(JSON.parse('{"key": "value"}'))
So, if for some reason you really need to compile several JSON files into one, there is a solution - to make such resulting file with new lines as separators. Than in JS you can split your file by new line, and parse each line without issues.
Like so:
const arrayOfJSONs = Array(10).fill(null).map((_,i) => JSON.stringify({key: i, keyXTen: i * 10}))
// then you join them in one big file with \\n new lines as separators
const oneBigFile = arrayOfJSONs.join("\n");
console.log("oneBigFile:\n", oneBigFile)
// on the client you get your one big file, and then parse each line like so
const parsedJSONs = oneBigFile.split("\n").map(JSON.parse)
console.log("parsedJSONs\n", parsedJSONs)
JSON.parse take string input
Javacript fetch
$(document).ready(function(){
console.log("something")
for(var i = 2; i < Object.keys(jsTrips).length; i++){
var data_file = "http://localhos:8080/trips/" + jsTrips[i];
fetch(data_file).then((res) => res.json())
.then((currJSON) => {
// document.getElementsByClassName(i).innerHTML = currJSON.start_time;
// update your DOM here
})
}
console.log("finished")
});
JQuery $.getJSON
$(document).ready(function(){
console.log("something")
for(var i = 2; i < Object.keys(jsTrips).length; i++){
var data_file = "http://localhos:8080/trips/" + jsTrips[i];
$.getJSON(data_file, (currJSON) => {
// document.getElementsByClassName(i).innerHTML = currJSON.start_time;
// Update DOM here
});
}
console.log("finished")
});

POST Slim Route not working

I'm using Slim for development. All my GET routes are working just fine, but whenever I use POST, I get "unexpected result". Please have a look at how I've implemented slim and that "unexpected error".
index-routes.php (index root file)
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim(array(
'debug' => true
));
require_once 'site-index.php';
require_once 'routes/default-routes.php';
$app->contentType('application/json');
$app->run();
?>
routes/default-routes.php
<?php
$app->post('/login',function(){
echo 'AllHailSuccess!';
})
?>
origin of POST request called via AJAX
function try1()
{
var value1 = "afsfesa";
API.call('/login','text','POST',function(data){console.log(data)},{var1:value1});
}
AJAX Call API
var API = {
call:function(url,returnType,reqType,callback,data){
var data = (!!data) ? data : {};
var callback = (!!callback) ? callback : function(){};
$.ajax({
dataType: returnType,
type:reqType,
crossDomain: true,
xhrFields: { withCredentials: true },
url: url,
data:data,
success:callback,
error:function(data){
console.log("Error!");
console.log(data);
}
});
}
}
"Unexpected error": When I execute try1(), THE POST ROUTE DOES GETS EXECUTED SUCCESSFULLY but the contents (The entire code in plain-text) of site-index.php (Which I called in root index-routes.php file) also gets logged along with it. The reason why I imported site-index.php in the first place, is because it acts like a "main stage" for my site. It's the only page I want to load and user navigates within it.
I want to know:
Why I'm getting this type of output?
Is my approach alright? I think importing my main-stage file from index- routes is causing this. Is there any other way of doing this?
Any help is appreciated. Thank you.
Your Slim calls are going to return anything that is displayed on the page.
There are a few ways to work around this:
Nest all of your page renders inside the route and don't render full pages for AJAX routes.
Modify your AJAX calls to search the returned DOM to find the relevant information.
In your example shown, AllHailSuccess! will be displayed after all of the content in site-index.php
Many people use templating software to render their pages and then use a service to render their page via the template. For more basic sites, I would recommend you create a simple service to display content.
Here's a simple example of a Viewer class I use in my project(s)
class Viewer {
/**
* Display the specified filename using the main template
* #param string $filepath The full path of the file to display
*/
public function display($filepath) {
//set a default value for $body so the template doesn't get angry when $body is not assigned.
$body = "";
if (file_exists($filepath)) {
$body = get_include_contents($filepath);
} else {
//You want to also return a HTTP Status Code 404 here.
$body = get_include_contents('404.html');
}
//render the page in the layout
include('layout.php');
}
}
/**
* Gets the contents of a file and 'pre-renders' it.
* Basically, this is an include() that saves the output to variable instead of displaying it.
*/
function get_include_contents($filepath, $params = array()) {
if (is_file($filepath)) {
ob_start();
include $filepath;
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
return false;
}
Your routes that you want to display the page layout to the user should look something like this now:
$app->get('/', function() {
(new Viewer())->display('home.html');
});
This is by no means a comprehensive solution because it does not address proper HTTP status codes and files are referenced directly in your code which can get messy, but it's a good starting point and its quick to mock something like this up.
If you want to continue in this direction, I would recommend you take a look at the Slim v2 Response Documentation and create a class that constructs and returns Response objects. This would give you much more flexibility and power to set HTTP status codes and HTTP Return headers.
I highly recommend checking out Slim v3 Responses as well because Slim 3 uses PSR-7 Response objects which are standard across multiple frameworks.

Connecting to a server-side SQL database via php with jquery

I have been trying to look over an example to figure out how to connect to a server's SQL database from a client using JQuery, AJAX, and PHP, and though it is old it seems well done and straight forward: Example Link.A single folder contains all of my php files as well as the product version of jQuery (javascript-1.10.2.min.js).
Problem 3 - Fixed
JS console shows [Object, "parsererror", SyntaxError] at
var id = data.data[0]; //get id, data['data'][0] works here as well
in client.php. Object responseText shows ..."No Database Selected"... I have updated my client.php based on Daedalus' response and am still getting the same error.
Error was in mislabeling a variable ($link instead of $con) in server-api.php
-- Code --
db-connect.php:
<?php
//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "password";
$databaseName = "server-db";
$tableName = "inventory";
?>
server-api.php:
<?php
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'db-connect-99k.php';
$con = mysql_connect($host,$user,$pass);
$db_selected = mysql_select_db('zgc7009_99k_db', $con);
$array = array('mysql' => array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con)));
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); //query
$array['mysql'][] = array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con));
$array['data'] = mysql_fetch_row($result); //fetch result
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($array);
?>
client.php
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<!-------------------------------------------------------------------------
1) Create some html content that can be accessed by jquery
-------------------------------------------------------------------------->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'server-api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
//dataType: 'json', //data format (comment out or get parsererror)
// Successful network connection
// Successful network connection
success: function(data) //on recieve of reply
{
var id = data.data[0]; //get id, data['data'][0] works here as well
var vname = data.data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
$('#error_code').html("Success!");
},
error: function() {
console.log(arguments);
}
});
});
</script>
</body>
</html>
Problem 1 - Fixed
Thanks to user help, I have managed to get rid of my original error of:
OPTIONS file:///C:/Users/zgc7009/Desktop/Code/Web/php/server-api.php No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. jquery.js:8706
XMLHttpRequest cannot load file:///C:/Users/zgc7009/Desktop/Code/Web/php/server-api.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Problem 2 - Fixed [now running on temporary web server (see link at bottom)]
Now I am running WAMP (including phpmyadmin and apache) as my webserver. I can run my php page with script (client.php) no problem, it runs, can't seem to find any errors in my logs. However, I still never seem to hit the success function of my script. I am assuming that I have inappropriately set something somewhere (eg localhost/"my site".php) but I am not sure where.
I also tried changing my AJAX function a bit, to include .done:
$.ajax({
url: 'localhost/server-api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
// Successful network connection
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
}
}).done(function() {
$('#output').html("AJAX complete");
});
but my output value never gets changed within the ajax call. I could be implementing .done incorrectly, but I just can't seem to figure out why I am not hitting anything and can't seem to find a log that is a help in finding the next step.
On previous edit I removed localhost from php calls ('localhost/server-api.php' returned a 404) and now I am stuck again. I get a 304 Not Modified from my jQuery call, but I thought that, as of jQuery 1.5 ajax handled this as a success so I should still be hitting my html text update (correct?) and I don't.
WAMP access Log:
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /client.php HTTP/1.1" 200 2146
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /jquery.js HTTP/1.1" 304 -
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /server-api.php HTTP/1.1" 200 38
Note - this is the only log that updates when I refresh client.php in my browser. my js console stays blank. I have uploaded this to a temp site: zgc7009.99k.org/client-99k.php
Forgive me if the following is drawn out, but I wish to explain all that I can;
Firstly, as noted in comments, the error method of the jQuery .ajax() method only gets called if there is an error when the method attempts to load the requisite php page you(or it(if you don't specify a url, it uses the current page)) has specified. An error in this regard would be something like a 404(page not found), 500(server error), or what-have-you.
The current error you are experiencing is two-fold:
You are not running a server on your computer(or you are and aren't accessing the page via the correct url in your browser(it should be localhost/path/to/file.extension)
Same origin policy is preventing your page from even being loaded
In regards to problem #1, a php page needs to be processed by your php interpreter, which you need to have installed on your system. I would recommend something like xampp to suit this case, though there are plenty others available.
When accessing a server which is running on your machine, one uses the localhost url in the address bar, no protocol(http://,https://,ftp://,etc), and never a file:/// protocol. For example, if I were to visit the folder test's index.php file, it would be localhost/test/index.php.
In regards to problem #2, browsers have various restrictions in place in order to prevent malicious code from executing.. One of these restrictions is the Same Origin policy, a policy which restricts documents of a differing origin than the originating request from accepting that request. For example..
If we have a server at domain.website.com, and it makes a request to otherdomain.website.com, the request will fail as the endpoint of the request is on a different domain.
Likewise, the same exists for any requests made in regards to a file:/// protocol.. It is always1 treated as a different origin, and it will always1 fail. This behavior can be changed, but it is not recommended, as it is a security hole.
I also recommend you check out MDN's article on SOP.
Of course, to fix all this.. install a web server(like xampp or wamp) on your machine(depending on your OS) or use a hosted web server, never open your html file by double clicking it, but by visiting its url(according to your webserver's directory(it differs per server)), and always make sure your domains and ports match.
1: Except in certain cases, such as here
Edit 1:
Don't know why I didn't see this before; we could have avoided headaches.. anyway, firstly, change the error catching you do here:
$dbs = mysql_select_db($databaseName, $con);
echo mysql_errno($con) . ": " . mysql_error($con). "\n";
To:
$array = array('mysql' => array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con)));
And then, change your array set after your db handling to this:
$result = mysql_query("SELECT * FROM $tableName"); //query
$array['mysql'][] = array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con));
$array['data'] = mysql_fetch_row($result);
To explain what I've changed, and why.. Your first echo was causing the json parser to fail when parsing your echoed json. If you didn't have your console open during your refresh, you wouldn't have seen that it did in fact execute the ajax request. You also do not define an error handler, so you would have never known. In order to parse the new json I just created above, modify your success handler's variable declarations above into this:
var id = data.data[0]; //get id, data['data'][0] works here as well
var vname = data.data[1]; //get name
Of course, if your mysql causes any errors, you can then access those errors with the following:
console.log(data.mysql);
Again, in your success function. To see if you have any errors with the actual .ajax() method or such, you can just do this for your error handler:
error: function() {
console.log(arguments);
}
please you should start learning to PDO or Mysqli real fast, mysql_* will soon be depreciated, that is soonest, let me rewrite your query for you using PDO and prepared statements, you can kick it off from there.
$connectionStr = 'mysql:host='.$host.';dbname='.$databaseName.'';
$driverOptions = array();
$dbh = new PDO($connectionStr, $user, $pass, $driverOptions);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$query = $dbh->prepare("SELECT * FROM $tableName");
$query->execute();
$array = fetch(PDO::FETCH_OBJ);
echo json_encode($array);

Is there a way to load a XML file from another domain using just JavaScript?

jQuery has the $.getJSON() function that I use to load json files from other domains like so:
$.getJSON('http://somesite.com/file.js', function(output) {
// do stuff with the json data
});
I was wondering if I can do the same with xml files from other domains or do I have to use a server side language for that?
This is the xml document I would like to load:
http://google.com/complete/search?output=toolbar&q=microsoft
I agree with #viyancs , simply speaking if you want to get xml of other domain, there is a cross-domain-restriction, the way to solve this is create a proxy, so the request process is:
1. use $.ajax to request your proxy(with the real xml url you want to access).
2. your proxy retrive the xml url content.
3. your proxy returns the content to your $.ajax call.
For more detail have a look at: http://developer.yahoo.com/javascript/howto-proxy.html
BTW: why you dont have to do this for JSON? it is a technique called JSONP.
you can try this
$.ajax({
type: "GET",
dataType: "xml",
url:"localhost/grab.php",
success: function(){
//to do when success
}
});
1) make service as proxy to get content from url
example in grab.php code:
<?php
$url = 'http://google.com/complete/search?output=toolbar&q=microsoft';
$parsing = parse_url($url);
$scheme = $parsing[scheme];
$baseurl = basename($url);
$strbase =$baseurl;
$finalUri = $scheme .'://' .$strbase;
$handle = fopen($finalUri, "r",true);
// If there is something, read and return
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
If you really don't have the ability to use a proxy with a cache (which is proper etiquette), you can use something like YQL as a JSONP proxy service. You'll eventually hit a limit without an API key.
// query: select * from xml where url='http://google.com/complete/search?output=toolbar&q=microsoft'
var xml_url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fgoogle.com%2Fcomplete%2Fsearch%3Foutput%3Dtoolbar%26q%3Dmicrosoft'&diagnostics=true"
$.get(xml_url,function(xml){ console.log(xml); });

Categories

Resources