Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My .php is reading some variables from pos.txt and I need to show them live, without refreshing the page. I've used <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">, but it's annoying. I've read something about ajax, but I can't really understand how it works.
$line = file_get_contents('pos.txt');
list($date, $time, $x, $y, $z) = explode(' ', $line);
For this you have to use AJAX. You have to learn this http://www.w3schools.com/ajax/default.asp.
Once you learn it you will use it allways.
Just make a ajax call from your display page to your php file.
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && xmlhttp.status==200)
{
var response = ajax.responseText;
// Here is your response
}
}
ajax.open("POST", "request/path/response.php");
ajax.send(any_data);
Details
http://api.jquery.com/jquery.ajax/
$.ajax({
url: "[_YOUR_URL_]/post.txt",
}).done(function(data) {
$("#some_id").val(date.find("some data").text);
});
The code of above obvisouly won't work, but the code you will use can be that simple.
And as stated above once you go ajax you wont go back.
Using the jQuery wrapper makes the ajax bunches easier. You will want to spend an hour or two reading about it as well as looking at various samples
The easiest way is to use jquery ajax:
http://api.jquery.com/jquery.ajax/
You want to do something like this:
$.ajax({
url: "pos.txt",
}).done(function(data) {
var split = data.split(' ');
var date = split[0];
var time = split[1];
var x = split[2];
var y = split[3];
var z = split[4];
//then insert these variables into the elements you need
$('#date').val(date);
});
Try this it will work:
<html>
<head>
<script>
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && xmlhttp.status==200)
{
var response = ajax.responseText;
document.getElementById('get-data').innerHtml = response;
}
}
ajax.open("GET", "pos.txt");
ajax.send(any_data);
</script>
</head>
<body>
<div id="get-data">
</div>
</body>
</html>
Related
Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.
I am trying to do this on client side using JavaScript.
Question: How to access JSON stored within https://www.instagram.com/xsolvesoftware/media/ with JavaScript and turn it into Object?
I tried xmlHttpRequest
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
var data = httpGet("https://www.instagram.com/xsolvesoftware/media/");
console.log(data);
I have tried loading it with src but it obviously doesn't work as it works only on content inside of tags:
var jsonData = JSON.parse(document.getElementById('data').textContent)
<script id="data" type="application/json" src="https://www.instagram.com/xsolvesoftware/media/">
</script>
I have tried editing this example but it uses JSONP not JSON as a reply and i think i would get JSONP only if i would use registered with access to users content:
var token = '1362124742.3ad74ca.6df307b8ac184c2d830f6bd7c2ac5644',
num_photos = 10,
container = document.getElementById( 'rudr_instafeed' ),
scrElement = document.createElement( 'script' );
window.mishaProcessResult = function( data ) {
for( x in data.data ){
container.innerHTML += '<li><img src="' + data.data[x].images.low_resolution.url + '"></li>';
}
}
scrElement.setAttribute( 'src', 'https://api.instagram.com/v1/users/self/media/recent?access_token=' + token + '&count=' + num_photos + '&callback=mishaProcessResult' );
document.body.appendChild( scrElement );
<ul id="rudr_instafeed"></ul>
have you already tried it?
What is you concrete problem?
If you have already tried, you could provide some code snippets and explain what you are struggeling with? (edit: you edited the question and added some code snippets, I'll have a look at them now)
From the distance it sounds like you are running into the CORS trap.
You need a backend service that fetches the json for you running on the same origin as you page is served from. This answer is a good starting point :)
Hope this helps.
edit: Had a look at your snippets and it is like I assumed: you have a problem with CORS. Your javascript is not allowed to load data from any arbitrary URL.
I'm working on an application that should be sending a post request to an internal page that does a certain calculation
When pressing a button, the page(dashboard.php) prints the content of the other page(calculate_salary.php)
here's my js code so far:
<script language="JavaScript" type="text/javascript">
function getXmlHttpRequestObject() {
return new XMLHttpRequest();
}
var receiveReq = getXmlHttpRequestObject();
function sayHello() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
var start_date = $("#start_date").val();
var end_date = $("#end_date").val();
receiveReq.open("GET", 'calculate_salary.php', true);
receiveReq.onreadystatechange = handleSayHello;
receiveReq.send(null);
}
}
function handleSayHello() {
if (receiveReq.readyState == 4) {
document.getElementById('span_result').innerHTML = receiveReq.responseText;
}
}
</script>
I want to send over the values in start_date and end_date to the calculate_salary.php page
I will use that calculate page to perform some sql statements and return the result back.
How can I create this request?
POST is not an absolute necessity, I'm willing to use other techniques (js, php) to get the job done
thanks
You can use ajax instead
$.ajax({
url:"calculate_salary.php",
type:"POST",
data:{
start_date = $("#start_date").val(),
end_date = $("#end_date").val()
},
success:function(response){
$('#span_result').html(response);
}
});
You can read more about $.ajax and $.post
You have to generate querystring with url like so:
var url = 'calculate_salary.php?start_date='+start_date+'&end_date='+end_date;
receiveReq.open("POST", url, true);
Because you are not sending values that is why you are not receiving values on server side.
Another example you can find here:
How do I pass along variables with XMLHTTPRequest
Also check into this:
http://devzone.co.in/jquery-serialize-function-ajax-post-bigger-html-forms/
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to retrieve some data from my XML file and I want to insert it inside an unordered list. This is how my Ajax code looks like:
var request;
//For backward compatibility
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET','data.xml');
request.onreadystatechange = function(){
// if((request.readyState === 4) && (request.Status===200)){
console.log(request.responseXML);
var items = request.responseXML.getElementByTagName('name');
alert('hello');
var ouptput = '<ul>';
for (var i = 0; i >= items.length; i++) {
output += '<li>' + items[i].firstChild.nodeValue + '</li>';
}
output += '</ul>';
document.getElementById('update').innerHTML = output;
//}
}
request.send();
This code doesn't read my XML file, it gives me an error saying 'Response XML is null(Type error)' I tried to use this in a server(localhost) but it didn't work either.
Can someone please give me an idea how to solve this? Thank you.
i used jQuery to solve this... this is how i did this.....
<script>
$(document).ready(function(){
$(".update").append("<ul></ul>");
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: function(xml){
$(xml).find('book').each(function(){
var sTitle = $(this).find('title').text();
var sprice = $(this).find('price').text();
$("<li></li>").html(sTitle + ", " + sprice).appendTo(".update ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to find some source code which can auto refresh every 30 second on my div tag. I think there is only javascript can be done. I am confusing how to do it. Can anyone tell me what can I do?
this is my php code :
<?php $sql = $getUser->getuser();
if ($rs = $db->Execute($stmt)) {
$arrResult = array();
while($rsa = $rs->FetchRow()) {
array_push($arrResult, array("username" => $rsa['username'] ));
}
}
?>
and this is my div tag in my html which will display online user
<body onload="timer = setTimeout('auto_reload()',10000);">
<{section name=thisrsa loop=$rsa max=$max}>
<div>
<td><{$rsa[thisrsa].username}></td>
</div>
<{/section}>
and it will display like this at one of the site in html page:
-----------
|jimmy |
|Anderson |
|simon |
|vincent |
-----------
this is what i use to control my div
<script>
var timer = null;
function auto_reload()
{
window.location = 'http://domain.com/page.php';
}
</script>
i do not know this sample code will run properly inside your project or not. but if you do not feel trouble. if you have free time you can try this code.
<html>
<body>
<script type="text/javascript">
function Ajax(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari
}catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("No AJAX!?");
return false;
}
}
}
xmlHttp.onreadystatechange=function(){
document.getElementById('ReloadThis').innerHTML=xmlHttp.responseText;
setTimeout('Ajax()',2000);
}
xmlHttp.open("GET","text.txt",true);
xmlHttp.send(null);
}
window.onload=function(){
setTimeout('Ajax()',2000);
}
</script>
<div id="ReloadThis">Default text</div>
</body>
</html>
since your php code to get data is on the same page you got to refresh the page in every 30 seconds to get the latest data which can be done this way:
window.setInterval(function(){window.location = window.location.href},30000);
if your php code to retrieve data was in next page you could simply make ajax request to that page to fetch the updated data and update the div with the new data
window.setInterval(function(){//ajax request //},30000);
One possible solution that implements JQuery/Javascript:
First, create a separate PHP page that will echo/contain ONLY the data you wish to populate the div with.
From your main page you can then use JQuery/Javascript to create a function that will both set the innerhtml of the div as the content of this separate page and refresh the div every 30 seconds by recursively calling itself using setTimeout.
<script>
function reloadData() {
$('#divIDHere').load("separatePage.php");
setTimeout(function() {reloadData(); }, 30000);
}
</script>
To do this you will need to import the JQuery min file into your page. You can download this at 'http://jquery.com/download/'.
You can then import this into your page by including the following HTML:
<script src="jquery-1.10.2.min.js"></script>
Now you have a separate page that echos the data you want into your div and a JQuery/Javascript function that will both set the content of the div to equal the separate page and refresh the div every 30 seconds.
All that is left to do is make the page call the function you have created. This can be done by including the following HTML:
<script>reloadData();</script>
To use this code your php file must echo
<?php $sql = $getUser->getuser();
if ($rs = $db->Execute($stmt)) {
$arrResult = array();
while($rsa = $rs->FetchRow()) {
$output.=$rsa['username']."<br>";
}
echo $output;
}
?>
HTML - Response will be shown in the #logins
<html>
<body>
<script type="text/javascript">
$(document).ready(function(){
Ajax();
setTimeout('Ajax()',30000);
function Ajax(){
$.post("ligin_check.php", { //This whoulb be youe php file
})
.done(function(data) {
$("#logins").html(data);
}).fail(function() {
("#logins").html( "error" );
});
}
});
</script>
<div id="logins">Waiting...</div>
</body>
</html>