Ajax Post versus GET - javascript

I am trying to implement an AJAX Example which perfectly works with the GET request, but I am not able to transmit via POST. What am I doing wrong ? The POST object received by PHP is always empty. Thanks for any advice!
HTML & JavaScript:
<html>
<head>
<title> Create a new user</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
function checkUser(){
xhttp = new XMLHttpRequest();
xhttp.open("POST","usercheck.php",true);
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var data = xhttp.responseText;
alert("Benutzer" + data);
}
}
xhttp.send("username=" + encodeURIComponent(document.getElementById("username").value));
}
</script>
</head>
<body>
<p>User:</p><br>
<input type="text" id="username" name="username">
<button onclick="checkUser();"> Check </button>
</body>
</html>
PHP Code:
<?php
$usernames = array("admin", "gast", "paul");
$validate_pattern = "/^[a-z0-9]{4,20}$/";
if (!isset($_POST["username"])) {
die("{valid:false,message:false}");
}
if (in_array($_POST["username"], $usernames)) {
die("{valid:false,message:'Username is used!'}");
}
if (!preg_match($validate_pattern, $_POST["username"])) {
die("{valid:false,message:'Username wrong.'}");
}
echo "{valid:true,message:false}";
?>

I found the bug in the code. I missed to set the request header, which was not part of the tutorial unfortunately:
xhttp.setRequestHeader('Content-Type','x-www-form-urlencoded');

Related

Javascript onclick function being called on page load

I have a simple Javascript function to be called when a button on the page is clicked. But it is getting called as soon as the page loads. Can anyone please tell me what the problem here is?
The HTML is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn">ClicMe!</button>
<div id="demo"></div>
<script src="script.js"></script>
</body>
</html>
While the 'script.js' file is as follows.
var url = "example.txt";
function loadDoc(url, cFunction) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
var btn = document.getElementById("btn");
btn.onclick = loadDoc(url, myFunction);
You must attach an event listener that invoke the function when a user clicks a button:
btn.addEventListener('click', () => {
loadDoc(url);
});
The last line of your script is calling the function instead of assigning the handler to it. Since you have arguments that you want to call it with, you need to use something to bundle the arguments and function together for when it is called. If you replace the last line with the following, it should work:
btn.onclick = loadDoc.bind(undefined, url, myFunction) // "this" value is not needed, so it is left undefined
use an arrow function like this:
btn.onclick = () => loadDoc(url, myFunction);
You are explicitly calling loadDoc() function in your JS file.
You should try this -
var url = "https://jsonplaceholder.typicode.com/posts";
function loadDoc() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn" onclick='loadDoc()'>ClicMe!</button>
<div id="demo"></div>
<script src="script.js"></script>
</body>
</html>

Can't get response using JSON API

I was wondering what I was doing wrong with this code? I'm trying to get the response for PC players from the API to be set to a tag in the html, but this isn't working.
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">
<title>Battlefield 4 Tracker</title>
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>
<script src="js/jquery-3.1.1.min.js"></script>
</head>
<body>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
var request = new XMLHttpRequest();
var jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)
var obj = JSON.parse(jsonResponse);
document.getElementById("response").innerHTML = obj.pc[1].count + "";
</script>
</body>
</html>
Since you are using JQuery as suggested by the html you provided , you can use $.get method of it. This method is a simple wrapper to work with the xmlHTTP asynchronous calls. The success call back of this method is where you should populate the obj with response.
And obj.pc is also an object, so you should access it like obj.pc.count
<!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">
<title>Battlefield 4 Tracker</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>
</head>
<body>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
var request = new XMLHttpRequest();
var obj = null;
var jsonResponse = $.get("http://api.bf4stats.com/api/onlinePlayers", function(response){
obj = response;
document.getElementById("response").innerHTML = obj.pc.count + "";
})
</script>
</body>
</html>
you forgot to send the XMLHttpRequest and what you get back is a object of object so you can call directly obj.pc.count. Try this one:
var json = new XMLHttpRequest();
json.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)
json.send(null)
var obj = JSON.parse(json.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
You never sent the request. You're missing request.send(). You then listen for the load event, when you've gotten a response.
Here's an edited version of your code. I assumed that you want to loop through all the types of devices and count them.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
function reqListener () {
//THIS HAPPENS AFTER THE REQUEST HAS BEEN LOADED.
var obj = JSON.parse(this.responseText);
var counter = 0;
for(var k in obj) {
var o = obj[k];
counter += o.count;
}
document.getElementById("response").innerHTML = counter;
}
var request = new XMLHttpRequest();
request.addEventListener("load", reqListener);
request.open("GET", "http://api.bf4stats.com/api/onlinePlayers");
request.send();
</script>
</body>
</html>
You may want to consider other events such as a failed attempt to load the request, etc. Here's more info: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
The request is never send send();
The correct way to do this is to handle it in the onreadystatechange event.
Try this (together with a proper check):
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
myFunction(obj);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(obj) {
document.getElementById("response").innerHTML = obj.pc.count;
}
or directly without extra function:
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
Demo
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
<div id="response"></div>
Try this one :-
<script>
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count + "";
}
};
jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", true);
request.send();
</script>

How to render HTML Text To Be Placed Inside third party webpage`s div without iframe?

I want to generate html as well as SVG code based on my Subsciber`s any of the position of on web page (or you can say any of the div).
I want to give some javascript code to be put in side of that page`s div so at that div whole my code place.
I don't want to use iframe because height and width is not defined its automated.
here what i have tried and i am still trying.
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
<div>
<script>
(function(){
var xhr=new XMLHttpRequest();
xhr.open("get","request Url of my side",true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200){
document.write(xhr.responseText);
}
};
}());
</script>
</div>
</body>
</html>
But what happening here is before response came whole page was loaded and document.write() erase existing content and place my responseText .
Any Help will be appreciated.
JQuery solution. You can write similar in pure java, but its a bit harder. Inside <div id="results"></div> you will get your response.
$.ajax({
url: "test.html",
cache: false
})
.done(function( html ) {
$( "#results" ).append( html );
});
Reference: http://api.jquery.com/jquery.ajax/
EDIT: Pure Javascript solution:
Async=true:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("results").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "test.html", true);
xhttp.send();
Async=false:
xhttp.open("GET", "test.html", false);
xhttp.send();
document.getElementById("results").innerHTML = xhttp.responseText;
Reference: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
its just take me long time to find document.scripts
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
Here Is The Code
<div>
<script>
(function(t){
var xhr=new XMLHttpRequest();xhr.open("get","request url",true);xhr.send();
xhr.onreadystatechange=function(){ if(xhr.readyState==4 && xhr.status==200){
document.scripts[document.scripts.length-1].parentNode.innerHTML=xhr.responseText;}}
}(this));
</script>
</div>
</body>
</html>

XMLHttpRequest can get data to display on webpage

I am trying to retrieve data from a web page and then display it on my webpage, nothing fancy atm just display it so it cam be read, however I am not sure how to do this, this is what I have so far(Also sorry if I've not done the formatting properly I'm still new to this):
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title> Night Out In Glasgow!!</title>
<link rel="stylesheet" type="text/css" href="StyleSheet.css">
<script src="pull.js"></script>
</head>
<body>
<form action = "">
<p><button type = "button" onclick ="getData()">Get The Data</button>
</p>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</body>
This is then my JS which is in a separate file called pull.js, which I have linked to in my HTML, hope this clears up any confusion form original post.
/*jslint node: true, browser: true */
"use strict";
/*jslint node: true, browser: true */
"use strict";
function getData(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://ratings.food.gov.uk/OpenDataFiles/FHRS776en- GB.xml");
xmlhttp.onreadystatechange = checkData;
xmlhttp.send(null);
function checkData() {
if(xmlhttp.status == 4){
if(xmlhttp.status == 200){
//We've got a response
alert(xmlhttp.responseXML);
}
}
else{
//Somethings went wrong
alert("Error: " + xmlhttp.status + ": " +xmlhttp.statusXML);
}
}
}
Try it in this order:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","...");
xmlhttp.onreadystatechange = {
if(xmlhttp.status == 4){
if(xmlhttp.status == 200){
...
};
xmlhttp.send();
I'm not sure with your case, but the same origin policy restricts contents retrieved via XMLHttpRequest to be accessed from a website with different origin. Go check this StackExchange answer

reading txt file from url (javascript)

I'm trying to read .txt files from external links the user provides, so I can later use them in an app. For now I'm just trying to show them in a div (.output). I got so far, and now I got stuck, don't really know how to proceed.
function getText(url){
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.send(null);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var type = request.getResponseHeader('Content-Type');
if (type.indexOf("text") !== 1) {
return request.responseText;
}
}
}
}
$(".url-input").change(function() {
getText($(".url-input").value);
});
.output {
width:500px;
height:500px;
border: 1px solid black;
}
<!DOCTYPE html>
<html>
<head>
<title>Ugh</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="output"></div>
<input class="url-input" type="url">
</body>
</html>
JavaScript get (notice you have to input the file name with the extension (.txt):
just change the value to val():
$(".url-input").change(function() {
getText($(".url-input").val());
});
jQuery get:
replace all the javascript with these few lines:
$(".url-input").change(function() {
$.get($(this).val(), function( data ) {
$('.output').html(data);
});
});
This is much better option, because the Ajax Get is an asynchronous call, so you want to update the output value on the callback.
By the way, you should do some validation on that use input before you make the Ajax call. Also, to remove the need to add the ".txt" in the input change it to:
$(".url-input").change(function() {
$.get($(this).val()+'.txt', function( data ) {
$('.output').html(data);
});
});

Categories

Resources