I have a college assignment in which I need to create a small chatting web site. I'm using Python for the back-end code and Flask as the framework.
Basically, I want to get the user input from the front-end, run it with a Python code I developed, and send it back as an answer. How would be the easiest way to do that?
I've read a lot about jQuery and AJAX, but I'm very bad at JS. Any tips?
What I need is to,after processing this string, send to the site whatever was processed. I tried to follow this post How do I send data from JS to Python with Flask? and it worked for my POST, but not my GET. It always returns as undefined. I tried changing to dict, trying to make different calls, but I can't find what will work specifically with what I actually need. Thanks!
EDIT!:
After trying out #arsho 's code, I got kind of lost. It works and I saw how it was implemented, but couldn't exactly make it work with what I have.
This is what I came up with:
test
https://pastebin.com/4i2hDRSJ
Sorry if I'm not being very clear. I translated the variable names for easier understanding.
Pastebin with the html my friend made me:
test
https://pastebin.com/m7FQCgAm
Scripts.js:
test
https://pastebin.com/pM1L77p7
Thanks again.
I am giving a head start for your project. I am giving a simple AJAX search example using Flask.
The application.py contains:
from flask import Flask, render_template, request, url_for, redirect
app = Flask(__name__)
#app.route('/show_search_result', methods=['GET','POST'])
def show_search_result():
if request.method == "POST":
word = request.form.get("word")
word_lower = word.lower()
data = {
"name" : "Ahmedur Rahman Shovon",
"country": "Bangladesh",
"gender": "Male"
}
if word_lower in data:
value = data[word_lower]
return value
else:
return "No data found"
else:
return redirect(url_for('show_index'))
#app.route('/')
#app.route('/index')
def show_index():
return render_template("ajax.html")
if __name__ == '__main__':
app.run(debug=True)
And in ajax.html we call the ajax requests like below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="author" content="Ahmedur Rahman Shovon">
<title>Ajax Example</title>
<link href="https://fonts.googleapis.com/css?family=Exo+2:400,400i,500,500i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<!-- Font Awesome CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-10">
<div class="card bg-light mb-3 content">
<h5 class="card-header">
<i class="fa fa-globe"></i>
Search Developer's Information (e.g.: name, country, gender etc.)
</h5>
<div class="card-body message_area" id="message_area">
</div>
<div class="card-footer">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-book"></i>
</span>
<input type="text" class="form-control" id="search_word_text"
placeholder="Search a word and press enter"/>
<span class="input-group-btn">
<button class="btn btn-dark" id="search_btn" type="button">
<i class="fa fa-search"></i> Search
</button>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
function create_message_div($original_word, $ajax_data){
$html_data = "<div><p><b>Search Term: </b><i>"+$original_word+"</i></p>";
$html_data += "<p><b>Result: </b><i>"+$ajax_data+"</i></p>";
$html_data += "<hr/></div>";
return $html_data;
}
function search_word(){
$search_word_value = $("#search_word_text").val();
$("#search_word_text").val("");
$.ajax({
url: '{{ url_for("show_search_result") }}',
data: {
"word" : $search_word_value,
},
type: 'POST',
success: function(response) {
$new_div = create_message_div($search_word_value, response);
$("#message_area").prepend($new_div);
},
error: function(error) {
console.log("Error");
}
});
}
$("#search_btn").on("click", function () {
search_word();
});
$('#search_word_text').on('keypress', function (e) {
if(e.which === 13){
search_word();
}
});
})
</script>
</body>
</html>
The output:
N.B.: I have posted the full working code to show a complete view how AJAX works with Flask. Modify it as per your requirement.
Related
I am trying to redirect the page to a different route, whenevery i get a message from the client. It is basically going to get different messages from different clients, and when it reaches specific amount in my players_choices array, i want the page to redirect.
This is my server code
from flask_app import app
from flask import render_template, redirect, request, flash, session
from flask_socketio import SocketIO, send
from flask_app.controllers import users_controller
from flask_app.controllers import scores_controller
import json
import ast
socketio = SocketIO(app, cors_allowed_origins="*")
players_choices = []
#socketio.on('message')
def handle_message(message):
print("\n\n\nMESSAGE TYPE ")
print(message)
print("\n\n\nCHOICEEEEEE END")
if message != "User connected!":
send(message, broadcast=True)
extracted_string = message['json']
print("\n\n\nIM AM HERE***********")
print(extracted_string)
choices = ast.literal_eval(extracted_string)
print("\n\n\nPRINTING JSONED DIC")
print(choices['user_id'])
print(choices['choice'])
players_choices.append(choices)
print("\n\n\nPLAYERS CHOICES")
print(players_choices)
if len(players_choices)>=2:
session['main_user_choice'] = players_choices[0]
session['opponent_user_choice'] = players_choices[1]
print("\n\n\nSESSION VALUES")
print(session['main_user_choice'])
print(session['opponent_user_choice'])
print("SESSION VALUES\n\n\n")
return redirect('/result')
if __name__ == "__main__":
socketio.run(app, host='localhost', port=5001)
And this is my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/style.css') }}">
<script type="text/javascript" src="{{ url_for('static', filename='js/script.js') }}" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var socket = io.connect("localhost:5001");
socket.on('connect', function(){
socket.send("User connected!");
});
$('#rock').on('click', function(){
//console.log("******************DATA")
//console.log($('#rock').data())
socket.send($('#rock').data())
});
$('#paper').on('click', function(){
socket.send($('#paper').data())
});
$('#scissor').on('click', function(){
socket.send($('#scissor').data())
});
});
</script>
<title>Gameplay</title>
</head>
<body class="bg-color-lght-green">
<div class="container border mt-5">
<!-- Choose now header -->
<h1 class="d-flex justify-content-center mt-5 display-5 animate__animated animate__fadeIn">CHOOSE NOW</h1>
<!-- Hand images with link to the loading page -->
<div class="d-flex flex-wrap justify-content-center gap-3 ">
<img onmouseover="addShake(this)" onmouseleave="removeShake(this)" src="{{RockPaperScissorsImages.paper}}" alt="paper">
<img onmouseover="addShake(this)" onmouseleave="removeShake(this)" src="{{RockPaperScissorsImages.rock}}" alt="rock">
<img id="scissorsss" onmouseover="addShake(this)" onmouseleave="removeShake(this)" src="{{RockPaperScissorsImages.scissors}}" alt="scissors">
</div>
<!-- HomePage Button -->
<div class="d-flex justify-content-center me-2 ms-2 mb-5">
<button onclick="window.location.href='/dashboard'" class="btn btn-outline-dark mt-5 animate__animated animate__fadeIn" style="border: 1px solid white; color: white" > Home Page</button>
</div>
</div>
</body>
</html>
i have other pages and routes defined in another controller, so i want it to redirect to '/result' route whenever len(players_choices)>=2 the length of my array reaches 2
I tried return redirect('/result') but it doesnt do anything
When using the redirect function with Flask, I believe you need to put the full URL in the parameter.
Try this:
#socketio.on('message')
def handle_message(message):
print("\n\n\nMESSAGE TYPE ")
print(message)
print("\n\n\nCHOICEEEEEE END")
if message != "User connected!":
send(message, broadcast=True)
extracted_string = message['json']
print("\n\n\nIM AM HERE***********")
print(extracted_string)
choices = ast.literal_eval(extracted_string)
print("\n\n\nPRINTING JSONED DIC")
print(choices['user_id'])
print(choices['choice'])
players_choices.append(choices)
print("\n\n\nPLAYERS CHOICES")
print(players_choices)
if len(players_choices)>=2:
session['main_user_choice'] = players_choices[0]
session['opponent_user_choice'] = players_choices[1]
print("\n\n\nSESSION VALUES")
print(session['main_user_choice'])
print(session['opponent_user_choice'])
print("SESSION VALUES\n\n\n")
return redirect('example.com/result') #Put your actual URL here. You may need to add "https://".
if __name__ == "__main__":
socketio.run(app, host='localhost', port=5001)
Look at this website for more information: Click here
I am very novice with coding, I just started learning about it a week ago.
To cut the story short, i have a code here.
function lookup (){
var mac_address = document.getElementById('mac_address');
var resultDiv = document.getElementById("result");
if(mac_address.value.length<6){
alert('Enter at least 6 characters!')
}else{
var lookUpAdress = '<object type="text/html" id="lookupresult" data="http://macvendors.co/api/jsonp/'+mac_address.value+'"></object>';
resultDiv.innerHTML=lookUpAdress;
}
}
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin">
<div style="padding:0px;">
<label>Enter mac address:</label>
<input type="text" id="mac_address" />
<input type="button" value="Lookup!" onclick="lookup();" />
<div id="result" style="margin-top:10px;" class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin">
</div><!-- Result. -->
</div><!-- Input Box. -->
</div><!-- Container. -->
</body>
</html>
I want to get the result of the Look Up and show it in a better format like :
Company :
Prefix :
Address :
Takenote I'd be happy just to get the "Company."
TIA.
Load jquery together with your html, make sure jquery is loaded otherwise you wont be able to use $.ajax and will have to go the javascript way. Also it is alot easier to use jquery than javascript to manupilate the dom. So if you are a beginner, first learn jquery then move on to javascript.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
Use the above one or any other. You can google jquery cdn.
Then add a script to the bottom of your html:
<script>
$(document).ready(function(){
GetMacAddress();
});
function GetMacAddress(){
$.ajax({
url:'http://macvendors.co/api/jsonp/34:13:e8:1b:82:e4',
type:'get',
success:function(data){
// do something with data
alert(data.result.company);
},
error:function(){
console.log('oops');
},
});
}
</script>
This code will get you the result, change the code to suite your needs, i.e. display something in textbox
I guess this would solve your problem but:
You had to look up how to do it in non jQuery (or use jQuery)
I couldn't get it to work with https connections
$.getJSON('https://anyorigin.com/go?url=http%3A//macvendors.co/api/jsonp/34%3A13%3Ae8%3A1b%3A82%3Ae4&callback=?', function(data){
console.log(data.contents);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You may read more about it here:
https://medium.freecodecamp.org/client-side-web-scraping-with-javascript-using-jquery-and-regex-5b57a271cb86
I know this sounds like a ridiculously simple question, but there is a lot more to it than just a basic function call. I'm implementing authentication on a webapp using the Auth0 python example, they have a full example available here.
I completely understand the python Auth0 stuff, and can get all the details I require from the session, but I simply can NOT work out how to move this sample code in to my app using a simple "login" and "logout" button! The HTML from the sample app looks like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script src="https://cdn.auth0.com/js/auth0/8.6.0/auth0.min.js"></script>
<script type="text/javascript" src="//use.typekit.net/iws6ohy.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- font awesome from BootstrapCDN -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
<script>
var AUTH0_CLIENT_ID = '{{env.AUTH0_CLIENT_ID}}';
var AUTH0_DOMAIN = '{{env.AUTH0_DOMAIN}}';
var AUTH0_CALLBACK_URL = '{{env.AUTH0_CALLBACK_URL if env.AUTH0_CALLBACK_URL else "http://localhost:3000/callback" }}';
var API_AUDIENCE = '{{env.API_IDENTIFIER}}';
</script>
<script src="/public/app.js"> </script>
<link href="/public/app.css" rel="stylesheet">
</head>
<body class="home">
<div class="container">
<div class="login-page clearfix">
<div class="login-box auth0-box before">
<img src="https://i.cloudup.com/StzWWrY34s.png" />
<h3>Auth0 Example</h3>
<p>Zero friction identity infrastructure, built for developers</p>
<a class="btn btn-primary btn-lg btn-login btn-block">SignIn</a>
</div>
</div>
</div>
</body>
</html>
The Javascript that is running is contained in a seperate file that is read in on document load:
$(document).ready(function() {
var auth = new auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID
});
$('.btn-login').click(function(e) {
e.preventDefault();
auth.authorize({
audience: 'https://'+AUTH0_DOMAIN+'/userinfo', // you can also set this on the .env file and put API_AUDIENCE instead
scope: 'openid profile',
responseType: 'code',
redirectUri: AUTH0_CALLBACK_URL
});
});
$('.btn-logout').click(function(e) {
e.preventDefault();
window.location.href = '/logout';
})
});
I don't want to use the standard HTML provided with the sample, all I want is a simple "login" button to, well log in the user, but for the life of me I simple don't understand how to make that happen. I want this to be as simple as possible, with all the javascript embedded in the page. I've tried the following, but it fails as the variable "e" is undefined, and I don't understand where it came from in the original example!
<html>
<head>
<script src="http://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script src="https://cdn.auth0.com/js/auth0/8.6.0/auth0.min.js"></script>
<script type="text/javascript" src="//use.typekit.net/iws6ohy.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<p><button onclick="loginfunc()">Click me</button></p>
<script>
$(document).ready(function() {
var auth = new auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID
});
},
</script>
<script>
function loginfunc(e) {
e.preventDefault();
auth.authorize({
audience: 'https://'+AUTH0_DOMAIN+'/userinfo', // you can also set this on the .env file and put API_AUDIENCE instead
scope: 'openid profile',
responseType: 'code',
redirectUri: AUTH0_CALLBACK_URL
});
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- font awesome from BootstrapCDN -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
<script>
var AUTH0_CLIENT_ID = '{{env.AUTH0_CLIENT_ID}}';
var AUTH0_DOMAIN = '{{env.AUTH0_DOMAIN}}';
var AUTH0_CALLBACK_URL = '{{env.AUTH0_CALLBACK_URL if env.AUTH0_CALLBACK_URL else "http://localhost:3000/callback" }}';
var API_AUDIENCE = '{{env.API_IDENTIFIER}}';
</script>
<script src="/public/app.js"> </script>
<link href="/public/app.css" rel="stylesheet">
</head>
<body class="home">
<div class="container">
<div class="login-page clearfix">
<div class="login-box auth0-box before">
<img src="https://i.cloudup.com/StzWWrY34s.png" />
<h3>Auth0 Example</h3>
<p>Zero friction identity infrastructure, built for developers</p>
<a class="btn btn-primary btn-lg btn-login btn-block">SignIn</a>
</div>
</div>
</div>
</body>
</html>
I'm guessing lines 6 and 7 of the original HTML is where all the "magic" is happening, I just don't know how to "read" what's going on there.
<script type="text/javascript" src="//use.typekit.net/iws6ohy.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
I understand this is a horrible, horrible question, but I've been looking at this for hours now and I'm just ready to give up, I can't look at it any more. For the life of me I don't understand why Auth0 didn't just make a super simple, all-on-on-page example that anyone can understand, not all this fancy bootstrap/css/html mess!
If anyone can help, I will be eternally grateful!
Thank you.
I did it!!!
So it turns out I was waaaaay off, it had nothing to do with the script lines I was focusing on. Here is the working code:
<html>
<head>
<script src="http://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script src="https://cdn.auth0.com/js/auth0/8.6.0/auth0.min.js"></script>
<script>
function loginfunc() {
var auth = new auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID
});
auth.authorize({
audience: 'https://'+AUTH0_DOMAIN+'/userinfo', // you can also set this on the .env file and put API_AUDIENCE instead
scope: 'openid profile',
responseType: 'code',
redirectUri: AUTH0_CALLBACK_URL
});
}
</script>
<script>
var AUTH0_CLIENT_ID = '{{env.AUTH0_CLIENT_ID}}';
var AUTH0_DOMAIN = '{{env.AUTH0_DOMAIN}}';
var AUTH0_CALLBACK_URL = '{{env.AUTH0_CALLBACK_URL if env.AUTH0_CALLBACK_URL else "http://localhost:3000/callback" }}';
var API_AUDIENCE = '{{env.API_IDENTIFIER}}';
</script>
</head>
<body >
<p><button onclick="loginfunc()">Click me</button></p>
</body>
</html>
Basically I just pulled the app.js code in to the main html file, then used a standard "onclick" button action to call the auth function. This is so much easier to read than the auth0 example.
I hope this makes the example clearer for someone else in the future. I find it really frustrating the developers confuse the core code example with completely unnecessary css and artys html formatting.
I am new to Angular.js and am trying to send form data to the server but I am getting an error for angular.js:13424 Error: [ng:areq]. I did try many answers available on Stack Overflow but I am not able to find the answer for my problem.
index.view.html (for register)
<div class="col-md-6 col-md-offset-3" >
<input type="text" ng-model="fname" placeholder="Enter the name :"required >Fristname
<br> <br>
button type="button" class="btn btn-success navbar-btn" ng-click=register()>Register </button>
</div>
index.controller.js
(function ()
{
angular
.module('app')
.controller('register.IndexController', function($scope,$http)
{
$scope.register= function()
{
$http.post('http://localhost:9000/user/register', {firstName : $scope.fname}).success(function(response)
{ console.log($scope.fname);
})
}
})
});
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>AngularJS JWT Authentication Example & Tutorial</title>
<!-- bootstrap css -->
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<!-- application css -->
<link href="app-content/app.css" rel="stylesheet" />
</head>
<!-- HEADER AND NAVBAR -->
<header>
<nav class="navbar navbar-default">
<nav class="cf" ng-include="'nav/index.view.html'" ng-controller="Main.IndexController"></nav>
</nav>
</header>
Seems that you are using the wrong controller identifier while processing your request.
You have named your controller as register.IndexController, but from the html , you are trying to access it as Main.IndexController.
Please check whether changing the html controller idenentifier solves your problem.
If you plan on using nested controllers, you can do that also. But the scope has to be identified correctly whichever controller you are using.
I've been attempting to put together a website that requires obtaining xml data from another website. So far, using only html and javascript (no twitter bootstrap), I can access the website XML and populate a select dropdown menu. Here is the non-bootstrap html code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/getXML.js"></script>
</head>
<body>
<h1>Test App</h1>
<button id="button1">submit</button>
<select id="selectState"></select>
</body>
</html>
and here is the bootstrap html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS-->
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
<!-- jQuery and JavaScript files -->
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/getXML.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<div class="container-fluid">
<div class="row-fluid">
<div class="span4 col-xs-3">
<form class = "well">
<h2 class="page-header">Inputs</h2>
<label class="control-label" for="selectState">Select State:</label>
<select id="selectState"></select>
<button type="submit" class="btn btn-default" id="button1" >submit</button>
</form>
</div>
</div>
</div>
</html>
and here is the getXML.js script:
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
$(document).ready(function(){
$( "#button1" ).click(function () {
aClient = new HttpClient();
aClient.get('http://www.waterqualitydata.us/Station/search?characteristicName=Caffeine&mimeType=xml&bBox=-92.8,44.2,-88.9,46', function(data) {
xmlDoc = $.parseXML( data ),
$xml = $( xmlDoc ),
$LocName = $xml.find( "MonitoringLocationName" );
var arr = [];
$.each($LocName,function() {
arr.push( $(this).text() );
});
for ( var i = 0; i < arr.length; i = i + 1 ) {
$('#selectState').append('<option>'+arr[i]+'</option>');
}
alert( "success" );
});
});
});
Now, when I try and using the Twitter bootstrap html, I am getting a Cross-Origin Request Block due to the Same Origin Policy.
Is there any reason why the scripts that don't use Twitter Bootstrap can get around the SOP, while the twitter bootstrap version can't?
Modify the Bootstrap script to include the 'type' attribute, like so:
<script src="js/bootstrap.min.js" type="text/javascript"></script>
The 'type' parameter here is key - it is what allows the remote request to happen. CSS and JS are allowed to do this kind of cross domain linking, as it is judged by the W3C gods to be a low security risk (at least last I checked).
Check these links out for more information on CORS:
IE's explanation: http://msdn.microsoft.com/en-us/library/ie/gg622939%28v=vs.85%29.aspx
Mozilla's thoughts: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
OK, I think I found the problem. I was placing the <button> inside a <form> element. This apparently raises the SOP block. Without the <form> element, no SOP block was raised.
I haven't looked at the exact reason behind this, but maybe its related to a security feature baked into the <form> element, since <form> elements can be used to pass sensitive information (passwords, etc.)?