<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Beispiel Archiv - Homepage nach Preis - Webseite erstellen lassen</title>
	<atom:link href="https://homepage-nach-preis.de/wort/beispiel/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>★ Responsive Webdesigner Homepage erstellen lassen, bereits ab 299 Euro professionelle Webseite. ✓ Google-Optimiert ✓ Mobil-Optimiert &#124; Webdesign &#38; Seo</description>
	<lastBuildDate>Fri, 06 Sep 2024 16:40:50 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://homepage-nach-preis.de/wp-content/uploads/2021/02/cropped-icon-150x150.png</url>
	<title>Beispiel Archiv - Homepage nach Preis - Webseite erstellen lassen</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Simple Blockchain Beispiel mit Miner</title>
		<link>https://homepage-nach-preis.de/2024/09/06/simple-blockchain-beispiel-mit-miner/</link>
					<comments>https://homepage-nach-preis.de/2024/09/06/simple-blockchain-beispiel-mit-miner/#respond</comments>
		
		<dc:creator><![CDATA[Homepage-nach-Preis]]></dc:creator>
		<pubDate>Fri, 06 Sep 2024 16:17:14 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Beispiel]]></category>
		<category><![CDATA[Blockchain]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[Miner]]></category>
		<guid isPermaLink="false">https://homepage-nach-preis.de/?p=8348</guid>

					<description><![CDATA[<p>Wie funktioniert eine Kryptowährung bzw. eine Blockchain mit einem Proof of Work Mechanismus (Mining). Ihr Gerät unterstützt eine Wiedergabe des Videos nicht. Github: https://github.com/HNP-Christopher-Rohde/hnp-example-blockchain-with-miner Blockchain Die Blockchain in diesem System ist eine auf Blöcken basierende Kette, die kryptografisch gesichert ist. Jeder Block enthält folgende Informationen: Index: Die Position des Blocks in der Kette. Zeitstempel: Der Zeitpunkt, zu dem der Block erstellt wurde (in Unix-Zeit). Daten: Die im Block gespeicherten Informationen (in binärer Form). Vorheriger Hash: Der Hash des vorhergehenden Blocks, der die Verbindung zu diesem sicherstellt. Hash: Der eigene Hash des Blocks, der durch den Hashing-Algorithmus SHA-256 berechnet wird. Nonce: Eine Zahl, die während des Minings variiert wird, um den Hash zu finden, der den Anforderungen der Schwierigkeit entspricht. Die Blockchain wird mit einem Genesis-Block initialisiert. Jeder neue Block wird durch einen Mining-Prozess erstellt, der den Hash so anpasst, dass er den Schwierigkeitsanforderungen (Difficulty) entspricht, d. h. der Hash muss mit einer bestimmten Anzahl von Nullen beginnen. Die Schwierigkeit passt sich dynamisch an, basierend auf der Zeit, die für die Erstellung der letzten Blöcke benötigt wurde. Validität der Blockchain: Jeder Block in der Kette wird überprüft, um sicherzustellen, dass der Hash korrekt ist und der Hash des vorherigen Blocks mit....</p>
<p>Der Beitrag <a rel="nofollow" href="https://homepage-nach-preis.de/2024/09/06/simple-blockchain-beispiel-mit-miner/">Simple Blockchain Beispiel mit Miner</a> erschien zuerst auf <a rel="nofollow" href="https://homepage-nach-preis.de">Homepage nach Preis - Webseite erstellen lassen</a>. Geschrieben von <a rel="nofollow" href="https://homepage-nach-preis.de/author/homepageadmin/">Homepage-nach-Preis</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>Wie funktioniert eine Kryptowährung bzw. eine Blockchain mit einem Proof of Work Mechanismus (Mining). </strong></p>
<div class="video-own" style="padding-top:5px;"><video style="width:99%;" poster="https://homepage-nach-preis.de/wp-content/uploads/2024/09/blockchain.jpg" controls controlsList="nodownload" preload="none"><source src="https://homepage-nach-preis.de/wp-content/uploads/2024/09/2024-09-06-18-38-00.mp4" type="video/mp4"/>Ihr Gerät unterstützt eine Wiedergabe des Videos nicht.</video></div>
<p><strong>Github:</strong> <a href="https://github.com/HNP-Christopher-Rohde/hnp-example-blockchain-with-miner" target="_blank" rel="nofollow noopener">https://github.com/HNP-Christopher-Rohde/hnp-example-blockchain-with-miner</a></p>
<h4>Blockchain</h4>
<p>Die Blockchain in diesem System ist eine auf Blöcken basierende Kette, die kryptografisch gesichert ist. Jeder Block enthält folgende Informationen:</p>
<p>    Index: Die Position des Blocks in der Kette.<br />
    Zeitstempel: Der Zeitpunkt, zu dem der Block erstellt wurde (in Unix-Zeit).<br />
    Daten: Die im Block gespeicherten Informationen (in binärer Form).<br />
    Vorheriger Hash: Der Hash des vorhergehenden Blocks, der die Verbindung zu diesem sicherstellt.<br />
    Hash: Der eigene Hash des Blocks, der durch den Hashing-Algorithmus SHA-256 berechnet wird.<br />
    Nonce: Eine Zahl, die während des Minings variiert wird, um den Hash zu finden, der den Anforderungen der Schwierigkeit entspricht.</p>
<p>Die Blockchain wird mit einem Genesis-Block initialisiert. Jeder neue Block wird durch einen Mining-Prozess erstellt, der den Hash so anpasst, dass er den Schwierigkeitsanforderungen (Difficulty) entspricht, d. h. der Hash muss mit einer bestimmten Anzahl von Nullen beginnen. Die Schwierigkeit passt sich dynamisch an, basierend auf der Zeit, die für die Erstellung der letzten Blöcke benötigt wurde.</p>
<p><strong>Validität der Blockchain:</strong></p>
<p>    Jeder Block in der Kette wird überprüft, um sicherzustellen, dass der Hash korrekt ist und der Hash des vorherigen Blocks mit dem gespeicherten previous_hash übereinstimmt.<br />
    Es wird außerdem geprüft, ob der Block die Schwierigkeit (Difficulty) erfüllt, bevor er zur Kette hinzugefügt wird.</p>
<p>Die Blockchain speichert die Blöcke auf der Festplatte (z. B. in der Datei blockchain.json) und bietet APIs für den Empfang und das Senden neuer Blöcke zwischen Peers.</p>
<p><strong>Blockchain:</strong></p>
<pre>
use serde::{Serialize, Deserialize};
use std::collections::VecDeque;
use std::fs;
use sha2::Digest;
use hex;
use std::time::{SystemTime, UNIX_EPOCH};
use reqwest;
use warp::Filter;
use log::{info, error};
use std::env;
use std::sync::{Arc, Mutex};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Block {
    pub index: u64,
    pub timestamp: u64,
    pub data: Vec&#x3C;u8&#x3E;,
    pub previous_hash: String,
    pub hash: String,
    pub nonce: u64,
}

impl Block {
    pub fn new(index: u64, data: Vec&#x3C;u8&#x3E;, previous_hash: String) -&#x3E; Self {
        let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
        let mut block = Block {
            index,
            timestamp,
            data,
            previous_hash,
            hash: String::new(),
            nonce: 0,
        };
        block.hash = block.calculate_hash();
        info!(&#x22;Created new block: {:?}&#x22;, block);
        block
    }

    pub fn calculate_hash(&#x26;self) -&#x3E; String {
        let mut hasher = sha2::Sha256::new();
        hasher.update(format!(&#x22;{}{}{}{}{}&#x22;, self.index, self.timestamp, hex::encode(&#x26;self.data), self.previous_hash, self.nonce));
        let result = hasher.finalize();
        hex::encode(result)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Blockchain {
    pub chain: VecDeque&#x3C;Block&#x3E;,
    pub difficulty: u32,
    pub adjustment_interval: u64,
    pub target_block_time: u64,
    pub last_difficulty_update: u64,
}

impl Blockchain {
    pub fn new(difficulty: u32, adjustment_interval: u64, target_block_time: u64) -&#x3E; Self {
        let mut chain = VecDeque::new();
        chain.push_back(create_genesis_block());
        info!(&#x22;Blockchain initialized with genesis block&#x22;);
        Blockchain {
            chain,
            difficulty,
            adjustment_interval,
            target_block_time,
            last_difficulty_update: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
        }
    }

    pub fn add_block(&#x26;mut self, data: Vec&#x3C;u8&#x3E;) {
        let previous_block = self.chain.back().unwrap();
        let new_block = mine_block(previous_block, data, self.difficulty);
        info!(&#x22;Adding new block: {:?}&#x22;, new_block);
        self.chain.push_back(new_block);
    
        // Update difficulty if needed
        if (self.chain.len() as u64) % self.adjustment_interval == 0 {
            self.update_difficulty_based_on_time();
        }
    
        if let Err(e) = self.save_to_file(&#x22;blockchain.json&#x22;) {
            error!(&#x22;Failed to save blockchain after adding block: {}&#x22;, e);
        }
    }
    
    pub fn is_valid(&#x26;self) -&#x3E; bool {
        for i in 1..self.chain.len() {
            let current = &#x26;self.chain[i];
            let previous = &#x26;self.chain[i - 1];

            if current.hash != current.calculate_hash() {
                error!(&#x22;Block {} has invalid hash&#x22;, current.index);
                return false;
            }

            if current.previous_hash != previous.hash {
                error!(&#x22;Block {} has invalid previous hash&#x22;, current.index);
                return false;
            }

            if !meets_difficulty(&#x26;current.hash, self.difficulty) {
                error!(&#x22;Block {} does not meet difficulty&#x22;, current.index);
                return false;
            }
        }
        true
    }

    pub fn save_to_file(&#x26;self, filename: &#x26;str) -&#x3E; std::io::Result&#x3C;()&#x3E; {
        let serialized = serde_json::to_string(self)
            .expect(&#x22;Serialization failed&#x22;);
        fs::write(filename, serialized).map_err(|e| {
            error!(&#x22;Failed to write blockchain to file: {}&#x22;, e);
            e
        })?;
        info!(&#x22;Blockchain saved to file: {}&#x22;, filename);
        Ok(())
    }
    
    pub fn load_from_file(filename: &#x26;str) -&#x3E; std::io::Result&#x3C;Self&#x3E; {
        match fs::read_to_string(filename) {
            Ok(data) if !data.is_empty() =&#x3E; {
                match serde_json::from_str::&#x3C;Blockchain&#x3E;(&#x26;data) {
                    Ok(blockchain) =&#x3E; {
                        info!(&#x22;Blockchain loaded from file: {}&#x22;, filename);
                        Ok(blockchain)
                    }
                    Err(e) =&#x3E; {
                        info!(&#x22;Failed to deserialize blockchain from file, creating a new one: {}&#x22;, e);
                        let (difficulty, adjustment_interval, target_block_time) = load_config();
                        Ok(Blockchain::new(difficulty, adjustment_interval, target_block_time))
                    }
                }
            }
            _ =&#x3E; {
                info!(&#x22;Blockchain file is empty or not found. Creating a new blockchain.&#x22;);
                let (difficulty, adjustment_interval, target_block_time) = load_config();
                Ok(Blockchain::new(difficulty, adjustment_interval, target_block_time))
            }
        }
    }
    
    pub async fn broadcast_new_block(&#x26;self, block: &#x26;Block, peers: &#x26;[&#x26;str]) -&#x3E; reqwest::Result&#x3C;()&#x3E; {
        for peer in peers {
            let url = format!(&#x22;{}/new-block&#x22;, peer);
            info!(&#x22;Broadcasting new block to peer: {}&#x22;, url);
            let result = reqwest::Client::new()
                .post(&#x26;url)
                .json(&#x26;block)
                .send()
                .await;

            match result {
                Ok(_) =&#x3E; info!(&#x22;Successfully sent block to {}&#x22;, url),
                Err(e) =&#x3E; error!(&#x22;Failed to send block to {}: {:?}&#x22;, url, e),
            }
        }
        Ok(())
    }
</pre>
<pre>
    pub fn add_block_from_request(&#x26;mut self, block: Block) -&#x3E; bool {
        let previous_block = self.chain.back().unwrap();

        info!(&#x22;Received block: {:?}&#x22;, block);
        info!(&#x22;Last block in chain: {:?}&#x22;, previous_block);

        // Additional validation for the timestamp
        if block.timestamp &#x3C;= previous_block.timestamp {
            error!(&#x22;Block timestamp is not valid&#x22;);
            return false;
        }

        let is_valid = block.index == previous_block.index + 1
            &#x26;&#x26; block.previous_hash == previous_block.hash
            &#x26;&#x26; block.hash == block.calculate_hash()
            &#x26;&#x26; meets_difficulty(&#x26;block.hash, self.difficulty);
        
        if is_valid {
            info!(&#x22;Valid block received and added to chain&#x22;);
            self.chain.push_back(block);
            if let Err(e) = self.save_to_file(&#x22;blockchain.json&#x22;) {
                error!(&#x22;Failed to save blockchain after adding block: {}&#x22;, e);
            }
        } else {
            error!(&#x22;Invalid block received: \n\
                    Index: {} \n\
                    Previous Hash: {} \n\
                    Expected Previous Hash: {} \n\
                    Hash: {} \n\
                    Calculated Hash: {} \n\
                    Difficulty Met: {}&#x22;,
                block.index,
                block.previous_hash,
                previous_block.hash,
                block.hash,
                block.calculate_hash(),
                meets_difficulty(&#x26;block.hash, self.difficulty));
        }
        
        is_valid
    }
    
    pub fn update_difficulty_based_on_time(&#x26;mut self) {
        let length = self.chain.len() as u64;
        info!(&#x22;Chain length: {}&#x22;, length);
        
        if length &#x3E;= self.adjustment_interval {
            let interval_start_block = &#x26;self.chain[self.chain.len() - self.adjustment_interval as usize];
            let interval_end_block = self.chain.back().unwrap();
    
            let time_taken = interval_end_block.timestamp - interval_start_block.timestamp;
            let expected_time = self.adjustment_interval * self.target_block_time;
    
            info!(&#x22;Time taken for the last {} blocks: {} seconds&#x22;, self.adjustment_interval, time_taken);
            info!(&#x22;Expected time for the last {} blocks: {} seconds&#x22;, self.adjustment_interval, expected_time);
    
            if time_taken &#x3C; expected_time / 2 {
                self.difficulty += 1;
                info!(&#x22;Difficulty increased to {}&#x22;, self.difficulty);
            } else if time_taken &#x3E; expected_time * 2 {
                if self.difficulty &#x3E; 1 {
                    self.difficulty -= 1;
                    info!(&#x22;Difficulty decreased to {}&#x22;, self.difficulty);
                }
            } else {
                info!(&#x22;Difficulty remains at {}&#x22;, self.difficulty);
            }
    
            // Update the last difficulty update timestamp
            self.last_difficulty_update = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
        } else {
            info!(&#x22;Not enough blocks to adjust difficulty.&#x22;);
        }
    }
    
    
    pub fn update_difficulty(&#x26;mut self, new_difficulty: u32) {
        self.difficulty = new_difficulty;
        info!(&#x22;Difficulty updated to {}&#x22;, new_difficulty);
        if let Err(e) = self.save_to_file(&#x22;blockchain.json&#x22;) {
            error!(&#x22;Failed to save blockchain after updating difficulty: {}&#x22;, e);
        }
    }
}

pub fn create_genesis_block() -&#x3E; Block {
    Block::new(0, &#x22;Genesis Block&#x22;.as_bytes().to_vec(), &#x22;0&#x22;.to_string())
}

fn meets_difficulty(hash: &#x26;str, difficulty: u32) -&#x3E; bool {
    let target = vec![0u8; difficulty as usize];
    let hash_bytes = hex::decode(hash).expect(&#x22;Hex decode failed&#x22;);
    hash_bytes.len() &#x3E;= target.len() &#x26;&#x26; hash_bytes.starts_with(&#x26;target)
}

fn mine_block(previous_block: &#x26;Block, data: Vec&#x3C;u8&#x3E;, difficulty: u32) -&#x3E; Block {
    let mut new_block = Block::new(previous_block.index + 1, data.clone(), previous_block.hash.clone());

    let mut attempt = 0;

    while !meets_difficulty(&#x26;new_block.hash, difficulty) {
        new_block.nonce += 1;
        new_block.hash = new_block.calculate_hash();

        attempt += 1;
        if attempt % 100 == 0 {
            println!(&#x22;Attempt {}: Trying hash: {}&#x22;, attempt, new_block.hash);
        }
    }

    new_block
}


fn load_config() -&#x3E; (u32, u64, u64) {
    use serde::Deserialize;
    #[derive(Deserialize)]
    struct Config {
        initial_difficulty: u32,
        adjustment_interval: u64,
        target_block_time: u64,
    }

    let data = fs::read_to_string(&#x22;config.json&#x22;).expect(&#x22;Unable to read config file&#x22;);
    let config: Config = serde_json::from_str(&#x26;data).expect(&#x22;Unable to parse config file&#x22;);
    (config.initial_difficulty, config.adjustment_interval, config.target_block_time)
}

#[tokio::main]
async fn main() {
    env::set_var(&#x22;RUST_LOG&#x22;, &#x22;info&#x22;);
    env_logger::init();

    let (initial_difficulty, adjustment_interval, target_block_time) = load_config();
    let blockchain = Arc::new(Mutex::new(
        Blockchain::load_from_file(&#x22;blockchain.json&#x22;).unwrap_or_else(|_| Blockchain::new(initial_difficulty, adjustment_interval, target_block_time))
    ));

    let blockchain_filter = warp::any().map(move || blockchain.clone());

    let new_block = warp::post()
        .and(warp::path(&#x22;new-block&#x22;))
        .and(warp::body::json())
        .and(blockchain_filter.clone())
        .map(|block: Block, blockchain: Arc&#x3C;Mutex&#x3C;Blockchain&#x3E;&#x3E;| {
            let mut blockchain = blockchain.lock().unwrap();
            let response = if blockchain.add_block_from_request(block) {
                &#x22;Block added successfully&#x22;
            } else {
                &#x22;Invalid block&#x22;
            };
            response
        });

    let difficulty = warp::get()
        .and(warp::path(&#x22;difficulty&#x22;))
        .map(move || format!(&#x22;Difficulty: {}&#x22;, initial_difficulty));

    let set_difficulty = warp::post()
        .and(warp::path(&#x22;set-difficulty&#x22;))
        .and(warp::body::json())
        .and(blockchain_filter.clone())
        .map(|_new_difficulty: u32, _blockchain: Arc&#x3C;Mutex&#x3C;Blockchain&#x3E;&#x3E;| {
            // Ignoring difficulty change here, as it&#x27;s handled externally
            format!(&#x22;Difficulty updated to {}&#x22;, _new_difficulty)
        });

    let last_block = warp::get()
        .and(warp::path(&#x22;last-block&#x22;))
        .and(blockchain_filter.clone())
        .map(|blockchain: Arc&#x3C;Mutex&#x3C;Blockchain&#x3E;&#x3E;| {
            let blockchain = blockchain.lock().unwrap();
            let last_block = blockchain.chain.back().cloned().unwrap_or_else(|| create_genesis_block());
            warp::reply::json(&#x26;last_block)
        });

    let routes = new_block.or(difficulty).or(set_difficulty).or(last_block);

    info!(&#x22;Starting server at http://127.0.0.1:8000&#x22;);
    warp::serve(routes).run(([127, 0, 0, 1], 8000)).await;
}

</pre>
<h4>Miner</h4>
<p>Der Miner ist für die Erstellung neuer Blöcke in der Blockchain verantwortlich. Er arbeitet nach einem Proof-of-Work-Mechanismus, bei dem der Miner eine nonce-Nummer anpasst, bis ein gültiger Hash gefunden wird, der den Schwierigkeitsanforderungen entspricht.</p>
<p><strong>Ablauf des Mining-Prozesses:</strong></p>
<p>    Der Miner fragt den letzten Block der Blockchain von einem Server ab.<br />
    Der Miner fragt die aktuelle Schwierigkeit vom Server ab.<br />
    Ein neuer Block wird erstellt, indem die Daten des vorherigen Blocks verwendet werden, sowie neue Transaktionsdaten.<br />
    Der Miner berechnet den Hash des neuen Blocks durch Anpassung der nonce, bis der Hash die Schwierigkeit erfüllt (d. h., der Hash beginnt mit einer bestimmten Anzahl von Nullen).<br />
    Sobald ein gültiger Block gefunden wurde, wird er an den Server gesendet, der ihn zur Blockchain hinzufügt.</p>
<p>Der Mining-Prozess läuft in einem Loop, sodass kontinuierlich nach neuen Blöcken gesucht wird, die der Blockchain hinzugefügt werden können.</p>
<pre>
use serde::{Serialize, Deserialize};
use sha2::{Sha256, Digest};
use std::time::{SystemTime, UNIX_EPOCH};
use reqwest;
use hex;
use anyhow::{Result, Context};
use tokio::task;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Block {
    pub index: u64,
    pub timestamp: u64,
    pub data: Vec&#x3C;u8&#x3E;,
    pub previous_hash: String,
    pub hash: String,
    pub nonce: u64,
}

impl Block {
    pub fn new(index: u64, data: Vec&#x3C;u8&#x3E;, previous_hash: String) -&#x3E; Self {
        let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
        let mut block = Block {
            index,
            timestamp,
            data,
            previous_hash,
            hash: String::new(),
            nonce: 0,
        };
        block.hash = block.calculate_hash();
        block
    }

    pub fn calculate_hash(&#x26;self) -&#x3E; String {
        let mut hasher = Sha256::new();
        hasher.update(format!(&#x22;{}{}{}{}{}&#x22;, self.index, self.timestamp, hex::encode(&#x26;self.data), self.previous_hash, self.nonce));
        let result = hasher.finalize();
        hex::encode(result)
    }
}

fn meets_difficulty(hash: &#x26;str, difficulty: u32) -&#x3E; bool {
    let target = vec![0u8; difficulty as usize];
    let hash_bytes = hex::decode(hash).expect(&#x22;Hex decode failed&#x22;);
    hash_bytes.starts_with(&#x26;target)
}

async fn mine_block(previous_block: &#x26;Block, data: Vec&#x3C;u8&#x3E;, difficulty: u32) -&#x3E; Block {
    let mut new_block = Block::new(previous_block.index + 1, data.clone(), previous_block.hash.clone());

    // Parallel mining using multiple threads
    let mining_task = task::spawn_blocking(move || {
        let mut attempt = 0;
        while !meets_difficulty(&#x26;new_block.hash, difficulty) {
            new_block.nonce += 1;
            new_block.hash = new_block.calculate_hash();

            attempt += 1;
            if attempt % 100 == 0 {
                println!(&#x22;Attempt {}: Trying hash: {}&#x22;, attempt, new_block.hash);
            }
        }

        new_block
    });

    mining_task.await.unwrap()
}

async fn get_last_block_from_server() -&#x3E; Result&#x3C;Block&#x3E; {
    let client = reqwest::Client::new();
    let url = &#x22;http://localhost:8000/last-block&#x22;;

    let res = client.get(url)
        .send()
        .await
        .context(&#x22;Failed to send request to get last block&#x22;)?;

    let last_block: Block = res.json().await
        .context(&#x22;Failed to parse last block&#x22;)?;
    Ok(last_block)
}

async fn send_block_to_server(block: &#x26;Block) -&#x3E; Result&#x3C;()&#x3E; {
    let client = reqwest::Client::new();
    let url = &#x22;http://localhost:8000/new-block&#x22;;

    println!(&#x22;Sending block: {:?}&#x22;, block);

    let res = client.post(url)
        .json(block)
        .send()
        .await
        .context(&#x22;Failed to send request to post new block&#x22;)?;

    let status = res.status();
    let body = res.text().await
        .context(&#x22;Failed to read response text&#x22;)?;

    if status.is_success() {
        println!(&#x22;Block successfully sent to server.&#x22;);
    } else {
        println!(&#x22;Failed to send block to server: {} - {}&#x22;, status, body);
    }

    Ok(())
}
</pre>
<pre>
async fn get_difficulty_from_server() -&#x3E; Result&#x3C;u32&#x3E; {
    let client = reqwest::Client::new();
    let url = &#x22;http://localhost:8000/difficulty&#x22;;

    let res = client.get(url)
        .send()
        .await
        .context(&#x22;Failed to send request to get difficulty&#x22;)?;

    let difficulty_str = res.text().await
        .context(&#x22;Failed to read difficulty response&#x22;)?;
    let difficulty = difficulty_str.trim_start_matches(&#x22;Difficulty: &#x22;)
        .parse::&#x3C;u32&#x3E;()
        .context(&#x22;Failed to parse difficulty&#x22;)?;

    Ok(difficulty)
}

async fn display_difficulty() -&#x3E; Result&#x3C;()&#x3E; {
    let difficulty = get_difficulty_from_server().await
        .context(&#x22;Error retrieving difficulty from server&#x22;)?;

    println!(&#x22;Current Difficulty: {}&#x22;, difficulty);

    Ok(())
}

#[tokio::main]
async fn main() -&#x3E; Result&#x3C;()&#x3E; {
    loop {
        // Anzeige der aktuellen Schwierigkeit
        display_difficulty().await
            .context(&#x22;Error displaying difficulty&#x22;)?;

        // Hol die Schwierigkeit vom Server
        let difficulty = get_difficulty_from_server().await
            .context(&#x22;Error retrieving difficulty from server&#x22;)?;

        // Hol den letzten Block vom Server
        let previous_block = get_last_block_from_server().await
            .context(&#x22;Error retrieving last block from server&#x22;)?;

        let data = b&#x22;Block data&#x22;.to_vec();
        let new_block = mine_block(&#x26;previous_block, data, difficulty).await;

        send_block_to_server(&#x26;new_block).await
            .context(&#x22;Error sending block to server&#x22;)?;

        // Warte eine gewisse Zeit, bevor der n&#xE4;chste Block erstellt wird
        tokio::time::sleep(tokio::time::Duration::from_secs(0)).await; // Wartezeit erh&#xF6;ht
    }
}

</pre>
<p>Der Beitrag <a rel="nofollow" href="https://homepage-nach-preis.de/2024/09/06/simple-blockchain-beispiel-mit-miner/">Simple Blockchain Beispiel mit Miner</a> erschien zuerst auf <a rel="nofollow" href="https://homepage-nach-preis.de">Homepage nach Preis - Webseite erstellen lassen</a>. Geschrieben von <a rel="nofollow" href="https://homepage-nach-preis.de/author/homepageadmin/">Homepage-nach-Preis</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://homepage-nach-preis.de/2024/09/06/simple-blockchain-beispiel-mit-miner/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		<enclosure url="https://homepage-nach-preis.de/wp-content/uploads/2024/09/2024-09-06-18-38-00.mp4" length="41740699" type="video/mp4" />

			</item>
		<item>
		<title>HNP Empty Plugin &#8211; WordPress Demo Code</title>
		<link>https://homepage-nach-preis.de/2024/04/10/hnp-empty-plugin-wordpress-demo-code/</link>
					<comments>https://homepage-nach-preis.de/2024/04/10/hnp-empty-plugin-wordpress-demo-code/#respond</comments>
		
		<dc:creator><![CDATA[Homepage-nach-Preis]]></dc:creator>
		<pubDate>Wed, 10 Apr 2024 13:54:30 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Wordpress Code]]></category>
		<category><![CDATA[Beispiel]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Demo]]></category>
		<category><![CDATA[Empty]]></category>
		<category><![CDATA[Leeres]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[wordpress]]></category>
		<guid isPermaLink="false">https://homepage-nach-preis.de/?p=8186</guid>

					<description><![CDATA[<p>Das HNP Empty Plugin ist ein einfaches Demo-Plugin für WordPress, das entwickelt wurde, um grundlegende Funktionen eines Plugins zu demonstrieren. Es zeigt, wie man Styles und Skripte sowohl im Frontend als auch im Backend von WordPress einbindet. Außerdem bietet es eine Benutzeroberfläche zur Verwaltung von Plugin-Optionen über das WordPress-Dashboard. Der Plugin-Demo Code besitzt alle wichtigen Sicherheitsoptionen und Code-Qualitätsanforderungen, damit ein Plugin im offiziellen WordPress Verzeichnis aufgenommen wird. Zudem Funktionen, welche im Jahr 2024 auf dem neuesten Stand sind. Somit eine gute Grundlage für WordPress-Plugin-Entwickler. Geteste Kompatibilität: WordPress 6.5.2 und PHP 8.3. Das Plugin wird aber auch mit neueren und älteren PHP und WordPress Versionen kompatibel sein. Features: Frontend und Backend Styling: Das Plugin fügt sowohl dem Frontend als auch dem Backend von WordPress benutzerdefinierte CSS- und JavaScript-Dateien hinzu, um das Erscheinungsbild anzupassen. Plugin-Optionen: Es bietet eine einfache Möglichkeit, Plugin-Optionen über das WordPress-Dashboard zu konfigurieren, einschließlich Textfelder, Zahlenfelder, Farbwähler, Dropdown-Listen und Checkboxen. Shortcode: Das Plugin stellt einen Shortcode bereit, mit dem Benutzer die konfigurierten Optionen auf beliebigen Seiten oder Beiträgen anzeigen können. Sicherheitsmaßnahmen: Das Plugin implementiert Sicherheitsmaßnahmen wie Nonce-Überprüfung, um unerwünschte Zugriffe auf die Plugin-Einstellungen zu verhindern. &#160; Plugin-Download: [sdm_download id=&#8221;8187&#8243; fancy=&#8221;0&#8243;] Github: https://github.com/HNP-Christopher-Rohde/hnp_empty_wordpress_plugin Quellcode: &#60;?php /* Plugin Name: HNP Empty....</p>
<p>Der Beitrag <a rel="nofollow" href="https://homepage-nach-preis.de/2024/04/10/hnp-empty-plugin-wordpress-demo-code/">HNP Empty Plugin &#8211; WordPress Demo Code</a> erschien zuerst auf <a rel="nofollow" href="https://homepage-nach-preis.de">Homepage nach Preis - Webseite erstellen lassen</a>. Geschrieben von <a rel="nofollow" href="https://homepage-nach-preis.de/author/homepageadmin/">Homepage-nach-Preis</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Das HNP Empty Plugin ist ein einfaches Demo-Plugin für WordPress, das entwickelt wurde, um grundlegende Funktionen eines Plugins zu demonstrieren. Es zeigt, wie man Styles und Skripte sowohl im Frontend als auch im Backend von WordPress einbindet. Außerdem bietet es eine Benutzeroberfläche zur Verwaltung von Plugin-Optionen über das WordPress-Dashboard. Der Plugin-Demo Code besitzt alle wichtigen Sicherheitsoptionen und Code-Qualitätsanforderungen, damit ein Plugin im offiziellen WordPress Verzeichnis aufgenommen wird. Zudem Funktionen, welche im Jahr 2024 auf dem neuesten Stand sind. Somit eine gute Grundlage für WordPress-Plugin-Entwickler. Geteste Kompatibilität: WordPress 6.5.2 und PHP 8.3. Das Plugin wird aber auch mit neueren und älteren PHP und WordPress Versionen kompatibel sein. </p>
<p><strong>Features:</strong></p>
<ul>
<li><strong>Frontend und Backend Styling:</strong> Das Plugin fügt sowohl dem Frontend als auch dem Backend von WordPress benutzerdefinierte CSS- und JavaScript-Dateien hinzu, um das Erscheinungsbild anzupassen.</li>
<li><strong>Plugin-Optionen:</strong> Es bietet eine einfache Möglichkeit, Plugin-Optionen über das WordPress-Dashboard zu konfigurieren, einschließlich Textfelder, Zahlenfelder, Farbwähler, Dropdown-Listen und Checkboxen.</li>
<li><strong>Shortcode:</strong> Das Plugin stellt einen Shortcode bereit, mit dem Benutzer die konfigurierten Optionen auf beliebigen Seiten oder Beiträgen anzeigen können.</li>
<li><strong>Sicherheitsmaßnahmen:</strong> Das Plugin implementiert Sicherheitsmaßnahmen wie Nonce-Überprüfung, um unerwünschte Zugriffe auf die Plugin-Einstellungen zu verhindern.</li>
</ul>
<p>&nbsp;</p>
<p><strong>Plugin-Download:</strong> [sdm_download id=&#8221;8187&#8243; fancy=&#8221;0&#8243;]<br />
<strong>Github:</strong> <a href="https://github.com/HNP-Christopher-Rohde/hnp_empty_wordpress_plugin" target="_blank" rel="nofollow noopener">https://github.com/HNP-Christopher-Rohde/hnp_empty_wordpress_plugin</a><br />
<strong>Quellcode:</strong></p>
<pre>&lt;?php
/*
  Plugin Name: HNP Empty Plugin
  Description: Creates a Demo Plugin in WordPress
  Version: 2.0
  Author: HNP C.R. 
  Author URI: https://homepage-nach-preis.de/
  License: GPLv3
  License URI: https://www.gnu.org/licenses/gpl-3.0.html
 */

// Security check to prevent direct access to the plugin file
defined('ABSPATH') or die('No script kiddies please!');

// Function to enqueue the Frontend CSS and JS
function hnp_empty_plugin_frontend_scripts() {
    // Define a version number
    $version = '2.0';

    // Check if CSS is not already enqueued
    if (!wp_style_is('hnp_empty_plugin_frontend-css')) {
        // Enqueue CSS with the defined version
        wp_enqueue_style('hnp_empty_plugin_frontend-css', plugin_dir_url(__FILE__) . '/frontend/css/hnp_empty_plugin_frontend.css', array(), $version);
    }

    // Check if JavaScript is not already enqueued
    if (!wp_script_is('hnp_empty_plugin_frontend-js')) {
        // Enqueue JavaScript with the defined version
        wp_enqueue_script('hnp_empty_plugin_frontend-js', plugin_dir_url(__FILE__) . '/frontend/js/hnp_empty_plugin_frontend.js', array(), $version, true);
    }
}
add_action('wp_enqueue_scripts', 'hnp_empty_plugin_frontend_scripts');

// Function to enqueue Backend CSS and JS
function hnp_empty_plugin_backend_scripts() {
    // Define a version number
    $version = '2.0';

    // Check if CSS is not already enqueued
    if (!wp_style_is('hnp_empty_plugin_backend-css')) {
        // Enqueue CSS with the defined version
        wp_enqueue_style('hnp_empty_plugin_backend-css', plugin_dir_url(__FILE__) . '/backend/css/hnp_empty_plugin_backend.css', array(), $version);
    }

    // Check if JavaScript is not already enqueued
    if (!wp_script_is('hnp_empty_plugin_backend-js')) {
        // Enqueue JavaScript with the defined version
        wp_enqueue_script('hnp_empty_plugin_backend-js', plugin_dir_url(__FILE__) . '/backend/js/hnp_empty_plugin_backend.js', array(), $version, true);
    }
}
add_action('admin_enqueue_scripts', 'hnp_empty_plugin_backend_scripts');

// Function for Test - with load Options and Fallback
function hnp_empty_plugin_echo_func() {
    // Get option values
    $name = get_option('hnp_empty_plugin_name_field', 'Name');
    $number = get_option('hnp_empty_plugin_number_field', '12');
    $color = get_option('hnp_empty_plugin_color_field', '#ff0000');
    $description = get_option('hnp_empty_plugin_description_field', 'Im a Desc Field');
    $dropdown = get_option('hnp_empty_plugin_dropdown_field', 'option1');
    $checkbox = get_option('hnp_empty_plugin_checkbox_field', 0);

    // Echo option values
    echo '&lt;p&gt;Name Field: ' . esc_html($name) . '&lt;/p&gt;';
    echo '&lt;p&gt;Number Field: ' . esc_html($number) . '&lt;/p&gt;';
    echo '&lt;p&gt;Color Field: ' . esc_html($color) . '&lt;/p&gt;';
    echo '&lt;p&gt;Description Field: ' . esc_html($description) . '&lt;/p&gt;';
    echo '&lt;p&gt;Dropdown Field: ' . esc_html($dropdown) . '&lt;/p&gt;';
    echo '&lt;p&gt;Checkbox Field: ' . ($checkbox ? 'Enabled' : 'Disabled') . '&lt;/p&gt;';
}
add_shortcode('hnp_empty_plugin_echo_func', 'hnp_empty_plugin_echo_func');


// Function to add plugin options to the main menu
function hnp_empty_plugin_add_plugin_options_page() {
    // Check permission
    if (current_user_can('manage_options')) {
        add_menu_page(
            'HNP Empty Plugin Settings',
            'HNP Empty Plugin',
            'manage_options',
            'hnp-empty-plugin-settings',
            'hnp_empty_plugin_render_plugin_options_page',
            plugin_dir_url(__FILE__) . 'img/hnp-favi.png' 
        );
    }
}
add_action('admin_menu', 'hnp_empty_plugin_add_plugin_options_page');


// Function to render plugin options page
function hnp_empty_plugin_render_plugin_options_page() {
    ?&gt;
    &lt;div class="wrap hnp-empty-plugin-settings"&gt;
        &lt;h1&gt;HNP Empty Plugin Settings&lt;/h1&gt;
        &lt;form method="post" action="options.php"&gt;
            &lt;?php settings_fields('hnp_empty_plugin_settings_group'); ?&gt;
            &lt;?php do_settings_sections('hnp-empty-plugin-settings'); ?&gt;
            
            &lt;?php 
                // Add nonce
                wp_nonce_field('hnp_empty_plugin_settings_nonce', 'hnp_empty_plugin_settings_nonce'); 
            ?&gt;
            
            &lt;?php submit_button(); ?&gt;
        &lt;/form&gt;
    &lt;/div&gt;
    &lt;?php
}

// Function to register plugin options
function hnp_empty_plugin_register_plugin_options() {
    // Name
    add_settings_section(
        'hnp_empty_plugin_name_section',
        'Demo',
        'hnp_empty_plugin_demo_section_callback',
        'hnp-empty-plugin-settings'
    );

    // Name
    add_settings_field(
        'hnp_empty_plugin_name_field', 
        'Name Field', 
        'hnp_empty_plugin_name_field_callback', 
        'hnp-empty-plugin-settings', 
        'hnp_empty_plugin_name_section' 
    );

    // Number
    add_settings_field(
        'hnp_empty_plugin_number_field',
        'Number Field',
        'hnp_empty_plugin_number_field_callback',
        'hnp-empty-plugin-settings',
        'hnp_empty_plugin_name_section'
    );

    // Color
    add_settings_field(
        'hnp_empty_plugin_color_field',
        'Color Field',
        'hnp_empty_plugin_color_field_callback',
        'hnp-empty-plugin-settings',
        'hnp_empty_plugin_name_section'
    );

    // Description
    add_settings_field(
        'hnp_empty_plugin_description_field',
        'Description Field',
        'hnp_empty_plugin_description_field_callback',
        'hnp-empty-plugin-settings',
        'hnp_empty_plugin_name_section'
    );

    // Dropdown
    add_settings_field(
        'hnp_empty_plugin_dropdown_field',
        'Dropdown Field',
        'hnp_empty_plugin_dropdown_field_callback',
        'hnp-empty-plugin-settings',
        'hnp_empty_plugin_name_section'
    );

    // Checkbox
    add_settings_field(
        'hnp_empty_plugin_checkbox_field',
        'Checkbox Field',
        'hnp_empty_plugin_checkbox_field_callback',
        'hnp-empty-plugin-settings',
        'hnp_empty_plugin_name_section'
    );
}
add_action('admin_init', 'hnp_empty_plugin_register_plugin_options');
</pre>
<pre>
// Callback function for demo section
function hnp_empty_plugin_demo_section_callback() {
    echo 'This a Demo Plugin. Frontend-Shortcode: &amp;#x5B;hnp_empty_plugin_echo_func]&lt;/p&gt;';
}

// Callback function for name field
function hnp_empty_plugin_name_field_callback() {
    $value = get_option('hnp_empty_plugin_name_field', 'Name'); // Fallback value is 'Name'
    echo '&lt;input type="text" name="hnp_empty_plugin_name_field" value="' . esc_attr($value) . '" /&gt;';
}

// Callback functions for number fields
function hnp_empty_plugin_number_field_callback() {
    $value = get_option('hnp_empty_plugin_number_field', '12'); // Fallback value is '12'
    echo '&lt;input type="number" name="hnp_empty_plugin_number_field" value="' . esc_attr($value) . '" /&gt;';
}

// Callback function for Color Field
function hnp_empty_plugin_color_field_callback() {
    $value = get_option('hnp_empty_plugin_color_field', '#ff0000'); // Fallback value is red color
    echo '&lt;input type="color" name="hnp_empty_plugin_color_field" value="' . esc_attr($value) . '" /&gt;';
}

// Callback function for Description Field
function hnp_empty_plugin_description_field_callback() {
    $value = get_option('hnp_empty_plugin_description_field', 'Im a Desc Field'); // Fallback value is 'Im a Desc Field'
    echo '&lt;textarea name="hnp_empty_plugin_description_field"&gt;' . esc_html($value) . '&lt;/textarea&gt;';
}

// Callback function for dropdown field
function hnp_empty_plugin_dropdown_field_callback() {
    $value = get_option('hnp_empty_plugin_dropdown_field', 'option1'); // Fallback value is 'option1'
    ?&gt;
    &lt;select name="hnp_empty_plugin_dropdown_field"&gt;
        &lt;option value="option1" &lt;?php selected($value, 'option1'); ?&gt;&gt;Option 1&lt;/option&gt;
        &lt;option value="option2" &lt;?php selected($value, 'option2'); ?&gt;&gt;Option 2&lt;/option&gt;
        &lt;option value="option3" &lt;?php selected($value, 'option3'); ?&gt;&gt;Option 3&lt;/option&gt;
    &lt;/select&gt;
    &lt;?php
}

// Callback function for checkbox field
function hnp_empty_plugin_checkbox_field_callback() {
    $value = get_option('hnp_empty_plugin_checkbox_field', 0); // Fallback value is 0 (not checked)
    ?&gt;
    &lt;label for="hnp_empty_plugin_checkbox_field"&gt;
        &lt;input type="checkbox" name="hnp_empty_plugin_checkbox_field" id="hnp_empty_plugin_checkbox_field" value="1" &lt;?php checked($value, 1); ?&gt;&gt;
        Enable Checkbox
    &lt;/label&gt;
    &lt;?php
}

// Security measures: Nonce verification and save options
function hnp_empty_plugin_register_security_options() {
    // Check if the current page is our plugin options page
    if (isset($_POST['option_page']) &amp;&amp; $_POST['option_page'] == 'hnp_empty_plugin_settings_group') {
        // Check if the nonce is set and valid
        if (!isset($_POST['hnp_empty_plugin_settings_nonce']) || !wp_verify_nonce($_POST['hnp_empty_plugin_settings_nonce'], 'hnp_empty_plugin_settings_nonce')) {
            // Unauthorized request, do not save options
            wp_die('Unauthorized request.'); // Output error message for unauthorized requests
        }

        // Save options
        update_option('hnp_empty_plugin_name_field', $_POST['hnp_empty_plugin_name_field']);
        update_option('hnp_empty_plugin_number_field', sanitize_text_field($_POST['hnp_empty_plugin_number_field']));
        update_option('hnp_empty_plugin_color_field', sanitize_text_field($_POST['hnp_empty_plugin_color_field']));
        update_option('hnp_empty_plugin_description_field', sanitize_textarea_field($_POST['hnp_empty_plugin_description_field']));
        update_option('hnp_empty_plugin_dropdown_field', sanitize_text_field($_POST['hnp_empty_plugin_dropdown_field']));
        update_option('hnp_empty_plugin_checkbox_field', isset($_POST['hnp_empty_plugin_checkbox_field']) ? 1 : 0);
    }
}
add_action('admin_init', 'hnp_empty_plugin_register_security_options');

// Register plugin options and security measures
function hnp_empty_plugin_register_settings() {
    // Register setting and sanitize callback
    register_setting('hnp_empty_plugin_settings_group', 'hnp_empty_plugin_name_field');
    register_setting('hnp_empty_plugin_settings_group', 'hnp_empty_plugin_number_field');
    register_setting('hnp_empty_plugin_settings_group', 'hnp_empty_plugin_color_field');
    register_setting('hnp_empty_plugin_settings_group', 'hnp_empty_plugin_description_field');
    register_setting('hnp_empty_plugin_settings_group', 'hnp_empty_plugin_dropdown_field');
    register_setting('hnp_empty_plugin_settings_group', 'hnp_empty_plugin_checkbox_field');
}
add_action('admin_init', 'hnp_empty_plugin_register_settings');


// Security measures: Nonce verification for options update
function hnp_empty_plugin_validate_settings($input) {
    return $input; // Simply return the input, no further validation here
}

</pre>
<p>Der Beitrag <a rel="nofollow" href="https://homepage-nach-preis.de/2024/04/10/hnp-empty-plugin-wordpress-demo-code/">HNP Empty Plugin &#8211; WordPress Demo Code</a> erschien zuerst auf <a rel="nofollow" href="https://homepage-nach-preis.de">Homepage nach Preis - Webseite erstellen lassen</a>. Geschrieben von <a rel="nofollow" href="https://homepage-nach-preis.de/author/homepageadmin/">Homepage-nach-Preis</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://homepage-nach-preis.de/2024/04/10/hnp-empty-plugin-wordpress-demo-code/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Ajax und WP-Ajax verstehen &#8211; Code Beispiel</title>
		<link>https://homepage-nach-preis.de/2024/04/06/ajax-und-wp-ajax-verstehen-code-beispiel/</link>
					<comments>https://homepage-nach-preis.de/2024/04/06/ajax-und-wp-ajax-verstehen-code-beispiel/#respond</comments>
		
		<dc:creator><![CDATA[Homepage-nach-Preis]]></dc:creator>
		<pubDate>Sat, 06 Apr 2024 04:00:17 +0000</pubDate>
				<category><![CDATA[Webdesign]]></category>
		<category><![CDATA[Wordpress Code]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Beispiel]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[verstehen]]></category>
		<category><![CDATA[wordpress]]></category>
		<category><![CDATA[Wp-Ajax]]></category>
		<guid isPermaLink="false">https://homepage-nach-preis.de/?p=8156</guid>

					<description><![CDATA[<p>AJAX (Asynchronous JavaScript and XML) ist eine Technik, die es ermöglicht, Daten zwischen dem Browser des Benutzers und dem Server auszutauschen, ohne die gesamte Webseite neu zu laden. Dies ermöglicht eine verbesserte Benutzererfahrung, da Inhalte dynamisch aktualisiert werden können, ohne die Seite zu verlassen. Stellen wir uns ein Restaurant vor und einen Kunden, der Kunde erhält seine Bestellung, ohne zum Restaurant fahren zu müssen, also vergleichbar mit einem Lieferanten. AJAX ist die Verbindung zwischen Server und Client, ein praktischer Helfer. Die grundlegende Arbeitsweise von AJAX besteht darin, dass der Browser mithilfe von JavaScript eine HTTP-Anfrage an den Server sendet. Der Server verarbeitet dann die Anfrage und sendet eine Antwort zurück, die vom JavaScript-Code auf der Client-Seite verarbeitet wird. In der Regel werden AJAX-Anfragen verwendet, um Daten im Hintergrund zu laden, Benutzeraktionen zu verarbeiten oder mit einem Server zu kommunizieren, ohne dass die Seite neu geladen werden muss. Dies kann beispielsweise bei der Validierung von Formularen, dem Laden von zusätzlichen Inhalten oder der Aktualisierung von Benutzerdaten nützlich sein. Um AJAX in einer Webseite zu implementieren, wird normalerweise JavaScript verwendet, um die Anfrage zu senden, und auf der Serverseite wird die Anfrage mit einer Programmiersprache wie PHP oder Python verarbeitet. In WordPress....</p>
<p>Der Beitrag <a rel="nofollow" href="https://homepage-nach-preis.de/2024/04/06/ajax-und-wp-ajax-verstehen-code-beispiel/">Ajax und WP-Ajax verstehen &#8211; Code Beispiel</a> erschien zuerst auf <a rel="nofollow" href="https://homepage-nach-preis.de">Homepage nach Preis - Webseite erstellen lassen</a>. Geschrieben von <a rel="nofollow" href="https://homepage-nach-preis.de/author/homepageadmin/">Homepage-nach-Preis</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>AJAX (Asynchronous JavaScript and XML) ist eine Technik, die es ermöglicht, Daten zwischen dem Browser des Benutzers und dem Server auszutauschen, ohne die gesamte Webseite neu zu laden. Dies ermöglicht eine verbesserte Benutzererfahrung, da Inhalte dynamisch aktualisiert werden können, ohne die Seite zu verlassen. Stellen wir uns ein Restaurant vor und einen Kunden, der Kunde erhält seine Bestellung, ohne zum Restaurant fahren zu müssen, also vergleichbar mit einem Lieferanten. AJAX ist die Verbindung zwischen Server und Client, ein praktischer Helfer. </p>
<p>Die grundlegende Arbeitsweise von AJAX besteht darin, dass der Browser mithilfe von JavaScript eine HTTP-Anfrage an den Server sendet. Der Server verarbeitet dann die Anfrage und sendet eine Antwort zurück, die vom JavaScript-Code auf der Client-Seite verarbeitet wird.</p>
<p>In der Regel werden AJAX-Anfragen verwendet, um Daten im Hintergrund zu laden, Benutzeraktionen zu verarbeiten oder mit einem Server zu kommunizieren, ohne dass die Seite neu geladen werden muss. Dies kann beispielsweise bei der Validierung von Formularen, dem Laden von zusätzlichen Inhalten oder der Aktualisierung von Benutzerdaten nützlich sein.</p>
<p>Um AJAX in einer Webseite zu implementieren, wird normalerweise JavaScript verwendet, um die Anfrage zu senden, und auf der Serverseite wird die Anfrage mit einer Programmiersprache wie PHP oder Python verarbeitet.</p>
<p>In WordPress wird AJAX häufig verwendet, um dynamische Inhalte in Themes und Plugins zu laden, ohne die Seite neu zu laden. WordPress bietet spezielle Funktionen und Hooks für die Verarbeitung von AJAX-Anfragen, was die Implementierung erleichtert. Hierzu ein praktisches Beispiel:<br />
<strong> WordPress:</strong><br />
<strong>Javascript:</strong></p>
<pre>
document.addEventListener(&#x22;DOMContentLoaded&#x22;, function() {
    var hnpAjaxButton = document.getElementById(&#x22;hnp_ajax_button&#x22;);
    
    hnpAjaxButton.addEventListener(&#x22;click&#x22;, function() {
        var xhr = new XMLHttpRequest();
        xhr.open(&#x22;POST&#x22;, ajax_object.ajax_url, true);
        xhr.setRequestHeader(&#x22;Content-Type&#x22;, &#x22;application/x-www-form-urlencoded&#x22;);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 &#x26;&#x26; xhr.status === 200) {
                alert(&#x22;Server sagt: &#x22; + xhr.responseText);
            }
        };
        xhr.send(&#x22;action=hnp_ajax_funktion&#x22;);
    });
});
</pre>
<p><strong>PHP</strong></p>
<pre>
add_action(&#x27;wp_enqueue_scripts&#x27;, &#x27;hnp_ajax_scripts&#x27;);
function hnp_ajax_scripts() {
    wp_enqueue_script(&#x27;hnp-ajax-script&#x27;, get_stylesheet_directory_uri() . &#x27;/js/hnp-ajax-script.js&#x27;, array(), &#x27;1.0&#x27;, true);
    wp_localize_script(&#x27;hnp-ajax-script&#x27;, &#x27;ajax_object&#x27;, array(&#x27;ajax_url&#x27; =&#x3E; admin_url(&#x27;admin-ajax.php&#x27;)));
}

add_action(&#x27;wp_ajax_hnp_ajax_funktion&#x27;, &#x27;meine_ajax_callback&#x27;);
add_action(&#x27;wp_ajax_nopriv_hnp_ajax_funktion&#x27;, &#x27;meine_ajax_callback&#x27;);
function meine_ajax_callback() {
    echo &#x27;Hallo von AJAX!&#x27;;
    die();
}
</pre>
<p><strong>HTML:</strong></p>
<pre>
&#x3C;button id=&#x22;hnp_ajax_button&#x22;&#x3E;Klick mich f&#xFC;r eine Begr&#xFC;&#xDF;ungsnachricht!&#x3C;/button&#x3E;
</pre>
<p><strong>ODER Universal:</strong></p>
<pre>
&#x3C;!DOCTYPE html&#x3E;
&#x3C;html lang=&#x22;en&#x22;&#x3E;
&#x3C;head&#x3E;
    &#x3C;meta charset=&#x22;UTF-8&#x22;&#x3E;
    &#x3C;meta name=&#x22;viewport&#x22; content=&#x22;width=device-width, initial-scale=1.0&#x22;&#x3E;
    &#x3C;title&#x3E;AJAX Beispiel&#x3C;/title&#x3E;
&#x3C;/head&#x3E;
&#x3C;body&#x3E;
    &#x3C;button id=&#x22;hnp_ajax_button&#x22;&#x3E;Klick mich f&#xFC;r eine Begr&#xFC;&#xDF;ungsnachricht!&#x3C;/button&#x3E;

    &#x3C;script&#x3E;
        document.addEventListener(&#x22;DOMContentLoaded&#x22;, function() {
            var hnpAjaxButton = document.getElementById(&#x22;hnp_ajax_button&#x22;);
            
            hnpAjaxButton.addEventListener(&#x22;click&#x22;, function() {
                var xhr = new XMLHttpRequest();
                xhr.open(&#x22;POST&#x22;, &#x22;server.php&#x22;, true); // Hier &#x22;server.php&#x22; durch die URL des Servers ersetzen, der die AJAX-Anfrage verarbeitet
                xhr.setRequestHeader(&#x22;Content-Type&#x22;, &#x22;application/x-www-form-urlencoded&#x22;);
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 &#x26;&#x26; xhr.status === 200) {
                        alert(&#x22;Server sagt: &#x22; + xhr.responseText);
                    }
                };
                xhr.send(&#x22;action=hnp_ajax_funktion&#x22;);
            });
        });
    &#x3C;/script&#x3E;
&#x3C;/body&#x3E;
&#x3C;/html&#x3E;

</pre>
<p>Der Beitrag <a rel="nofollow" href="https://homepage-nach-preis.de/2024/04/06/ajax-und-wp-ajax-verstehen-code-beispiel/">Ajax und WP-Ajax verstehen &#8211; Code Beispiel</a> erschien zuerst auf <a rel="nofollow" href="https://homepage-nach-preis.de">Homepage nach Preis - Webseite erstellen lassen</a>. Geschrieben von <a rel="nofollow" href="https://homepage-nach-preis.de/author/homepageadmin/">Homepage-nach-Preis</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://homepage-nach-preis.de/2024/04/06/ajax-und-wp-ajax-verstehen-code-beispiel/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
