why readyState is NOT equal to 4? - javascript

I have tried to learn how to receive data from database using ajax, and i have some problem...
the problem is when I submit the query I dont see any thing...
i know that the problem is because the readyState is NOT equal to 4...but why?
I have this code on the index.html file:
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option>m</option>
<option>f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
and this code on the ajax-example.php file:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "*************";
$dbname = "*************";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "SELECT * FROM ajax_example WHERE ae_sex = '$sex'";
if(is_numeric($age))
$query .= " AND ae_age <= $age";
if(is_numeric($wpm))
$query .= " AND ae_wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr>";
$display_string .= "<td>$row[ae_name]</td>";
$display_string .= "<td>$row[ae_age]</td>";
$display_string .= "<td>$row[ae_sex]</td>";
$display_string .= "<td>$row[ae_wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

The order of operations must be:
Create AJAX object
Open a connection
Set readystatechange handler
Send request.
You have items 2 and 3 in the wrong order, so the event handler is being cleared and is never called.
EDIT: It should also be noted that new XMLHttpRequest has been fully cross-browser since 2007, with the release of IE7. You don't need to use those ActiveXObjects now.

It looks like one of two things:
localhost is being used as the domain; it should be 127.0.0.1
ajax-example.php is running on localhost, but the associated HTML file is not

var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
you should use double and(&&)
try it
var queryString = "?age=" + age + "&&wpm=" + wpm + "&&sex=" + sex;

Related

Run AJAX PHP example in NetBeans

I found what looks like a decent introductory tutorial on AJAX using PHP and MYSQL and followed it to the letter - this is my first attempt at AJAX and PHP and I wish to run this in NetBeans but don't know how to get it running. How do I make this run in NetBeans? I have set the main file to ajax.html and attempted to run using the Green arrow but when the HTML page appears it does nothing when I enter valid data and click the "Query MySQL" button
Here us the ajax.html file
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
// Browser support code
function ajaxFunction(){
var ajaxRequest; // the variable that makes AJAX possible
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch(e){
// internet explorer browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
// something wrong in creating XMLHttpRequest
alert("Browser didn't create XMLHttpRequest");
return false;
}
}
}
// Now get the value from user and pass it to
// server script
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age;
queryString += "&wpm=" + wpm +"&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
// -->
</script>
<form name='myForm'>
<br />
Max Age: <input type='text' id='age' /> <br />
<br />
Max WPM: <input type='text' id='wpm' />
<br />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onClick='ajaxFunction()' value='Query MySQL' />
</form>
<div id='ajaxDiv'>Your result will be displayed here</div>
</body>
</html>
Here is the ajax-example.php file. The MySQL on my machine appears to be "localhost3306" and using the port number 7777
<?php
$dbhost = "localhost3306:7777";
$dbuser = "root";
$dbpass = "password";
$dbname = "web_prof_tracker";
// Connect to MySQL server
mysql_connect($dbhost, $dbuser, $dbpass);
// Select database
mysql_select_db($dbname) or die(mysql_error);
// Retrieve the data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape user input to help prevent SQL injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
// Build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
$query .= " AND age <= $age";
if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";
// Execute query
$qry_result = mysql_query($query) or die (mysql_error());
// Build result string
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($sql_result)){
$display_string = "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>
On the officially net beans website netbeans.org they do show a tutorial on how to run php projects using netbeans
This are the steps,
I will skip the configuration of php environment as you have mentioned that you do have apache and you used to run php projects.
On your netbeans this is what you need to do :
Start the IDE, switch to the Projects window, and choose File > New
Project. The Choose Project panel opens.
In the Categories list, choose PHP.
In the Projects area, choose PHP Application and click Next. The New
PHP Project > Name and Location panel opens.
Make sure your source folder is inside htdocs in your xampp.
Then click next and select Run As a local website then specify the project url
Then you have done your setup configuration
you need to then open the projects files then when you done choose run from the menu
Then your project will display on your default netbeans projects browser.
Hope this will help, Good luck
Source : https://netbeans.org/kb/docs/php/quickstart.html

Output of drop down list in php mysql

I want the output of "cor_resp_template" where is nome and select that values for in next page do some operations like(sum, multiplication,...). I try the first time use JavaScript, but i don´t know if the code is correct. I try to analysis step by step and seems ok for that operation.
In next picture like you see the empty values. Don´t show the table with the values for after submit that values for next page.
The output of database of the table template where is all the values:
That is the output of that page:
http://localhost/dissertacao/conceptualization13.php?menuId=1
After we have the code where we use the JavaScript for get the values in next page where is the PHP query.
<script>
function showUser(str) {
if (str == "") {
document.getElementById("$option").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 (this.readyState == 4 && this.status == 200) {
document.getElementById("$option").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","template1.php?option="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<?php
echo "<select name='template' class='form-control' onchange='showUser(this.value)'>";
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
echo "<center>";
// Get the county names from database - no duplicates
$query = "SELECT DISTINCT nome FROM template";
{
// execute the query, $result will hold all of the Counties in an array
$resultado = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($resultado))
$option .="<option>" . $row['nome'] . "</option>";
echo $option;
}
echo "</select>";
echo "<br>";
?>
<input type="submit" value="Submit">
</form>
<br>
<div id="valores"><b>Os valores para este template são:</b></div>
template1.php
The following code is the PHP QUERY where is called for give the output of the table with the values where is nome in the SQL table.
<?php
$option = (isset($_POST['nome']) ? $_POST['nome'] : '');
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
$query="SELECT * FROM template WHERE 'nome' = '".$option."'";
$resultado = mysql_query($query) or die(mysql_error());
echo "<table>
<tr>
<th>Valores</th>
</tr>";
while($row = mysql_fetch_array($resultado)) {
var_dump ($resultado);
echo "<tr>";
echo "<td>" . $row['corp_resp_template'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>**

Sending data back from php

I tried this tutorial to send/retrieve data from my mysql database, using ajax and php.
This is the ajax part:
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").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 (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","suchen_ma.php?id="+str,true);
xmlhttp.send();
}
</script>
The .php file looks like this:
<?php
//Connection Details
$username = 'root';
$password = '';
$hostname = 'localhost';
$databasename = 'plzdb';
$id = ($_GET['id']);
//Connection-string
$con = mysqli_connect($hostname,$username,$password,$databasename);
//SQL Query
$sql = "SELECT per_vorname,per_nachname from plz_person
WHERE per_id = $id";
$result = mysqli_query($con,$sql);
echo "<table border='0'>
<tr>
<th></th>
<th></th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['per_vorname'] . "</td>";
echo "<td>" . $row['per_nachname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The data is formatted within the php file, but I want to send the "raw" data back to the html and display it inside a list and format it with css. Unfortunately I have no idea how to do this
Just give back the data as JSON:
$sql = "SELECT per_vorname,per_nachname from plz_person
WHERE per_id = " . mysqli_real_escape_string($con, $id);
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
$persons[] = array(
"vorname" => $row['per_vorname'],
"per_nachname" => $row['per_nachname']
);
}
echo json_encode($persons);
and then create a loop in javascript, to build the HTML.
NOTE: Avoid sql injection by escaping your string.

Cannot retrieve value from post request with ajax

I just wrote my first Ajax request but it doesn't work. It needs to update when a new value in the drop-down list is selected.
This is my javascript code:
$(document).ready(function() {
function ajaxLoaded(response) {
$('#performanceResults').html(response);
}
function doRequest() {
$.ajax({
url: "results.php",
type: 'POST',
success: ajaxLoaded
});
}
$('#performance').change(doRequest);
});
and this is how I retrieve the q part (which doesn't work):
public function getResults() {
$intCase = intval ( $_POST ['q'] );
var_dump ( $intCase );
if ($intCase == 1 or $intCase == 2 ) {
if ($intCase == 1) {
$strSql = 'select bidder_id, won, lost, fillrate, costs, cost_auction from result_bidder where tagload = ( select max(tagload) from result_bidder) order by cost_auction asc limit 1';
}
if ($intCase == 2) {
$strSql = 'select bidder_id, won, lost, fillrate, costs, cost_auction from result_bidder where tagload = ( select max( tagload ) from result_bidder ) order by fillrate asc limit 1';
}
$arrBestPerformer = $objDatabase->queryresult ( $strSql );
echo "<table border='1'>
<tr>
<th>bidder_id</th>
<th>won</th>
<th>lost</th>
<th>fillrate</th>
<th>costs</th>
<th>cost_auction</th>
</tr>";
while ( $row = mysqli_fetch_array ( $arrBestPerformer ) ) {
echo "<tr>";
echo "<td>" . $row ['bidder_id'] . "</td>";
echo "<td>" . $row ['won'] . "</td>";
echo "<td>" . $row ['lost'] . "</td>";
echo "<td>" . $row ['fillrate'] . "</td>";
echo "<td>" . $row ['costs'] . "</td>";
echo "<td>" . $row ['cost_auction'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
}
My Form:
public function SelectPerformanceIndicator() {
$this->getResults ();
$str = '<form >';
$str .= 'Select your performance indicator<br>';
$str .= '<select id = "performance">';
$str .= '<option value = "">Select Performance Indicator</option>';
$str .= '<option value = "1">Cost per auction </option>';
$str .= '<option value = "2">Fillrate </option>';
$str .= '</select>';
$str .= '</form>';
$str .= '<br>';
$str .= '<div id="performanceResults">';
return $str;
}
Your problem is that your POST data string is invalid.
xmlhttp.send("q ="+ str);
Should be
xmlhttp.send("q="+ str);
Without the space between q and =.
And you missed to send the header to tell PHP that it should map the Data sent with the request to the $_POST var.
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
So your correct function would be:
function showUser(str) {
if (str=="") {
document.getElementById("performance").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("performance").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","results.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+ str);
}
But again: use jQuery to make your AJAX requests. If you use jQuery you don't have to struggle with errors like this anymore.
You have added space in query string, "q =" this is not behaving as q key in $_POST variable,
remove space between key and =
xmlhttp.send("q ="+ str);
to
xmlhttp.send("q="+ str);
Update Answer: AJax POST will be worked when request have Content-type: application/x-www-form-urlencoded header.
please add Header before send method
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
OR
you can send request by GET method without header

Changing a PHP db_query parameter with AJAX

Let's say I have this piece of code:
$templatesf = $DB->query('SELECT * FROM templates WHERE category="something"');
Is there a way to change that "something" using javascript/AJAX? For example:
function changesomething(selse){
if (selse == '1'){
something = 'this'
}else{
something = 'that'
}
}
The following will be your input page from where you'll call your ajax handler to process something.
<html>
<head>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var somedata = document.getElementById('something').value;
var queryString = "?something=" + somedata ;
ajaxRequest.open("GET", "ajax-example.php" +
queryString, true);
ajaxRequest.send(null);
}
</script>
</head>
<body>
<form name='myForm'>
Something: <input type='text' id='something' /> <br />
<input type='button' onclick='ajaxFunction()'
value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
Below is the php code to handle your request and process your something
<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$something = $_GET['something'];
// Escape User Input to help prevent SQL Injection
$something = mysql_real_escape_string($something);
//build query
$query = "SELECT * FROM ajax_example WHERE something = '$something'";
$qry_result = mysql_query($query) or die(mysql_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>something</th>";
$display_string .= "<th>other</th>";
$display_string .= "<th>blahblah</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[something]</td>";
$display_string .= "<td>$row[other]</td>";
$display_string .= "<td>$row[blahblah]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>
You'll need to place a variable instead of that SOMETHING, and then pass an ajax variable to that method.
You'll catch the variable with a $_POST and place it instead of the variable you had previously.
You could also use a default(in case nothing was passed, or wrong type of POST was passed).

Categories

Resources