Script php e ajax nella stessa pagina

  • Creatore Discussione Creatore Discussione Furion
  • Data di inizio Data di inizio

Furion

Utente Attivo
26 Ago 2013
32
0
0
Non sono sicuro sia la sezione giusta ma ci provo lo stesso

Mi sto avvicinando all'ajax e su internet ho trovato uno script di prova che è diviso in due pagine:

-pagina html con input e risultato ricerca,
-pagina php che estrae i dati dal db.

io ho necessità di mettere tutto su una pagina quindi lo script ora è così:

PHP:
<html>
<body>
<script language="javascript" type="text/javascript">
function PostData() {
    // 1. Create XHR instance - Start
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }
    // 1. Create XHR instance - End
    
    // 2. Define what to do when XHR feed you the response from the server - Start
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status == 200 && xhr.status < 300) {
                document.getElementById('ajaxDiv').innerHTML = xhr.responseText;
            }
        }
    }
    // 2. Define what to do when XHR feed you the response from the server - Start

     var age = document.getElementById('age').value;
     var wpm = document.getElementById('wpm').value;
     var sex = document.getElementById('sex').value;

    // 3. Specify your action, location and Send to the server - Start 
    xhr.open('POST','prova.php',true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("age=" + age + "&sex=" + sex + "&wpm=" + wpm);
    // 3. Specify your action, location and Send to the server - End
}
</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 value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='PostData()' 
                              value='Query MySQL'/>
</form>
</body>
</html>

<?php
        $username = "";
        $password = "";
        $host = "localhost";
        $database = "";

          $db=mysql_connect($host, $username, $password) or die("Errore durante la connessione al database");
mysql_select_db($database, $db) or die("Errore durante la selezione del database");


	// Retrieve data from Query String
$age = $_POST['age'];
$sex = $_POST['sex'];
$wpm = $_POST['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());

echo "<div id='ajaxDiv'>";

	//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[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;

echo "</div>";
?>

e senza inviare dati appare così:
screen1.jpg

il problema è che l'output è questo:
screen2.jpg

come risolvo la cosa?
Grazie anticipatamente!:byebye:
 
Ok ho fatto passi avanti modificando lo script che ora è:

PHP:
<html>
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function PostData() {
    // 1. Create XHR instance - Start
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }
    // 1. Create XHR instance - End
    
    // 2. Define what to do when XHR feed you the response from the server - Start
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status == 200 && xhr.status < 300) {
                document.getElementById('ajaxDiv').innerHTML = xhr.responseText;
            }
        }
    }
    // 2. Define what to do when XHR feed you the response from the server - Start

     var name = document.getElementById('name').value; 
     var age = document.getElementById('age').value;
     var wpm = document.getElementById('wpm').value;
     var sex = document.getElementById('sex').value;

    // 3. Specify your action, location and Send to the server - Start 
    xhr.open('POST','prova2.php',true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("age=" + age + "&sex=" + sex + "&wpm=" + wpm + "&name=" + name);
    // 3. Specify your action, location and Send to the server - End
}
</script>

<div id='ajaxDiv'>
<?
        $username = "";
        $password = "";
        $host = "localhost";
        $database = "";

          $db=mysql_connect($host, $username, $password) or die("Errore durante la connessione al database");
mysql_select_db($database, $db) or die("Errore durante la selezione del database");

$query = "SELECT * FROM ajax_example";
	//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[name]</td>";
	$display_string .= "<td>$row[age]</td>";
	$display_string .= "<td>$row[sex]</td>";
	$display_string .= "<td>$row[wpm]</td>";
	$display_string .= "</tr>";
}
$display_string .= "</table>";	
echo "$display_string";
?>


<br>
<form name='myForm' >
Name: <input type='text' id='name' /> <br />
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='PostData()' 
                              value='Invia'/>
</form>
</div>
</body>
</html>


<?php

	// Retrieve data from Query String
$name = $_POST['name'];
$age = $_POST['age'];
$sex = $_POST['sex'];
$wpm = $_POST['wpm'];
if(isset($age)){

$insert = "INSERT INTO `ajax_example` (`name`, `age`, `sex`, `wpm`) VALUES ('$name', '$age', '$sex', '$wpm')";
$res = mysql_query($insert) or die(mysql_error());

	// 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";
	//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[name]</td>";
	$display_string .= "<td>$row[age]</td>";
	$display_string .= "<td>$row[sex]</td>";
	$display_string .= "<td>$row[wpm]</td>";
	$display_string .= "</tr>";
	
}
$display_string .= "</table>";
echo "$display_string";
}
?>

lo script diciamo che funziona però il mio intento sarebbe questo:

- apro la pagina mostro i record già presenti nel db,
- inserisco nuovi record e lo script me lo deve mostrare appena inserito.

questo è quello che succede quando apro la pagina:
screen3.jpg

questo quello che accade quando invio dati:
screen4.jpg

come vedete mi rimangono sopra i dati vecchi e sotto quelli nuovi...come faccio per mostrarli solo sopra, cioè sovrascrivendo quelli vecchi? :confused:
 

Discussioni simili