Felhasználói eszközök

Eszközök a webhelyen


oktatas:web:jquery:ajax:ajax_metodus

< AJAX

jQuery .ajax metódus

Todo

index.html
<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="utf-8">
    <title>TODO</title>
</head>
<body>
    <h1>TODO</h1>
    <input type="text" id="newtodo">
    <button id="addButton">Hozzáad</button>
    <ul id="todolist"></ul>
    <script src="lib/jquery-3.5.1.js"></script>
    <script src="js/select.js"></script>
    <script src="js/insert.js"></script>
</body>
</html>
js/select.js
$.ajax('php/getTodos.php', {
    success: function(data, status, xhr) {
        let list = $.parseJSON(data)
        initList(list);
    }
});
 
function initList(list) {
    $.each(list, function(index, value){
        $('#todolist').append(
        '<li>' + value['description'] + '</li>');
    });
}
js/insert.js
$('#addButton').click(function(){
    var newtodo = $('#newtodo').val();
    $('#newtodo').val('');
    $('#todolist').append('<li>' + newtodo + '</li>');
    var jsonNewTodo = JSON.stringify(newtodo);
    $.ajax( {
        type: 'post',
        url: 'php/insertTodo.php',
        data: jsonNewTodo,
        success: function(result) {
            console.log(result);
        }
    });
});
php/includes/config.php
<?php
 
$db['host'] = 'localhost';
$db['user'] = 'btodo';
$db['pass'] = 'titok';
$db['name'] = 'btodo';
php/includes/mariadb.php
<?php
 
include_once 'config.php';
 
function connectDb() {
	global $db;
	$conn = mysqli_connect(
		$db['host'], 
		$db['user'], 
		$db['pass'], 
		$db['name']
	);
	if (!$conn) {
		error_log('Hiba! A kapcsolódás sikertelen!');
	}
	if(!mysqli_set_charset($conn, 'utf8')) {
		error_log('Hiba! A karakterkódolás beállítása sikertelen!');
	}
	return $conn;
}
 
function closeDb($conn) {
	mysqli_close($conn);
}
php/includes/database.php
<?php
include_once 'mariadb.php';
 
function lekerTodos() {
	$conn = connectDb();
	$sql = "
	select * from todos
	";
	$res = mysqli_query($conn, $sql);
	if(!$res) {
		error_log('Hiba! A lekérdezés sikertelen!' .
		$sql);
		exit();
	}
	for( $datar = array(); 
		$row = $res->fetch_assoc(); 
		$datar[] = $row);
	closeDb($conn);
	return $datar;
}
 
function beszurTodo($todo) {
	$conn = connectDb();
	$sql = "
	insert into todos
	(description)
	values
	(?)
	";
 
	if ($stmt = mysqli_prepare($conn, $sql)) {
		mysqli_stmt_bind_param($stmt, "s", 
			$todo
			);
		mysqli_stmt_execute($stmt);
		error_log(mysqli_stmt_error($stmt));
		mysqli_stmt_close($stmt);
		echo "siker";
	} else {
		echo "Hiba a beszúrás során!";
	}
	closeDb($conn);
 
}
php/getTodos.php
<?php
 
include 'includes/database.php';
 
$tomb = lekerTodos();
 
echo json_encode($tomb);
php/insertTodo.php
<?php
include 'includes/database.php';
 
$todoDescription = json_decode(file_get_contents("php://input"));
 
beszurTodo($todoDescription);
oktatas/web/jquery/ajax/ajax_metodus.txt · Utolsó módosítás: 2021/02/28 23:39 szerkesztette: admin