Webentwicklung – die neusten Beiträge

PHP Upload funktioniert auf PC aber nicht aufm Handy?

Hallo,

dieser Code funktioniert nicht auf Handy aber auf dem PC, hat wer tipps?

Clientseite (JavaScript):
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script></head>
<body>
<form id="fileUploadForm" enctype="multipart/form-data">
    <input type="file" name="file" id="fileInput" required>
    <button type="button" id="uploadButton">Hochladen</button>
</form>


<script>
    $(document).ready(function(){
        $('#uploadButton').on('click touchend', function(){
            var formData = new FormData($('#fileUploadForm')[0]);
            $.ajax({
                url: 'https://sub-upload.main.de/upload.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response){
                    console.log(response);
                    alert(response);
                },
                error: function(xhr, status, error){
                    alert(error + xhr.status);
                }
            });
        });
    });


</script>
</body>
</html>
Serverseite (upload.php):
<?php
$targetDirectory = '../uploads/';
header("Access-Control-Allow-Origin: https://sub.main.de");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
if (!file_exists($targetDirectory)) {
    mkdir($targetDirectory, 0777, true);
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $targetFile = $targetDirectory . basename($_FILES['file']['name']);
    if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
        echo 'Die Datei wurde erfolgreich hochgeladen.';
    } else {
        echo 'Beim Hochladen der Datei ist ein Fehler aufgetreten.';
    }
} else {
    echo 'Keine Datei zum Hochladen gefunden.';
}
?>
HTML, Webseite, JavaScript, HTML5, Code, Datenbank, JQuery, MySQL, PHP, Programmiersprache, Webdesign, Webentwicklung

Warum kann ich meinen HTML- Code nicht mit meinem Python- Code verbinden?

Hallo,

ich wollte meinen Python- Code mit meinem HTML- Code verbinden, damit, wenn mein Wake- Word "Luna" erkannt wurde, ein div in der Datei index.html seine Farbe ändert. Hier ist der Code:

Python:

from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'luna_secret1984773249523'
socketio = SocketIO(app)


@socketio.on('connect')
def handle_connect():
    emit('message', {'data': 'Connected'})


@socketio.on('start_listening')
def start_listening():
    if detect_wake_word():
        emit('color_change', {'color': 'red'})


@app.route('/')
def index():
    return render_template('output.html')

HTML /CSS:

... #color_div {
    width: 100%;
    height: 100%;
    position: absolute;
    background-color: green;
}    
</style>
</head>
<body>
<div id="color_div"></div>

JavaScript:

... // FLASK
        var socket = io();

        socket.on('connect', function() {
            socket.emit('start_listening');
        });

        socket.on('color_change', function(msg) {
            document.getElementById('color_div').style.backgroundColor = msg.color;
        });
</script>
</body>
</html>
    """
    with open("output.html", "w") as html_file:
        html_file.write(html_content)

    return "output.html"

Wenn ich den Code aber ausführe und "Luna" sage, ändert der Div nicht seine Farbe. Woran liegt das?

Freundliche Grüsse

HTML, Webseite, CSS, JavaScript, HTML5, Code, Programmiersprache, Python, Webentwicklung, Frontend, Python 3, Flask

Warum funktioniert mein Websockets- Server nicht?

Hallo,

ich möchte mithilfe von Websockets über JS auf Python zugreifen, das ist mein Code:

Python:

def send_message_to_browser(message):
    url = "http://localhost:8000/?wake_word=luna"
    try:
        response = requests.get(url)
        if response.status_code == 200:
            print("Nachricht an den Browser gesendet:", message)
        else:
            print("Fehler beim Senden der Nachricht an den Browser")
    except requests.RequestException as e:
        print("Fehler beim Senden der Nachricht an den Browser:", e)

JavaScript:

// WEBSOCKET
var socket = new WebSocket('ws://localhost:8000/?wake_word=luna');

// Debugging-Ausgabe zur Überprüfung der Verbindung
console.log("WebSocket wird hergestellt...");

// Ereignisbehandlungsfunktion für Verbindungsherstellung
socket.onopen = function(event) {
    // Debugging-Ausgabe zur Bestätigung der erfolgreichen Verbindung
    console.log("WebSocket-Verbindung hergestellt.");
};

// Ereignisbehandlungsfunktion für Nachrichtenempfang
socket.onmessage = function(event) {
    // Nachricht vom Server erhalten
    var message = event.data;

    // Debugging-Ausgabe
    console.log("Nachricht empfangen:", message);

    // Überprüfen, ob die empfangene Nachricht "luna" ist
    if (message === "luna") {
        // Ändern der Hintergrundfarbe der Div mit der ID "luna_wake_word" auf Rot
        $('#luna_wake_word').css("background-color", "red");
    }
};

// Fehlerbehandlungsfunktion für WebSocket-Verbindung
socket.onerror = function(error) {
    console.error('WebSocket Error: ', error);
};

// Schließen der WebSocket-Verbindung
function closeWebSocket() {
    socket.close();
}

Doch immer, wenn ich das Programm starte und in die Konsole schaue kommt dieser Fehler:

WebSocket wird hergestellt...

index.html?_ijt=bj6j8vutnl8e16bhrbgfck9djq&_ij_reload=RELOAD_ON_SAVE:1929 WebSocket connection to 'ws://localhost:8000/?wake_word=luna' failed: 

(anonym) @ index.html?_ijt=bj6j8vutnl8e16bhrbgfck9djq&_ij_reload=RELOAD_ON_SAVE:1929

index.html?_ijt=bj6j8vutnl8e16bhrbgfck9djq&_ij_reload=RELOAD_ON_SAVE:1957 WebSocket Error: Event {isTrusted: true, type: 'error', target: WebSocket, currentTarget: WebSocket, eventPhase: 2, …}

Kann mir jemand helfen?

Freundliche Grüsse

HTML, Webseite, JavaScript, HTML5, Code, Programmiersprache, Python, Webentwicklung, Python 3

Warum wird meine Verbindung abgelehnt (Domain)?

Homepage, Online-Shop, HTML, Webseite, Domain, Webentwicklung, Webhosting, Shopify, shopify-store

Wie kann ich den Fehler beheben?

const http = require('http');
const fs = require('fs');
const mysql = require("mysql2");

var db  = mysql.createConnection({
    host : "localhost",
    user : "root",
    password : "passwort",
    database : "test-datenbank"
});


db.connect(function (error){
    if (error) throw error;
    console.log("Connected!")
    var sql = "INSERT INTO benutzer (username) VALUES ('Beispiel')";
    db.query(sql, function (error,result){
        if(error) throw error;
        console.log("1 record inserted");
    });
    sql="SELECT * FROM benutzer"
    
    db.query(sql,function(error,result){
        if (error) throw error;
        console.log(result);

    });
});

const server = http.createServer((req,res) => {
    const url = req.url;
    const method = req.method;
    

    if ( url === "/"){
    res.setHeader("key","value");
    res.setHeader("Content-Type","text/html");
    res.write('</html><body>');
    res.write('<h1>Main</h1>');
    res.write('<h1><form action="/register" method="post"> <input type="text" name="Username"><br><button type="submit">Click</button></form></h1>');
    res.write("</body></html>");
    res.end()
    return;
    }

    if (url === "/register"){
         
        const reqBody = []
         req.on('data', (chunk)=>{
            console.log(chunk);
            reqBody.push(chunk);
     });
        
     req.on('end', () => {
        console.log(reqBody);
        const parsed = Buffer.concat(reqBody).toString();
        console.log(parsed);
        const user = parsed.split('=')[1];
        console.log(user)
        
        // funktioniert nicht 
        sql = 'INSERT INTO benutzer (username) VALUES ?, user;
        db.query(sql,function(error,result){
            if (error) throw error;
            console.log(result);
        });



});
        
        
        res.setHeader("key","value");
        res.setHeader("Content-Type","text/html");
        res.write('</html>');
        res.write('<body><h1>Registriert</h1></body>');
        res.write("</html>");
        res.end()
        return;

    }
    
}) 



server.listen(1337);

Der Fehler lautet wie folgt:

code: 'ER_PARSE_ERROR',

 errno: 1064,

 sqlState: '42000',

 sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1",

 sql: 'INSERT INTO benutzer (username) VALUES',

 fatal: true

SQL, Webentwicklung, node.js

Meistgelesene Beiträge zum Thema Webentwicklung