Script php e ajax nella stessa pagina

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:
 

Furion

Utente Attivo
26 Ago 2013
32
0
0
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
Autore Titolo Forum Risposte Data
O [PHP] inviare dati da form e script ajax PHP 0
C Eseguire script ajax nella stessa pagina index.php Ajax 2
S [Retribuito] Cerco sviluppatore script ajax/php/mysql Offerte e Richieste di Lavoro e/o Collaborazione 0
E Problema con script ajax+php Ajax 2
P lanciare script asp (o php) da jquery Javascript 1
G [PHP] Creare script di prenotazione con controllo disponibilità. PHP 7
M Collegamento tra form html e script php PHP 4
felino PHP e script generazione file excel PHP 2
R Primo script in PHP / CSS PHP 4
felino Script PHP per leggere un file JSON. autenticazione? PHP 4
T [a pagamento] programmatore PHP che mi aiuti a migrare gli script da vecchia versione PHP a nuova Offerte e Richieste di Lavoro e/o Collaborazione 1
Max 1 [PHP] Script che funziona in locale e non online PHP 16
K Help: problema con uno script di booking in php! PHP 0
P [PHP] Aggiungere un mio script a prestashop? PHP 10
D [Javascript] inserire uno script in un file php Javascript 6
Gabriele15497514 php testo errato durante la lettura del file txt quando lo script viene eseguito contemporaneamente PHP 3
romeocharly [PHP] Script per rinominare in automatico le immagini inviate da ftp PHP 0
A [PHP] Script con array con numeri che iniziano per 00 PHP 2
TpD [PHP] Script per organizzazione presenza eventi PHP 3
D [PHP] script che invii una mail automatica dopo risposta ad una discussione di un forum PHP 0
T interpretare uno script php non fatto da me... PHP 3
O Script PHP e loro visibilità PHP 4
A [PHP] Script Ip camera su altervista senza sottocartelle PHP 6
M [PHP] Problema script ricezione e invio posta... PHP 1
Y Codice AdSense su script php PHP 4
L [PHP] Problema Script 'Not Found' PHP 4
webmachine [PHP] Script per censurare parole PHP 4
C richiamare una funzione in un altro script php PHP 1
M [PHP] Script per controllo disponibilitá negozio in citta PHP 4
B [PHP] hp script creare un utente diminuendo -1 e cosi via PHP 1
Y Modificare script php PHP 5
paloppa [PHP] script importati da internet o da file PHP 24
xone [Vendo] Script gestionale php-mysql gestione pratiche Altri Annunci 0
T mostrare il riultato di uno script php Ajax 2
K Script PHP per leggere array.txt Presentati al Forum 3
Punix [PHP] problema script invio e-mail PHP 2
R pagina html + script php PHP 12
M Script php funziona / non funziona in base all'hosting PHP 21
T [PHP] piccola modifica a script (non mio...) PHP 8
Trapano Script php che non va più' con Versione MySQL: 5.6 PHP 5
Mauro Guardiani [PHP] script per caricamento video PHP 0
matteoraggi Screenshot da script php PHP 0
F Richiesta script PHP PHP 1
giancadeejay Bloccare utente se non loggato con script php PHP 12
booklisa [PHP] Script nello script PHP 2
H [PHP] Script non vengono eseguiti PHP 2
elpirata [PHP] Script reminder email PHP 11
S Problema con script php-javascript PHP 2
9 inserire contenuto in un file pdf aperto sul browser tramite script php PHP 0
A [PHP] inserire paginazione su script php/mysql PHP 6

Discussioni simili