How to check output of a created URL? - javascript

I want to make a RuneScape(an MMORPG Game) Name Checker. For this i am using an IRC bot. The URL i am using to check names is this- http://rscript.org/lookup.php?type=namecheck&name=
I am using javascript to take input and go to this url for checking names. The code i am using is this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
}
</script>
</head>
<body>
<input class="textBox" id="uname" type="text" maxlength="15" required/>
<input type="button" onclick="nameCheck()" value="Submit">
</body>
</html>
To proceed with this i need a code that could check the output of the final url created ie.
curl. If the output page looks like this:
START
NAMECHECK: NOTAVALIBLE
SUGGESTIONS: blah blah blah
END
Then the code should run the function nameNotAva(). And if the output is like this:
START
NAMECHECK: AVALIBLE
END
Then the code should run the function nameAva().
The question:
I just want that using javascript the output be evalutaled to check that if NAMECHECK: NOTAVAILABLE is a part of the output page or not. If yes then a function nameNotAva() should be run. Otherwise a function nameAva() should be run.

Dont know what language u are using, with jQuery u can do following things
You can load the response inside a div.
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
var output = $('#someDiv').load( curl ).html() // .html() will give you the output or what the page
if( output.contains('NAMECHECK: NOTAVALIBLE'){ nameNotAva(); }
}
You can use simple AJAX and get the response text ( may be with async false)
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
$.ajax({
url : curl,
type : 'GET' //or 'POST',
success : function( urlOutput ){
if( urlOutput .contains('NAMECHECK: NOTAVALIBLE'){
nameNotAva();
}
}
});
}

Related

send/update integer to flask with Javascript

I created a website using flask with a running sqlite-db (SQLAlchemy). I want to send an integer with javascript to flask and back. I know AJAX can be used to accomplish that, but I don't know how to send the integer whenever my if/else-statement within my javascript game is met.
games.html
if (loc == unicornloc) {
money = 5000;
alert("\n\nBRAVO! You found the Unicorn! :)");
}else {
money = -250;
alert("The unicorn isn't here :(")
}
<FORM method="POST" name="searchb">
<input type=checkbox onClick="javascript:search('x1y1');">
<input type=checkbox onClick="javascript:search('x1y2');">
<input type=checkbox onClick="javascript:search('x1y3');">
games.py
#app.route('/games/<money>',methods=['GET'])
#login_required
def games(money):
print(request.args.get('money', type=int))
return render_template('games.html',money)
I want to get the money-value to flask, calculate a new value, pass it to my db and show the updated value on my website without reloading the page.
first set up jquery in your html.
make sure that the jquery is included in your head section of the html page:
You won't need to submit a form to update the server it is enough if you put a listener on one of your buttons that sends an ajax request every time it is clicked:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var sendServerNotification = function(status){
var urlToCall = '/games/' + status;
$.ajax({
url : urlToCall, // the endpoint
type : "GET", // http method
// handle a successful response
success : function(parentDescriptions) {
console.log('success'); // log the returned json to the console
// update the page with jquery
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
$( document ).ready(function() {
$('#obsevervedbutton').click(function{
//we read the value that the user wants to submit:
var valueToSubmit = $('#valueToSubmit').val()
// here you can check if you want to submit the value
// or not
if(true){
sendServerNotification(valueToSubmit);
}
});
});
</script>
</head>
<body>
<button id="obsevervedbutton">notify server</button>
<input id="valueToSubmit"></input>
</body>
and on your server side it is important to return a json response instaed of a normal http response to finish the ajax request and invoke either the success or error url:
def games(money):
print(request.args.get('money', type=int))
# update the database here
return json.dumps({"result":"operation successfull!"})
I hope this will get you going.

How can I share javascript var with php?

I have a php file. I click on and with onclick I call a javascript function with a parameter passed. This parameter is received on javascript function like a var, but into this function I want add this to $_SESSION php var.
script language="javascript">
<?php
session_start();
?>
function recargar(myVar){
var variable_post="Mi texto recargado";
<?php
$_SESSION['b'] = variable_post; //Here I want add myVar
?>
});
}
</script>
</head>
<body>
<div id="recargado">My text</div>
<p align="center">
recargar
</p>
</body>
</html>
I know that this could be a wrong way, how can I do this possible or in a similar way?
Thanks!!
You can only manipulate $_SESSION on the server, but JS code runs only on the client. The easiest way to do that would be with an ajax call, which will look like this, assuming you're using jQuery:
function recargar(myVar){
var variable_post="Mi texto recargado";
$.get("setsession.php?var="+variable_post);
});
}
This will run the setsession.php script on the server, without reloading the page. The setsession.php script will look like this:
<?php
$_SESSION['b'] = $_GET['var'];
?>
Of course, this code needs more work on error handling, but this is the general idea.
You won't be able to set php session through js but you can use cookies with javascript like this :
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
Just call setCookie to set cookie, getCookie to get it and checkCookie to check it.
Javascript, loaded on the client-side like this, cannot write into a PHP variable directly, because PHP resides in the server-side.
To do what you want you will need to pass your Javascript variable to PHP in the server-side, via an HTTP request. It can be, for example:
clicking on a link like Click, which will reload the page (and there you will be able to do $_SESSION['b'] = $_GET['myVar'] ),
having a <form> submit, just like the link above,
or without re-loading the page by using AJAX, meaning "background" calls from Javascript to other pages without leaving your page. You can do AJAX calls in many ways, some of the other answers mention jQuery, a Javascript library that makes it easy to do such things. This post seems to explain it well.
use ajax, passing the variable to a php file.
Just below created a index.php file name in the header receives a script with an ajax, you will see that it is sending the variable you created to another file name file.php that receive so that you can process and return to the index.php file so you may make an append to your html.
I will put an example that the script's been a for variable returned can be treated the way you want.
If you do not know a lot of ajax follows the link via ajax jquery documentation.
http://api.jquery.com/jquery.ajax/
//---------------------------------------------------------------------------
index.php
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
var variable_post="Mi texto recargado";
$.ajax({
url:'file.php',
type:'post',
data:{variable_post:variable_post},
success:function(data){
$('h1').html(data);
}
});
}
);
</script>
</head>
<body>
<h1>Text Here</h1>
</body>
</html>
//---------------------------------------------------------------------------
file.php
<?php
$_SESSION['b'] = $_POST['variable_post'];
echo $_SESSION['b'];
?>
//---------------------------------------------------------------------------
Remembering that using the browser features, for example in Chrome Inspect Element -> NetWork, you can check out everything that is sent back to the ajax a php page.
If you have any questions let me know.

Node.js javascript and html script not functioning properly

okay so I am trying to make my html/javascript communicate with my nodes.js server.
what I am trying to do is post data to my nodes.js server then echo the result back into my html/javascript.
the communication is working as in node I have console.log for the postdata and I can see it via the running node console .
problem is I need javascript to wait for the node.js function to complete and then echo me the text produced by node back to the html page.
I just cannot get this to work heres my html/javascript
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html><head><title>Welcome To ....</title>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(msg){
for(i = 0; i < msg.length; i++) {
// something per item
var data = {}; //your own data
$.post("http://192.168.2.109:8111" + "?" + $.param({name: msg[i]}), data);
}
// the old code
document.getElementById("message").innerHTML = msg.join("
");
}
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body></html>
and here is my node script
var url = require('url')
var http = require('http')
var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});
if (queryData.name) {
// user told us their name in the GET request, ex: http://host:8000/?name=Tom
var basevalue = queryData.name;
var value = basevalue.split (":");
console.log(value[0]);
console.log(value[1]);
var exec = require('child_process').exec;
exec ("casperjs test.js " + value[0] + " " + value[1] + '\n',function(err, stdout, stderr) {
response.end(stdout);
});
} else {
response.end("Contact Admin - Not Working\n");
}
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8111);
can someone please show me and help me fix this thanks
IT is simple.
you need to call the alert in callback. so it will be executed when post request completed.
change your few lines as following
$.post("http://192.168.2.109:8111" + "?" + $.param({name: msg[i]}), function(data){
// data contains your response from server. now you can handle it as you want
});

get post field by JavaScript

as you know we can get post field by server side language like php,for example in php
$var1 = $_POST['field1']now I wanna know is it possible to get it by JavaScript to?(or any Client Side Language like VBScript)
for example I have page which has got form
<form method = "post" action="test.php">
in test.php I wanna get field by JavaScript,not by php.
Is it possible and how can I do it if it's possible?
You cannot read $_POST data using JavaScript.
When you submit data through the GET method, the generated query string can be read through the location.search object. Another method to "post" data from page 1 to page 2 is by using hashes.
The location object (JavaScript)
location.href = http://example.com/test.php?formElem=value&another=true#hash
location.search = ?formElem=value&another=true
location.hash = #hash
Example (based on the URL at the previous paragraph)
<script>
var $_GET = (function(){
var query_string = location.search.substr(1); //Exclude the first character: `?`
var data = query_string.split(/&+/); //
var $_GET = {};
for(var i=0; i<data.length; i++){
var qs = data.match(/^([^=]+)(?:=(.*))?$/);
$_GET[qs[1]] = qs[2];
}
return $_GET;
})()
alert($_GET["formElem"]); //Alerts "value"
</script>
An alternative method to transmit data from a form to a JavaScript HTML page is by using hashes:
<form action="index.html#someHash" method="get">
<input type="submit" name="someName" value="someValue" />
</form>
After submission, the following page will be requested: index.html?someName=someValue#someHashThe hash is available through the location.hash property.
in your test.php file, echo your post fields as a JSON object.
echo '<script> var data = '. json_encode($_POST).' </script>' ;
It can be accessed as a dictionary in javascript then.
Output in test.php
<script>
var data = { 'field1' : 'value1' , 'field2' : 'value2' } ;
alert(data['field1']);
</script>

How can I get javascript to read from a .json file?

My script currently looks like this:
<script type="text/javascript">
function updateMe(){
var x = 0;
var jsonstr = '{"date":"July 4th", "event":"Independence Day"}';
var activity=JSON.parse(jsonstr);
while(x<10){
date = document.getElementById("date"+x).innerHTML = activity.date;
event = document.getElementById("event"+x).innerHTML = activity.event;
x++;
}
}
</script>
Where date"x" and event"x" are a series of html tags. This function runs when the page loads (onload). My goal is to do this exact same thing, only from a local .json file as opposed to the hard code that I've got above. I've already checked out http://api.jquery.com/jQuery.getJSON/.
The local .json file looks like this:
{"date":"July 4th", "event":"Independence Day"}
Any suggestions?
Assuming you mean "file on a local filesystem" when you say .json file.
You'll need to save the json data formatted as jsonp, and use a file:// url to access it.
Your HTML will look like this:
<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
function updateMe(){
var x = 0;
var activity=jsonstr;
foreach (i in activity) {
date = document.getElementById(i.date).innerHTML = activity.date;
event = document.getElementById(i.event).innerHTML = activity.event;
}
}
</script>
And the file c:\data\activity.jsonp contains the following line:
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA
If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>
<p id="demo"></p>
<p>Take a look at json_demo.txt</p>
</body>
</html>
It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax
Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Here's a summary:
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Here's the example used:
var json = '{"result":true, "count":42}';
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:
Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.
If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/
Since it isn't working, I'd try using XMLHttpRequests
You could also try AJAX requests:
$.ajax({
'async': false,
'global': false,
'url': "/jsonfile.json",
'dataType': "json",
'success': function (data) {
// do stuff with data
}
});
Documentation: http://api.jquery.com/jquery.ajax/
You can do it like...
Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id= "data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.
$.ajax({
url: "File.json", //the path of the file is replaced by File.json
dataType: "json",
success: function (response) {
console.log(response); //it will return the json array
}
});
Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal;
E.g.
window.portalData = [
{
"kpi" : "NDAR",
"data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]
},
{
"kpi" : "NTI",
"data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]
},
{
"kpi" : "BS",
"data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]
},
{
"kpi" : "SISS",
"data" : [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]
},
{
"kpi" : "MID",
"data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]
}
];
You can then do the following in your HTML
<script src="server_data.js"> </script>
function getServerData(kpiCode)
{
var elem = $(window.portalData).filter(function(idx){
return window.portalData[idx].kpi == kpiCode;
});
return elem[0].data;
};
var defData = getServerData('NDAR');

Categories