< AJAX

Példák

Fogalmak

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Szókereső</title>
    <meta charset="UTF-8">
    <meta name="description" content="">
    <meta name="keywords" content="">
</head>
<body>
<h1>AJAX</h1>
 
<script>
 
httpRequest = new XMLHttpRequest();
 
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', "ker.php");
httpRequest.send();
 
 
function alertContents() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            var $ez = JSON.parse(httpRequest.responseText);            
            alert($ez[1]['szo']);
        } else {
            alert('A probléma a lekérés során!');
        }
    }
}    
 
 
</script>    
 
</body>
</html>
config.php
<?php
 
$db['host'] = "localhost";
$db['user'] = "szokereso";
$db['pass'] = "titok";
$db['dbname'] = "szokereso";
 
?>

Ne írassunk ki HTML elemeket!

ker.php
<?php
require_once("mysql.php");
 
$conn = dbopen();
leker($conn);
 
?>
mysql.php
<?php
require "config.php";
 
function leker($conn) {
    $sql = "select * from szavak";
    $result = $conn->query($sql);
    //echo json_encode($result->fetch_assoc());
 
 
    $res = array();    
    while($sor = $result->fetch_assoc()) {
        array_push($res, $sor);        
    }
    echo json_encode($res);
 
}
 
function insertDolgozo($conn, $data) {
	$sql = "INSERT INTO Dolgozók (Név, Település) 
        VALUES (\"{$data['nev']}\", \"{$data['telepules']}\")";
	$conn->query($sql);
}
 
function dbopen() {
	global $db;
	$conn = new mysqli($db['host'], $db['user'], $db['pass'], $db['dbname']);
	if($conn->connect_error)
		die("Hiba a kapcsolódás során (" . $mysqli->connect_errno . ")"
		. $conn->connect_error);
	$conn->set_charset("utf8");	
	return $conn;	
}
 
function dbclose($conn) {
	$conn->close();
}
?>

Adatbázis

CREATE DATABASE IF NOT EXISTS `szokereso` DEFAULT CHARACTER SET utf8 COLLATE utf8_hungarian_ci;
USE `szokereso`;
 
CREATE TABLE IF NOT EXISTS `szavak` (
`az` INT(11) NOT NULL,
  `szo` VARCHAR(100) COLLATE utf8_hungarian_ci NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_hungarian_ci;
 
INSERT INTO `szavak` (`az`, `szo`) VALUES
(1, 'zsiráf'),
(2, 'kutya'),
(3, 'macska'),
(4, 'elefánt');
 
ALTER TABLE `szavak`
 ADD PRIMARY KEY (`az`);
 
 
ALTER TABLE `szavak`
MODIFY `az` INT(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;