PHP Validation Button - php

I would like to have on my HTML page a simple button allowing me if right clicked one, click activate every time my PHP script.
I tried with this code, without any positive result for the moment:
//My html code
<!DOCTYPE html>
<head>
<title><?php echo $pageTitle; ?></title>
<meta charset="UTF-16" />
<link rel="stylesheet" type="text/css" media="all" href="css.css">
<style></style>
</head>
<body>
<main>
<button onclick="doTheFunction();">Run the script</button>
<script>
function doTheFunction(){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","script.php",true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
}
}
</script>
</main>
<footer>
<?php echo $footer; ?>
</footer>
</body>
A part of my php code :
echo "$result";

Your code is doing nothing with the result of Ajax. I suggest starting here as a reference. The most important thing you're missing is:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
Where "demo" is the Id of the element you want to load the Ajax result into. Otherwise nothing will happen with that result.
EDIT
Let's clean up your code so scripts and html are separate:
function doTheFunction(){
xmlhttp = new XMLHttpRequest();
//Set this before sending!!
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
}
//No reason to post
xmlhttp.open("GET","theme/generator/gensent.php",true);
xmlhttp.send();
}
<head>
<title><?php echo $pageTitle; ?></title>
<meta charset="UTF-16" />
<link rel="stylesheet" type="text/css" media="all" href="css.css">
<style></style>
</head>
<body>
<main id="demo">
<button onclick="doTheFunction();">Run the script</button>
</main>
<footer>
<?php echo $footer; ?>
</footer>
</body>
I would put the <script> tag at the end of your html, after closing the body, or include it in the header from another file. Note- I use GET since no sensitive info is transferred, the script should load after the HTML- hence put at the end, and finally you need a tag with the Id for this to actually work.

Related

continuos ajax request gives error net::ERR_EMPTY_RESPONSE

steps to reproduce the error
open http://www.blackboardjournals.com/test2.php
click on the next button continuously for 30-40 times
the counter stops after a certain count
the console shows an error net::ERR_EMPTY_RESPONSE
if you refresh immediately after the counter stops, the site becomes unresponsive
I am not able to understand why this error is occurring. can somebody help me understand what is wrong?
My code:
<?php
if(isset($_POST['btn_num'])){
$btn_name=$_POST['btn_num'];
echo $btn_name+1;
exit();
};
?>
<script type="text/javascript">
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function call_next(){
var new_ans=$('.number').html();
var ajax =ajaxObj("POST",'test2.php');
ajax.onreadystatechange=function(){
if(ajaxReturn(ajax)==true){
$('.number').html(ajax.responseText);
}
}
ajax.send('btn_num='+new_ans);
}
</script>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="/pwa/js/jquery.js" ></script>
</head>
<body>
<div class="number">1</div>
<button onclick="call_next();">next</button>
</body>
</html>

Select data and display on same page without loading (php/ajax)

I am getting user data by passing the id in url and using the select statement where it matches the id in url and display result
But I want this by using ajax. Please help me
<div id="show_data">
<?php
$id=$_GET['id'];
$category=$_GET['category'];
if ($category==Hosted) {
$result = $wpdb->get_results ("SELECT * FROM wp_user_host WHERE user_id=$id");
foreach ( $result as $print ){
?>
<table>
<tr>
<td>Name: <?php echo $print->drive_name;?</td>
<td>Date: <?php echo $print->drive_date;?</td>
</tr>
</table>
<?php
}
}
?>
</div>
<a href="page.php?id=2&category=Hosted:>VIEW DATA</a>
lets say i have an index file like follow
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
<button id="testDom">click to load dom</button>
<p id="domOutput"></p>
<script>
document.getElementById("testDom").addEventListener('click', function(){
loadAjax();
});
function loadAjax(){
var xmlHttp = new XMLHttpRequest();
var requestUrl = 'test.php';
xmlHttp.onreadystatechange = function(){
if( this.readyState == 4 && ( this.status > 200 || this.status < 300 ) ){
console.log("ok");
document.getElementById("domOutput").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open('GET', requestUrl);
xmlHttp.send();
}
</script>
</body>
lets say if u click the button ajax call made to the php file called test.php
<?php
echo "php file loaded";
ouput will printed in the index.html on p tag.

PHP AJAX Update Not Working

The Idea
User will select examination date from dropdown list which is populated with data from the database.
After selecting the date, the system will display the list of examiners based on the selected date.
The user can now encode grades per student.
After encoding the grade, the user will click the 'save' button which the system will save to the database. (Multiple update)
This is the code where the user selects the exam date.
<?php
include '../configuration.php';
$queryselect = mysql_query("SELECT examdateno, examdate from tbl_examdate ORDER BY examdate DESC");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SPORT Qualifying Exam System</title>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="../css/component.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "encodeinterviewajax.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<header>
<img src="../images/qes_logob.png" alt="logo">
<button class="hamburger">☰</button>
<button class="cross">˟</button>
</header>
<div class="menu">
<ul>
<a href="encodeinterview.php">
<li>Encode Grades</li>
</a>
<a href="viewinterview.php">
<li>View Grades</li>
</a>
<a href="../index.php">
<li>Logout</li>
</a>
</ul>
</div>
<script>
$(".cross").hide();
$(".menu").hide();
$(".hamburger").click(function () {
$(".menu").slideToggle("slow", function () {
$(".hamburger").hide();
$(".cross").show();
});
});
$(".cross").click(function () {
$(".menu").slideToggle("slow", function () {
$(".cross").hide();
$(".hamburger").show();
});
});
</script>
<div id="content">
<form>
<h1>Exam Dates</>
<select name="examdate" id="examDate" onchange="showUser(this.value)">
<option>Select Exam Date</option>
<?php
while ($row = mysql_fetch_array($queryselect)) {
echo "<option value={$row['examdateno']}>{$row['examdate']}</option>\n";
}
?>
</select>
</form>
</div>
<div id="txtHint">Examinees will be listed here</div>
</body>
</html>
This is where the displaying and the update should happen.
<?php
include '../configuration.php';
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/component.css" />
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="../css/grid.css">
</head>
<body>
<?php
$q = intval($_GET['q']);
$sql = mysql_query("select s.sno, s.fname, s.lname, s.examdate, s.interviewgrade, s.gwa from student s inner join tbl_examdate e on s.examdate=e.examdate where e.examdateno=$q");
?>
<div class="as_wrapper">
<div class="as_grid_container">
<div class="as_gridder" id="as_gridder"></div> <!-- GRID LOADER -->
<form method="post" action="">
<table class="as_gridder_table">
<tr class="grid_header">
<td><div class="grid_heading">Student No.</div></td>
<td><div class="grid_heading">First Name</div></td>
<td><div class="grid_heading">Last Name</div></td>
<td><div class="grid_heading">Exam Date</div></td>
<td><div class="grid_heading">Interview Grade</div></td>
<td><div class="grid_heading">GWA</div></td>
</tr>
<?php
while ($row = mysql_fetch_array($sql)) {
?>
<tr class="<?php
$i+=1;
if ($i % 2 == 0) {
echo 'even';
} else {
echo 'odd';
}
?>">
<td><?php $sno[]=$row['sno'];echo $row['sno']; ?></td>
<td><?php $fname[]=$row['fname']; echo $row['fname']; ?></td>
<td><?php $lname[]=$row['lname'];echo $row['lname']; ?></td>
<td><?php echo $row['examdate']; ?></td>
<td><input type="text" size="3" maxlength="3" name="interview[]"></td>
<td><input type="text" size="3" maxlength="3" name="gwa[]"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="6"><button id="btnUpdate">Save</button>
</tr>
</table>
</form>
<?php
if (isset($_POST['btnUpdate'])){
for($i=0;$i<sizeof($sno);$i++){
$interview = $_POST['interview'][$i];
$gwa = $_POST['gwa'][$i];
$sql1= mysql_query("UPDATE student SET gwa='$gwa', interviewgrade='$interview' where fname='$fname[$i]' AND lname='$lname[$i]' ");
header('Location: encodeinterview.php');
}
}
?>
</div>
</div>
</body>
As I mentioned in my comment I'm not sure what exactly is not working for you but I can help you with a couple of things in what I'm guessing to be your homework project.
First, always wrap all jQuery actions that affect DOM elements or add EventListeners to DOM elements in a document.ready function. This function is triggered when all the HTML of the page has been loaded to the DOM. Adding an event listener or trying to ".hide()" and element before it is loaded to the DOM will fail. There is the long way of calling the document.ready function:
$(document).ready(function(){
.... Code to manipulate the DOM goes here ...
});
and the shorthand function call that does exactly the same thing:
$(function(){
.... Code to manipulate the DOM goes here ...
});
If you need to wait until all the additional resources (e.g. images) are loaded you can use:
$(window).load(function(){
.... Your code goes here ....
});
This function is triggered when all resources are loaded. So if you're looking to get the position of an element or size of an element that contains images it's best to wait until the images are loaded. otherwise the position or size may well change once the images are loaded.
So your jQuery block needs to wrapped like this:
<script>
$(function(){
$(".cross").hide();
$(".menu").hide();
$(".hamburger").click(function () {
$(".menu").slideToggle("slow", function () {
$(".hamburger").hide();
$(".cross").show();
});
});
$(".cross").click(function () {
$(".menu").slideToggle("slow", function () {
$(".cross").hide();
$(".hamburger").show();
});
});
});
</script>
And for goodness sake if your using jQuery NEVER type 'document.getElementById'. The jQuery equivalent is $('#id'). Note the '#' means ID where the '.' means CLASS. It's much shorter and it creates the element as a jQuery object which allows you to use all of jQuery's wonderful functions on it.
If you're using jQuery anyway. You should use it for AJAX. It's much easier. Here's your same showUser function done with jQuery including error handling for the ajax call:
function showUser(str) {
if (str == "") {
$("#txtHint").html("");
return;
} else {
$.ajax({
url: "encodeinterviewajax.php?q=" + str,
type: 'GET',
success: function(data){
$('#txtHint').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("Status = " + textStatus);
console.log("Error = " + errorThrown);
}
});
}

Unexpected HTML result using List view JQuery

My implementation is at : http://i.cs.hku.hk/~hsbashir/Project_Work/Listview/list_view.html
The first entry is when the list is hardcoded. Second and third ones are when they are extracted from the server using xmlhttp object. I am unable to understand why in the 2nd & 3rd list the formatting is different.
Original HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script>
lastRecord=0;
function loadNews(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var x = document.getElementById("sample");
x.innerHTML = "hello";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var news = document.getElementById("news_mesgs");
news.innerHTML += xmlhttp.responseText;
$("news_mesgs").enhanceWithin();
}
}
xmlhttp.open("GET", "queryNews.php?lastRecord="+lastRecord,true);
xmlhttp.send();
}
</script>
</head>
<body onload="loadNews()">
<div data-role="page" id="pageone">
<div data-role="main" class="ui-content">
<ul data-role="listview" data-inset="true" id="news_mesgs">
<li>
<a href="#">
<img src="http://i.cs.hku.hk/~hsbashir/Project_Work/Listview/suicide-panel.jpg">
<h2> HKU identifies a new strategy to protect flowers from freezing stress </h2>
<p> sample description </p>
</a>
</li>
</ul>
</div>
</div>
<div id="sample"></div>
</body>
</html>
Updated HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script>
lastRecord=0;
function loadNews(){
$('#sample').html( 'hello' );
$.get(
"queryNews.php?lastRecord="+lastRecord,
function( data ) {
$('#news_mesgs').append( data )
.enhanceWithin();
}
);
}
</script>
</head>
<body onload="loadNews()">
<div data-role="page" id="pageone">
<div data-role="main" class="ui-content">
<ul data-role="listview" data-inset="true" id="news_mesgs">
<li>
<a href="#">
<img src="http://i.cs.hku.hk/~hsbashir/Project_Work/Listview/suicide-panel.jpg">
<h2> HKU identifies a new strategy to protect flowers from freezing stress </h2>
<p> sample description </p>
</a>
</li>
</ul>
</div>
</div>
<div id="sample"></div>
</body>
</html>
PHP
<?
...
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$query = "SELECT * FROM News_Info";
$result = mysql_query($query) or die( "Unable to execute query");
while ($row = mysql_fetch_array($result)){
print "<li>";
print "<h2>".$row['Title']."</h2>";
print "<p>sample description is here</p>";
print "</a>";
print "</li>";
}
?>
The second and third are added after the widget has been initialized. You therefore have to re-enhance (refresh) the widget each time you make an update to it. And you can do that using the $(parent_of_new_content).listview('refresh'). In your case you would have to call the following:
$('#news_mesgs').listview( 'refresh' );
Just out of curiosity, is there any particular reason why you're using plain vanilla JS for your ajax call? If you were to use jQuery (recommended) your function would be:
lastRecord=0;
function loadNews(){
$('#sample').html( 'hello' );
$.get(
"queryNews.php?lastRecord="+lastRecord,
function( data ) {
$('#news_mesgs').append( data )
.listview( 'refresh' );
}
);
}
EDIT
Please note that in the above code .enhanceWithin() has been replaced with .listview('refresh')
JS FIDDLE DEMO

My AJAX file does not work

I just make a simple AJAX application so that my html page can get some data from the php file through the ajax.js file, I have already put them in the server, so when I access localhost/mypage, it should be executed, however it seems there are some problems therefore things do not happen as my expected way.
Here is my html file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META http-equiv="Content-Type" Content="text/html; Charset=UTF-8">
<title>
My Portal
</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body onload="load()">
<div id="header">
<img src="images/logo.gif" id="logo" alt="Logo"/>
<a href="http://www.google.com">
<img src="images/logo2.png" id="logo2" align="right" alt="google Ltd"/>
</a>
</div>
<div id="container">
<div id="function"></div>
<div id="Display"></div>
<div id="View"></div>
</div>
<div id="footer">
</div>
</body>
</html>
And below is the js file:
function load(){
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("function").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php", true);
xmlhttp.send();
}
At last is the php file:
<?php
print "<h1>hgfkegfalhgj</h1>";
?>
I expect it should print out the above char string in my page, however, nothing can be shown, can anyone tell me where is the problem? I have checked that I have already enabled javascript in my browser, so I am quite sure my html file can call the function in js file.
I don't know PHP but you must set content type to text/plain . Like :
header('Content-Type: text/plain');
Your code works for me.
The problem can be any of the following:
1) Check the path to test.php (I would suggest using absolute path in xmlhttp.open() )
2) Your server may not be returning the page correctly (Try opening test.php, and check the output)
You can use browser plugins like firebug, to analyze the ajax request and response, it can give you a better insight.
instead of onLoad function in body tag try with
<script>
window.onload = function(){
load();
};
function load(){
//your code
}
</script>
or try with script load() function before body. I think it will solve your problem.
Also Try to change id, preferably keywords should not be used as id (function id change it to something else)

Categories