I have wrote a HTML/Javascript code generator but instead of outputting the code to a HTML site i would like the code to be send to php to be added to a database but i cant work out how to get the out put of the javascript into PHP
there is also another javascript doc to go with this if you need it to make it work ..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="../voucher_codes.js"></script>
</head>
<body>
<h1>pattern codes</h1>
<ul id="pattern-codes"></ul>
<script>
var patternCodes = voucher_codes.generate({
prefix: "BREAK-",
postfix: "-2019",
length:5,
count: 5,
charset: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
});
function fillList(listId, items) {
var list = document.getElementById(listId);
items.forEach(function(item) {
list.innerHTML += "<li>" + item + "</li>";
});
}
fillList("pattern-codes", patternCodes);
</script>
</body>
</html>
i am wanting the output of the function "fillList" to send the output to PHP if this is possible....
You would have to look into using AJAX or the Axios library to send requests to a server page such as PHP.
Here is a simple AJAX POST server request in Javascript:
`
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
}
};
xhttp.open("POST", "request_page.php", true); // set method and page
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // set content type that we are sending POST data
xhttp.send("key=VALUE&key=VALUE"); // POST values
}
</script>
`
On the PHP page if you want to give a response of data to use back in Javascript, make sure to
json_encode($array_values)
the data array before echoing it out and set the headers to
header("Content-Type: application/json")
so you can grab the response data in Javascript and it can be turned into a Javascript {Object} or [Array]
Related
I am trying to make an API call and display that data on my HTML page. Currently no data is displayed when the button is clicked, but the API call is made successfully as I can track my usage on another page. My code is below:
<!DOCTYPE html>
<html>
<body>
<h1>API Data</h1>
<div id="container">
<div id="api">Nothing Yet</div>
</div>
<br>
<button type="button" onclick="loadAPI()">Change Content</button>
<script>
function loadAPI() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "API URL with Token here", false);
xhttp.addEventListener("load", loadData);
xhttp.send();
}
function loadData() {
document.getElementById('api').innerText = JSON.parse(this.responseText);
}
</script>
</body>
</html>
No data is displayed because you're not putting the data into the target element.
To insert data into #api, you need to do something like
document.getElementById('api').innerHTML = apiResponse; // no underscore
// or
document.getElementById('api').innerText = apiResponse;
I'll leave it for you to read up on security. https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
Also, XMLHttpRequest is asynchronous unless specified otherwise (in a param). So the most reliable way is to display the data in the load event listener. Your final code should be something like:
// Making a XMLHttpRequest
function loadAPI() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "API URL with Token Here", false);
xhttp.addEventListener("load", loadData);
xhttp.send();
}
// Displaying the data
function loadData() {
document.getElementById('api').innerText = this.responseText;
}
Note if your response is in JSON, you need to JSON.parse(this.responseText) to access the array/objects.
I have a server running OTRS 5 and I would like to retrieve a list in XML format. I'm running a JavaScript code that should display the list, but instead I get an error.
My local server is https://labcentos3/otrs/mds.pl?Action=ServiceList.
I think its a Perl script that runs on the server side and then displays a list in XML format.
This is what I get if I browse the local link: it gives me the list I want
I wrote HTML and JavaScript to try to do the same for working with the retrieved data later, but I can't get past an error.
HTML
<html>
<head>
<title>XML read</title>
<script src="reader.js" type="text/javascript"></script>
</head>
<body>
<h1>XML File</h1><br/>
</body>
</html>
reader.js
var user = "bla bla bla";
var pass = "bla bla bla"
var getXMLFile = function(path, callback) {
var request = new XMLHttpRequest();
request.open("POST", path);
request.setRequestHeader("Content-Type", "text/plain");
//request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader('Authorization', 'Basic ' + btoa(user + ":" + pass));
request.onreadystatechange = function() {
if(request.readyState === 4 && request.status === 200) {
callback(request.responseXML);
}
};
request.send();
};
getXMLFile("https://labcentos3/otrs/mds.pl?Action=ServiceList", function(xml) {
console.log(xml);
});
The error I get in the Chrome console is this:
XMLHttpRequest cannot load https://labcentos3/otrs/mds.pl?Action=ServiceList. The request was redirected to 'https://labcentos3/otrs/index.pl', which is disallowed for cross-origin requests that require preflight.
I have a php file, content.php, that is currently being loaded in the browser:
<html>
<head>
<title>Content</title>
<script src="content.js"></script>
</head>
<body>
<?php
if ( isset($_POST["status"]) && ($_POST["status"] === 1) ) {
?>
Content for users with status 1
<?php
} else {
?>
Content for users with different status
<?php
}
?>
</body>
</html>
What I want to do, is set the
$_POST["status"]
variable from within
content.js
I have thought about using a hidden html form and clicking the submit button through javascript, but that doesn't really seem like an elegant solution.
I have also thought about using an XMLHttpRequest, the problem being that I haven't found a way to send the data to the currently viewed/loading page through an XMLHttpRequest.
I am using no extra libraries, only javascript and php.
Is there a more elegant solution to my problem the a hidden html form?
Seems you need to work with AJAX because you need to execute server side script in hidden manner and update the html.
interface.php has content.js and a div
content.js send ajax post request with status
content.php sends the content according to status
interface.php's div is updated.
Here are the content.js and interface.php
let status = 1;
loadDoc(status);
function loadDoc(status) {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = () => {
if (xhttp.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML =
xhttp.responseText;
}
};
xhttp.open("POST", "content.php", true);
xhttp.send("status=" + status);
}
<html>
<head>
<title>Content</title>
<script src="content.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
And here is your content.php
<?php
if ( isset($_POST["status"]) && ($_POST["status"] === 1) ) {
?>
Content for users with status 1
<?php
} else {
?>
Content for users with different status
<?php
}
?>
Bingo! You set the $_POST["status"] via content.js
POST variables can only be passed in a request header. This means that it has to be either a form submission, as you already know, or an AJAX request. There is no way to have a separate client-side resource supply new information to an existing request.
<!doctype html>
<html>
<head>
<title>Twitter</title>
<meta charset="utf-8">
<script>
window.onload = function () {
// set up the click handler for the form button
var button = document.getElementById("submit");
button.onclick = getTweets;
}
// when you click "Get Tweets" we call this function
function getTweets() {
// set up a new XHR request
var xhr = new XMLHttpRequest();
// we're calling search.php and passing in a query string
var url = "search.php?query=";
var query = document.getElementById("query").value;
if (!query) {
query = "html5";
}
// we encode the query to handle any special characters properly
url += encodeURIComponent(query);
// this is the function that is called when the XHR request
// to our search.php script is handled, and a response sent back
xhr.onload = function () {
// if everything went okay, then send the response data
// to the displayTweets() function
if (xhr.status == 200) {
displayTweets(xhr.responseText);
} else {
var errorDiv = document.getElementById("error");
errorDiv.innerHTML = "Error getting tweets: " + xhr.status;
}
};
// make the request!
xhr.open("GET", url);
xhr.send(null);
}
function displayTweets(tweets) {
// tweets is a big long string, so we need to parse it
// into JSON first
tweets = JSON.parse(tweets);
var ul = document.querySelector("ul");
// clear existing tweets from list
while (ul.hasChildNodes()) {
ul.removeChild(ul.lastChild);
}
// add new tweets
for (var i = 0; i < tweets.length; i++) {
var li = document.createElement("li");
li.innerHTML = tweets[i].tweet;
ul.appendChild(li);
}
}
</script>
</head>
<body>
<form>
Query:
<input type="text" id="query">
<input type="button" id="submit" value="Get Tweets">
</form>
<div id="error"></div>
<ul></ul>
</body>
</html>
In the above code when I enter some text in the textbox and click on "Get Tweets" button it gives an error as Error getting tweets: 0. The search.php when executed independently without embedding in html and javascript gives accurate and required results.Can you please check the html and js code and suggest any changes in code??
Seems that the issue is CROSS-DOMAIN Ajax issue. When you execute the search.php independently, then there is no X-domain issue. But when you are embedding the code in some html, check if the html is part of the same domain or not. Also, if you are trying to run the html file from file:/// it will not work.
JSON URL : http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&suggest=
Here "str" may be any 2-3 char for an example
str = 'nas'
then JSON URL : http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search=nas&namespace=0&suggest=
I want to grab all result and put these result in a table
I tried AJAX, JSON, JQUERY
Can any one send me working Code for doing this .
My Dummy Code as :-
<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
function FillSearchBox(str)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status=200)
{
//Pointer never Comes in this Section (If I Debuug I got xmlhttp.status=0 every time)
var JSONObject = JSON.parse(xmlhttp.responseText);
}
}
var strr= "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&suggest=";
xmlhttp.open("GET",strr,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" name="wikisearch" id="" onkeyup="FillSearchBox(this.value)" />
</form>
<!-- add Table or Div Here -->
</body>
</html>
You need to use JSONP to make cross-origin requests:
function gotData(d) { alert(d); }
var s = document.createElement('script');
s.src = "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&callback=gotData";
s.appendTo(document.body);
Note that this is much easier with jQuery.