This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a html form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=1.0, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id="formGIT">
<input type="text" name="GitHubUsername" id="GitHubUsername">
<input type="submit" value="Submit">
</form>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
In scripts/app.js what I want is to get the github-api data in a variable using jQuery. For that, I have tried,
var githubAPIMainStream = null;
var url = null;
$(document).ready(function(){
$('#formGIT').on('submit', function(e){
var githubusername = $('#GitHubUsername').val();
url = 'https://api.github.com/users/'+githubusername;
$.getJSON(url, function(data) {
githubAPIMainStream = data;
});
alert(githubAPIMainStream);
});
});
But, what I am getting in the githubAPIMainStream variable is a null. It would be helpful, If someone tell me what is going wrong.
$.getJSON retrieves data from a URL, and then passes it into a callback function as 'data', within the function you then need to use it. Where you're declaring githubAPIMainStream = data, you then need to alert it afterwards.
var githubAPIMainStream = null;
var url = null;
$(document).ready(function(){
$('#formGIT').on('submit', function(e){
var githubusername = $('#GitHubUsername').val();
url = 'https://api.github.com/users/'+githubusername;
$.getJSON(url, function(data) {
githubAPIMainStream = data;
alert(githubAPIMainStream);
});
});
});
EDIT Working snippet without the form submit
var githubAPIMainStream = null;
var url = null;
$(document).ready(function(){
//$('#formGIT').on('submit', function(e){
var githubusername = "shunjid"; //$('#GitHubUsername').val();
url = 'https://api.github.com/users/'+githubusername;
$.getJSON(url, function(data) {
githubAPIMainStream = data;
console.log(githubAPIMainStream);
});
//});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
I had similar code run before but now i've lost it. No matter what I do, it will never run the php 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.0">
<title>Document</title>
<script>
function kosarica() {
var vrednost = "Itworks!";
var httpr=new XMLHttpRequest();
httpr.open("POST","izpis3.php",true);
httpr.setRequestHeader("Content-type","aplication/x-www-form-urlencode");
httpr.onreadystatechange=function(){
if(httpr.readyState==4 && httpr.status ==200){
document.getElementById("responce").innerHTML=httpr.responseText;
}
httpr.send("vrednost"+vrednost);
}
}
</script>
</head>
<body>
<p id="responce">a</p>
<button onclick="kosarica()">Click me</button>
</body>
</html>
PHP Code:
<?php
echo $_POST['vrednost'];
?>
I know that I can make code for this example all in javascript but I want to run more php code where it access my database.
It does not fail, but it does never happen. You need to move the send() outside the handler.
The content type is wrong.
You need to use an equal sign to make it a variable for PHP.
Please do not use var keyword. Use const for a constant or let for a variable.
function kosarica() {
const vrednost = "Itworks!";
const httpr = new XMLHttpRequest();
httpr.open("POST", "izpis3.php", true);
httpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpr.onreadystatechange = function () {
if (httpr.readyState === 4 && httpr.status === 200) {
document.getElementById("responce").innerHTML = httpr.responseText;
}
}
httpr.send("vrednost=" + vrednost);
}
I am trying to develop a web application that allows me to type commands in the Rcon console via the web Browser.
The problem is that every time I send a command I get “[Rcon] Failed to parse message, incorrect format”.
Error message rcon
File log server
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket</title>
</head>
<body>
<h1>WebSockets Rust Server</h1>
<input type="button" value="Send" onclick="webSocketTest();">
<script>
function webSocketTest() {
// Create the WebSocket
const rcon = new WebSocket('ws://localhost:28016/1234');
rcon.onopen = function(e) {
// This line causes the problem
rcon.send('status');
}
rcon.onmessage = function(e) {
// Code
}
rcon.onerror = function(e) {
// Code
}
rcon.onclose = function(e) {
// Code
}
}
</script>
</body>
</html>
EDIT:
Finally I fix the problem. I was making the mistake of trying to collect the data in the wrong function.
<<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket</title>
</head>
<body>
<h1>WebSockets Rust Server</h1>
<input type="button" value="Send" id="btnSend"><br>
<textarea id="response" rows="10" cols="60"></textarea>
<script>
const rcon = new WebSocket('ws://localhost:28016/1234');
console.log(rcon);
rcon.onopen = function() {
console.log('Connected');
};
/* In this funcion have the server response */
rcon.onmessage = function(e) {
const msg = JSON.parse(e.data);
document.getElementById('response').innerHTML = msg.Message;
}
rcon.onerror = function (e) {
console.log(e);
}
rcon.onclose = function(e) {
console.log('Connection closed');
console.log(e);
};
/* Click Event on send btn that calls anonymous function to send the data */
const btnSend = document.getElementById("btnSend");
btnSend.addEventListener('click', function() {
/* Data to send */
const data = {
Message: "status", // rcon command
Identifier: 1, // +server.identity
Name: "totalgamer" // +server.hostname
};
/* Need to use JSON.stringify before send the data */
rcon.send(JSON.stringify(data));
});
</script>
</body>
</html>
Now it's works fine.
Hello i started javascript and im making a dynamic ajax GET page, (refreshes page when json data changed etc.).
My problem is i need to refresh page or container div when data is changed
this my code
HTML:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Refresh" content="600">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="container">
<div id="event"></div>
<div id="counter">
<span id="countdown"></span>
</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
JS:
var request = $.ajax({
url: "data.php",
type: "GET",
dataType: "json"
}).done(function (data) {
var write = '<img src="' + data.img + '">';
$("#event").html(write);
$("#event").delay(data.countdown * 1000).fadeOut();
var i = data.countdown;
var fade_out = function () {
$("#counter").fadeOut().empty();
clearInterval(counter);
};
setTimeout(fade_out, data.countdown * 1000);
function count() { $("#countdown").html(i--); }
var counter = setInterval(function () { count(); }, 1000);
});
JSon is like this
{"img":"img\/maltolmeca.jpg","countdown":"60"}
In this day and age, it might be worth you looking into libraries such as Angular, React and Vuejs which handle 'data refreshing' for you.
Anyway, in your done() function you can just call location.reload() which would refresh the page.
...though I imagine that isn't what you are actually trying to achieve. Refreshing the page like that is a bad user experience usually, so let's try a better solution.
One way of 'reloading' a div is to do something like this:
if (data.success){
$("#event").fadeOut(800, function(){
$("#event").html(msg).fadeIn().delay(2000);
});
}
or even
$("#event").load("#event");
I just put this code in to my php folder, its like from stone age but its ok for my project.
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("data.php", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);
I have seen questions and answers regarding this issue. For example How to return a HTML file as the response to a POST request? but am having problems implementing the solutions. Here is a sample of some php code in a directory called websiteIssue that does not work, and I am not sure why.
index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
$page = "";
}
include 'case.php';
?>
case.php
<?php
$testLog = 'testLog.txt';
$fileHandle = fopen('testLog.txt', 'a');
fwrite($fileHandle, '$page = '.$page."\n";
switch($page)
{
case "screen2":
include 'screen2.php';
fwrite($fileHandle, 'including screen2.php'."\n");
break;
default:
include 'screen1.php';
fwrite($fileHandle, 'including screen1.php'."\n");
break;
}
fclose($fileHandle);
?>
screen1.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen1.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen2</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen2.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen2.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen1"})> Screen 2 => Screen1</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
On initial load it works as I expected, the html in screen1.php is shown in the browser, but when the button on the page is pressed the html remains the same, rather than changing to that in screen2.php
The output to testText.log is something like:
$page =
including screen1.php
$page = screen2
including screen2.php
As is might be obvious, I am a newbie to this, and hopefully there is some basic thing I have not done. The browser I am running it on is Firefox. Any help would be much appreciated.
Small note:I retyped the code by hand for this post, and have not run it (the machine running the webserver is not connected to the internet), hopefully there are no syntax errors, but I may have made a typo somewhere.
By including the php file you are responding to the javascript, but you arent actually using that response for anything. If redirecting to that page is what you want, you need to use location.assign on the response. To do that:
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
// Redirects user to response when received.
xmlRequest.onreadystatechange=function{
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
location.assign(xmlRequest.responseText);
}
};
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
Based on the answer given by Felipe Souza I made the following modifications to allow the page to be dynamically modified rather than being a redirect. Thought I would share as it is another solution which some might be interested in.
index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
include 'case.php';
}
else
{
include 'base.php';
}
?>
case.php
<?php
switch($page)
{
case "screen2":
include('screen2.php');
break;
case "screen1":
include('screen1.php');
break;
default:
include('screen1.php');
break;
}
?>
base.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>base.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<div id="container" style="width:100%; height:100%">
<?php
if(!isset($_POST['page']))
{
$page = "";
include 'case.php';
}
?>
</div>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData = new FormData();
xmlRequest.onreadystatechange=function()
{
if(xmlRequest.readyState==4 && xmlRequest.status==200)
{
document.getElementById("container").innerHTML = xmlRequest.responseText;
}
}
for(name in data)
{
formData.append(name, data[name]);
console.log(name + ":" + data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen1.php
<button type"button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen 2</button>
screen2.php
<button type"button" onClick=dataSubmit({page:"screen1"})>Screen 2 => Screen 1</button>
There seem some potential advantages in that the amount of data sent for the new screens is smaller, and (not sure if it is useful) the structure of the website is more disguised. Anyway, it is based on the answer given by Felipe Souza and supplements it (shows a dynamic approach rather than a changing pages one). Just thought I would mention it, if that was what some were looking for.
I just signed up and want to test out the Websockets API to check on an address balance. Following the API docs, I was trying to see if I could get a proof of concept working, but I can't seem to get past the "success" message. Can someone take a look at this code and let me know what I'm doing wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Websocket Test</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script>
<script>
var connection = new WebSocket('wss://n.block.io/:443');
var message = {
"type": "account",
"api_key": "a40c-587d-e9a6-67d3",
"network": "BTC",
"type": "address",
"address": "13qUEUgSZRBqrXUyDghm1JhXMzJyrhA69h"
};
connection.onmessage = function(e){
var server_message = e.data;
console.log(server_message);
}
connection.onopen = function(){
connection.send(message);
}
</script>
</body>
</html>
https://block.io/docs/notifications
Sorry for the late reply but you need to JSON.stringify your message. Try something like this:
https://jsfiddle.net/bxw3v8c7/
<html>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var btcs = new WebSocket('wss://n.block.io/');
btcs.onopen = function()
{
var addrToMonitor = "1SomeBTCAddress";
btcs.send( JSON.stringify( {'type':'address','network':'BTC', 'address':addrToMonitor} ) );
};
btcs.onmessage = function(onmsg)
{
var response = JSON.parse(onmsg.data);
console.log(response); //for debugging
var amount = response.data.amount_received;
$('#messages').prepend("<p>" + amount + "</p>");
}
</script>
<body>
</body>
</html>