I'm building a PHP script that sends an email to people on their birthdays. I also need a small web interface where I can turn the entire program on or off, watch who is celebrating his birthday today and see if any mails could not be send. The php on the server is working, but I'm struggling with the html and javascript interface. Specifically the Ajax request that gets the information from the server. it works fine in firefox, chrome and opera, but in Internet Explorer 8 I don't get a response from the server. The readyState switches to 4, but the status remains 0 and the responseText is empty.
After googling I found out that a lot of people advice JQuery, but I couldn't get that to work in any browser. I want to find out more about it, because it seemed pretty easy, but for now I would like to know how to do this without JQuery.
edit
In response to questions from the comments, switching the if and else statements yields the same results. As does changing the connection from 'open' to 'close', incidentally, it is supposed to be close, I can't remember why I changed it, probably just trying something out of frustration. Finally I added the server side php code. The server sends back string data in case 'action' is switchonoff or, just a header with no text if action is clearlog and a jsonarray if action is initialize. Whatever the request the server's HTTP status is always 0.
<script type="text/javascript">
function loadXMLDoc(action) {
var parameters = "action="+encodeURI(action);
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.open("POST",'http://mailer.test/App/postscript.php',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "open");
xmlhttp.send(parameters);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
if(action == 'switchonoff'){
document.getElementById("onoffbutton").innerHTML=xmlhttp.responseText;
} else if(action == 'initialize'){
var response = JSON.parse(xmlhttp.responseText);
document.getElementById("onoffbutton").innerHTML=response['onoff'];
document.getElementById("birthdays").innerHTML=response['birthdays'];
document.getElementById("errors").innerHTML=response['errors'];
} else if(action == 'clearlog'){
document.getElementById("errors").innerHTML="";
}
}
}
}
window.onload = function() {
loadXMLDoc('initialize');
}
</script>
edit, here's the php script
<?php
include "settingschanger.php";
include "customercsv.php";
if (!isset($_POST['action'])) {
$_POST['action'] = 'dummy';
}
$post = $_POST['action'];
if(strcmp($post, "initialize") == 0) {
$settings = new SettingsChanger();
$onoff = $settings->getOnOff();
$csv = new CustomerCSV();
$csv->openFile((__DIR__).CustomerCSV::FILENAME);
$todaysbirthdays = $csv->getTodaysBirthdays();
$birthdays = "";
foreach ($todaysbirthdays as $row) {
$birthday = "";
foreach ($row as $data) {
$birthday .= $data . " ";
}
$birthdays .= $birthday . "<br />";
}
$errorLogArray = $settings->getErrorLog();
$errors = "";
foreach($errorLogArray as $line) {
$errors .= $line . "<br />";
}
$result = json_encode(array('onoff'=>$onoff, 'birthdays'=>$birthdays, 'errors'=>$errors));
header("HTTP/1.1 200 OK");
print $result;
}
if(strcmp($post, "switchonoff") == 0) {
$settings = new SettingsChanger();
$result = $settings->changeOnOff();
header("HTTP/1.1 200 OK");
print $result;
}
if(strcmp($post, "clearlog") == 0) {
$settings = new SettingsChanger();
$settings->clearLog();
header("HTTP/1.1 200 OK");
}
?>
Try with xmlhttp.send(parameters); after xmlhttp.onreadystatechange statement.
I had some issues with the returned content being empty in older versions of IE ( less than v9), but the success-function was triggered.
Then I found out that I was using HTML5 tags, and in IE, for some odd reason, HTML5 output via an AJAX-request doesn't work and returns an empty or no DOM.
Look at the last edit in "jquery .load() not inserting data in ie8 and below".
Well, I got the site to work. Instead of a post request I now use a get request and that seems to work. It's not perfect and I'll continue looking for a way to do it with a post request, but for now it'll work.
Related
so I get the feed after choosing an option but its not "refreshing as new news come".
I have the same problem with openweather.
Is the "GET" my problem or browser or something else? I guess everything is cached but it should not.
Should it be POST and not GET how sould I change that with the current code?
thanks!
<script>
nocache = "&nocache" + Math.random()* 1000000
url = "$q"
out = "";
function showRSS(str) {
if (str.length==0) {
document.getElementById("rssOutput").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("rssOutput").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getrss.php?q="+str+nocache,true);
xmlhttp.send();
}
</script>
<?php
//get the q parameter from URL
$q = $_GET["q"];
//find out which feed was selected
if($q=="Baden-Württemberg") {
$xml=("https://verkehrsmeldungen.polizei-bw.de/TicRss.ashx?region=BW");
} elseif($q=="Bayern") {
$xml=("http://www.br.de/verkehr-static/verkehrsmeldungen-rss.xml");
}
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
//output elements from "<channel>"
echo("<p ><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br>");
echo($channel_desc . "</p>");
//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=5; $i++) {
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p ><a href='" . $item_link
. "'>" . $item_title . "</a>");
echo ("<br>");
echo ($item_desc . "</p>");
}
?>
From what you are saying or trying to accomplish, is to either use
polling
event or socket connection (socket.io)
Now with Polling, you set a particular interval to always go and check for new updates. This path is not too efficient as you might go to the server to retrieve new information and there might be none returned as at the time you sent the request.
Sample
var interval = 3000// milliseconds
function fetchFeeds(){
setTimeout(function(){
// goto the server here and manage returned record
}, interval);
}
For Events: you can check up on server side events here but for only HTML5, but nice stuff.
Will advise to go for socket instead, check socket.io
I have a HTML page JavaScript which send a GET request data to PHP file to return all datas saved in the database . PHP replies with a HTML-table - that works fine!
But: When if i click a button (which calls the same JavaScript function) to update my table in order to display the new data, i get the same result (and i have definitely new data on table).
If I call the PHP manually via the browser it'll show me the new results immediately and at this moment it is also working with JavaScript (but only once).
Here is a part of my code.
HTML/JS:
<button onclick="GetData()"></button>
<div id="test"></div>
<script>
function GetData(){
var xhttp = new XMLHttpRequest();
document.getElementById("test").innerHTML = "";
xhttp.onreadystatechange = function(){
if (xhttp.readyState == 4 && xhttp.status == 200){
document.getElementById("test").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "../GetData.php", true);
xhttp.send();
}
</script>
PHP:
//DB details
$dbHost = 'localhost';
$dbUsername = 'lalalala';
$dbPassword = 'lalalalal';
$dbName = 'lalalala';
//Create connection and select DB
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName) or die ("UUUUPS");
$sql = "select name, beschreibung, image, video from data";
$result = $db->query($sql);
if ($result->num_rows > 0) {
$return = '<table class ="table table-hover"><thead><tr><th scope="col">Name</th><th scope="col">Beschreibung</th><th scope="col">Bilddatei</th><th scope="col">Video-Url</th></tr></thead><tbody>';
// output data of each row
while($row = $result->fetch_assoc()) {
$return .= "<tr><td>".$row["name"]."</td><td>".$row["beschreibung"]."</td><td><img src=data:image/png;base64,".base64_encode($row["image"])."/></td><td>".$row["video"]."</tr>";
}
$return .= "</tbody></table>";
$db->close();
echo $return;
} else {
echo "0 results";
}
Thank you for your help!
It seems your browser is caching your result, that's why you see data.
You can test it like this:
var random = Math.floor(Math.random() * 100);
xhttp.open("GET", "../GetData.php?"+random, true);
If this helps, look into expire headers in your PHP script. Also, the way you're doing queries in quite outdated. It's a very PHP4 way. Have a look here: http://php.net/manual/en/book.mysqli.php
I guess you probably know this, but just in case. Have you had a look in your browsers inspector, when testing you html page? especially the network tab within that inspector. There you can see the actual response from the server and you can see if it is served from cache or fetched (you can even disable cache there), maybe this helps.
Kind regard,
Mark
i have a php script that takes some moments to execute. And it does multiple "echos" as the progress is going.
This script connects to ftp, deletes all contents and then upload new files. All is working fine and i'm getting the result but only when the script ends.
My output looks like this:
Deleting /var/www/index.php ... ok
Deleting /var/www/tempo.php ... ok
Deleting /var/www/indexOLD.php ... ok
//many lines here ...
//...
//...
Done!
Uploading /var/www/index.php ... ok
Uploading /var/www/tempo.php ... ok
Uploading /var/www/indexOLD.php ... ok
//many lines here ...
//...
//...
Done!
This is my client side code:
function atualizar(id) {
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() {
document.getElementById("estado").value = xmlhttp.responseText;
};
xmlhttp.open("GET","atualizarBOX.php?id="+id,true);
xmlhttp.send();
}
And here is my serverside php piece of code:
function ftp_putAll($conn_id, $src_dir, $dst_dir) {
$d = dir($src_dir);
while($file = $d->read()) { // do this for each file in the directory
if ($file != "." && $file != "..") { // to prevent an infinite loop
if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
if (!#ftp_chdir($conn_id, $dst_dir."/".$file)) {
ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
}
ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
} else {
ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
print "Uploading ".$src_dir."/".$file. " ... OK \n";
}
}
}
$d->close();
}
I already tried to use ob_flush(); flush(); but it ist working.
Also i already changed this values
In php.ini:
. output_buffering = Off
. zlib.output_compression = Off
All i want is to get "echo" one by one as the progress is going...
Something like this:
Deleting /var/www/index.php ... ok
//now user waits a couple of seconds
Deleting /var/www/index.php ... ok
Quick google search reveals that a common way of solving this is called 'comet programming technique'
Here is a quick PHP example (Source)
Stealing server side code from above link and pasting here:
<?php
/**
Ajax Streaming without polling
*/
//type octet-stream. make sure apache does not gzip this type, else it would get buffered
header('Content-Type: text/octet-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
/**
Send a partial message
*/
function send_message($id, $message, $progress)
{
$d = array('message' => $message , 'progress' => $progress);
echo json_encode($d) . PHP_EOL;
//PUSH THE data out by all FORCE POSSIBLE
ob_flush();
flush();
}
$serverTime = time();
//LONG RUNNING TASK
for($i = 0; $i < 10; $i++)
{
//Hard work!!
sleep(1);
//send status message
$p = ($i+1)*10; //Progress
send_message($serverTime, $p . '% complete. server time: ' . date("h:i:s", time()) , $p);
}
sleep(1);
send_message($serverTime, 'COMPLETE');
Looks like you just need to add the appropriate headers..
I have written following script on server-
<?php
//Create an array
$json_response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$status = "In Progress";
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$con)
{
die('Could not connect to database: ' . mysql_error());
}
//Query to select pending queries database
$result = mysqli_query($con, "SELECT * FROM tbl_query_master WHERE status='".$status."' ORDER BY query_date DESC");
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row_array['query_id'] = $row['query_id'];
$row_array['sender_mobile_no'] = $row['sender_mobile_no'];
$row_array['sender_name'] = $row['sender_name'];
$row_array['query_string'] = $row['query_string'];
$row_array['action_taken'] = $row['action_taken'];
$row_array['status'] = $row['status'];
$row_array['query_date'] = $row['query_date'];
$row_array['action_date'] = $row['action_date'];
$row_array['view_status'] = $row['view_status'];
$row_array['read_status'] = $row['read_status'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
?>
Above script returns one JSON object which is useful for me in JavaScript section of my JSP page, but I don't know how to call php-script from the java script section, so need your guidance for the same. Hope you understand what I'm saying Thank you..!
Suppose your php script is deployed to a web server (apache with php mod) and is triggered by some URL, e.g. http://localhost/script.php
Then in your javascript you can do POSt request using jquery:
$.getJSON('http://localhost/script.php', function(json) {
// do what you need with your json data
});
Finally I solved it using AJAX as follows, I don't know whether performance wise this method is correct or not, but perfectly worked for me. Write the following code in your JavaScript section.
var xmlHttp;
//FUNCTION TO CREATE BROWSER COMPATIBLE OBJECT.
function createBrowserObject()
{
if (typeof XMLHttpRequest != "undefined") //Object for Netscape 5+, Firefox, Opera, Safari,and Internet Explorer 7
{
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) //Version for Internet Explorer 5 and 6.
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) //Fails on older and nonstandard browsers
{
alert("Browser does not support XMLHTTP Request");
}
}
function getDataChange()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") //Check whether server response came back with no errors.
{
//THE RESPONSE FROM SERVER. DO YOUR STUFF WITH xmlHttp.responseText
alert("Responce= "+xmlHttp.responseText);
//document.getElementById("cart_div").innerHTML = xmlHttp.responseText;
}
}
function getData()
{
createBrowserObject();//CREATE BROWSER COMPATIBLE OBJECT.//
var url = "http://yourdomain.com/your_script.php"; // URL of server-side resource.
// Using following way you can send parameter to your script.
//url += "?param1=" + param1 + "¶m2=" + param2;
xmlHttp.onreadystatechange =getDataChange; //ASSIGN RESPONSE HANDLER FUNCTION NAME TO ONREADYSTATECHANGE//
xmlHttp.open("GET", url, true); //INITIATE GET or POST REQUEST. (Here GET)
xmlHttp.send(null); // SEND DATA. (Always null in case of GET.)
}
And finally create event to call "getData()" function. That's it. Thank you..!
I have AJAX code here that pass multiple values to PHP. But the problem is that the PHP can't get the value pass by AJAX and nothing is added on the database. However in my submit button I have an onclick event that calls addAnnouncement() and I think it is working because I put an alert in my ajax code and everytime I click that button it says OK.
So I think the part of the problem is in the passing of the variables.
What do you think is the problem in my code?
AJAX CODE:
function addAnnouncement()
{
var subject = document.getElementById("subject").value;
var name = document.getElementById("name").value;
var announcement = document.getElementById("announcement").value;
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)
{
if(xmlhttp.status==200){
alert("OK");
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
}
var variables = "subject=SAMPLE&name=HARVEY&announcement=HELLO";
xmlhttp.open("POST", "addAnnouncement.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(variables);
return false;
}
This is the PHP code that gets the values pass by AJAX.
PHP CODE:
<?php
require_once("config.php");
$subject = $_POST['subject'];
$name = $_POST['name'];
$text = $_POST['announcement'];
$dateTimeNow = date("Y-m-d H:i:s");
$query = "INSERT INTO table_announcement(subject, name, text, dateTimePosted)".
"VALUES('$subject', '$name' , '$text', '$dateTimeNow')";
$data = mysql_query($query)or die(mysql_error());
if($data){
echo "ADDED!";
}
else{
echo "ERROR!";
}
?>
Just return false when exiting from the event handler to prevent the default behaviour of the submit button (i.e. submit the form):
function addAnnouncement() {
// …
return false;
}
Also check the status of your XMLHttpRequest when it reaches readyState 4 (it might be something different then 200) and properly encode query string parameters with encodeURIComponent. Last, but not least, your code is open to SQL injection. Fix that by using prepared statements (available in MySQLi and PDO. If you can't decide which, this article will help you. If you pick PDO, here is a good tutorial).