I have my page which loads live stock data from server continuously (every second) making request to a php file named data.php. Also I have a Ganns square of 9 calculator that passes value to a PHP file (getdata.php) using ajax through a OnKeyUp function of a textbox and returns some output.
The issue is-
As the page loads both work perfectly. Live data as well as calculator can be used. But after a while the calculator doesn't work. On writing value into the textbox the request must be processed and value must be returned through ajax call, but it doesn't happen.
Live Stock data code (refreshes every sec):
<script>
function showPort(t)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("portfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data.php",true);
xmlhttp.send();
setTimeout(showPort,t);
}
</script>
It runs using on page load-
<body onload="JavaScript:showPort(2000);">
Ganns square calculator code which runs onkeyup event of textbox:
<script>
function showData(str)
{
if (str.length==0)
{
document.getElementById("txtData").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtData").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getdata.php?a="+str,false);
xmlhttp.send();
}
</script>
Runs onKeyUp event of textbox-
<input type="text" placeholder="Last traded Price" name="str" onKeyUp="showData(this.value)">
I tried searching for similar questions but did not get my answer. Thus, posting this issue as a new question here.
The first script:
function showPort(t)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("portfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data.php",true);
xmlhttp.send();
setTimeout(showPort,t);
}
Can be converted this way:
$(document).ready(function(){
setInterval(function(){
$.get("data.php", function(data){
$("#portfo").html(data);
});
}, 2000);
});
And the next one:
function showData(str)
{
if (str.length==0)
{
document.getElementById("txtData").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtData").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getdata.php?a="+str,false);
xmlhttp.send();
}
Can be rewritten as:
function showData(str)
{
if (str.length==0)
{
$("#txtData").html("");
return;
}
$.get("getdata.php?a="+str, function(data){
$("#txtData").html(data);
});
}
Can you please try executing the above code and see if it works? Don't forget to include jQuery this way:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
Related
Hey guys am new to ajax I have a php file and a ajax file. I just want to detect the php file from the ajax so I have send a request in ajax like
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
} else {
console.log('file not fetched');
}
xmlhttp.open("GET","first.php?m=babe",true);
xmlhttp.send();
}
}
loadXMLDoc();
</script>
</head>
<body>
</body>
</html>
My php file
<?php
include("ajax.html");
$p = $_REQUEST['m'];
if($p == 'babe') {
echo true;
}
When I run the ajax.html on localhost it doesn't show me any message in the window nor in the console.
Can you guys tell me why is it like this?
Thanx for the help
Some of your brackets were wrong:
function loadXMLDoc(){
var xmlhttp;
if(window.XMLHttpRequest){ // This bracket was missing
xmlhttp=new XMLHttpRequest();
}
else{ // This bracket was missing
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
}
else{
console.log('file not fetched');
}
} // This bracket was on the wrong place (it enclosed the .open() and .send())
xmlhttp.open("GET","first.php?m=babe",true);
xmlhttp.send();
}
loadXMLDoc();
Also, a simpler way of defining the callback function is:
xmlhttp.onload=function(){
if(xmlhttp.status==200){
alert(xmlhttp.responseText);
}
else{
console.log('file not fetched');
}
}
So I'm trying to build a pretty simple website, to learn basic webdesign. It's just a random quote generator - you click on a button and it prints some famous quote. Anyway, I try to use ajax to get the quote, so I use this function:
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
but no matter what I type into RandomQuote.php, even if it's something like :
<?php
echo 'Hello, world';
?>
nothing shows up in the quote "div', it just becomes blank. I really have no idea what's the problem here. Thanks for the help!
Well, I'm not sure about much, but are you calling your function? You put your ajax inside loadXMLDoc() , so you probably have to call it. Another way is to put your ajax into an addEventListener so when a user clicks on something, it'll execute. If that's not the problem, try making sure your element in your html page with the id of "quote" is spelled correctly. Sometimes the latter scenario is always the problem for me.
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
console.log( "Load was performed." );
});
Don't forget to include jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
This is my ajax function, try to use it:
/**
* #function ajax Send ajax-request with post
* #param {string} xmlpage Target url
* #param {string} data Post parameters (like param1=val1¶m2=val2...)
* #param {Function} callback
* #return {null}
*/
function ajax(xmlpage, data, callback)
{
var xmlh = null;
if(window.XMLHttpRequest)
xmlh = new XMLHttpRequest();
else
try
{
xmlh = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ex)
{
xmlh = new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlh)
{
xmlh.open("post", xmlpage, true);
xmlh.onreadystatechange = function(x)
{
if(xmlh.readyState==4 && typeof callback !== 'undefined')
callback(xmlh.responseText);
}
xmlh.setRequestHeader("Accept-Language","ru, en");
xmlh.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlh.send(data);
}
}
Following test files using your code from the question. It is working perfectly. Either you are missing something or its a browser issue. I tested on Mozilla. To be sure of browser independent code use jQuery for Ajax call
test.html
<html>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>
RandomQuote.php
<?php
echo 'hi';
Update: jQuery version
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function loadXMLDoc()
{
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
});
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>
I'm trying to have some data send to submit.php. The data does submit but it redirects me to the submit.php page. How can I submit this with out changing page?
JS
function submitq() {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("submitdata").value=xmlhttp.responseText;
}
}
xmlhttp.open("POST",submit.php,true);
xmlhttp.send();
}
Just figured it out.
The form can't have an action of a method because that will redirect it after it is posted.
got this file 'functions.php':
<?php
function test ($url){
$starttime = microtime(true);
$valid = #fsockopen($url, 80, $errno, $errstr, 30);
$stoptime = microtime(true);
echo (round(($stoptime-$starttime)*1000)).' ms.';
if (!$valid) {
echo "Status - Failure";
} else {
echo "Status - Success";
}
}
test('google.com');
?>
I want to run it every 10seconds or so, i was told to use ajax request but i dont completely understand how it works. I tried creating a new file 'index.php', and then had this written in it:
<script>
var milliSeconds = 10000;
setInterval( function() {
//Ajax request, i dont know how to write it
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();
}, milliSeconds);
</script>
I put both files into ftp but nothing happens, can someone help me write a propper ajax request?
Edit: eddited typo, still doesnt work tho
var milliSeconds = 1000;
setInterval( function() {
var xmlhttp;
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log ( xmlhttp.responseText );
}
}
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();
}, milliSeconds);
You have to load xmlhttp request object according to the browser ( xmlhttp=new XMLHttpRequest(); ), then set an event handler when the xmlhttp state changes ( xmlhttp.onreadystatechange=function() ). When it changes check if the status is 200 (success) then do whatever you want with the response. ( I printed it to console )
So, it sounds like your only problem is that you don't know how to write an XHR request. Take a look at Using XMLHttpRequest. Comment on this answer with your questions.
xmlhttp.open("POST","funkction.php",true);
should be:
xmlhttp.open("POST","functions.php",true);
How can JSON be used to parse xmlhttp.responseText? I can't seem to get textboxes populated using the parsed data. I tried using .value and .innerHTML with the dot notation with b.first and b.second used with json_encode from the loadTextBox.php file (see below), but the textboxes won't populate.
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
//code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var doc = window.document.createElement("doc");
var a = xmlhttp.responseText;
var b = JSON.parse(a);
document.getElementById("textbox").innerHTML=b.first;
document.getElementById("textbox2").innerHTML=b.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
---Placeholder for correct DB login info---
$result = $mysql->query("SELECT column_one FROM table_one");
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>
This is fully tested and works. Use as a starting point to accomplish what you are trying to do:
var url = "YOUR.php"
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.send(null);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && (ajax.status == 200)) {
console.log("ready")
var Data = JSON.parse(ajax.responseText);
console.log(Data);
console.log(Data.first);
} else {
console.log("not ready yet")
}
}
This assumes your JSON output is properly formatted as you stated:
{"first":"radim","second":"radi"}
I have figured out the underlying problem. Extra tags were being sent because I had unnecessary tags in my DB info file. Those tags were being sent in the responseText with {"first":"radim","second":"radi"}. So the code pertaining to ---Placeholder for correct DB login info--- was wrong. I also changed .innerHTML to .value and now it works as intended.
Main page code updated:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").value=a.first;
document.getElementById("textbox2").value=a.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}