在提交信息后,我如何成功重定向到我的.js文件(reactjs)而不是我的php文件?

As of now, I'm successfully inserting information into the database (SQL, phpMyAdmin) via Home.js but the problem is that every time the user enters information & hits submit, it gets redirected to my demo.php file instead of Next.js.

In other words, how can I make it so that upon the user information successfully entering the database and go to the next page? (Next.js)?

I know <form action="http://localhost/demo_react/api/demo.php" method={"POST"} encType="multipart/form-data"> will inevitably take me to demo.php but if I don't use this, then nothing gets submitted to my db.

What am I doing wrong and how can I fix this?

Here's Home.js:

import React, { Component } from 'react';
import Next from '../Home/Next';

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            show: false
        };
        this.getPHP = this.getPHP.bind(this);
    }

    getPHP(e) {
        this.setState({show: true});
        let formData = new FormData();
        fetch(`http://localhost/demo_react/api/demo.php`, {
            method: 'POST',
            body: formData
        }).then(res => res.json())
            .then(response => {
                console.log('response');
                console.log(response);
                e.preventDefault();
            });
    }

    render() {
        const goNext = this.state.show;
        if(goNext) {
            return <Next/>;
        }
        return (
            <div>
                <form action="http://localhost/demo_react/api/demo.php" method={"POST"} encType="multipart/form-data">
                    <div className="form-group">
                        <label htmlFor="username">Email</label>
                        <input className="form-control" type="text" name="username"/>
                    </div>

                    <div className="form-group">
                        <label htmlFor="password">Password</label>
                        <input className="form-control" type="password" name="password"/>
                    </div>
                    <input className="btn btn-primary" type="submit" value="Login" onSubmit={e => this.getPHP(e)} name={"submit"}/>
                </form>
            </div>
        );
    }
}

export default Home;

Here's demo.php:

$connection = mysqli_connect("localhost", "root", "", "loginapp");
$username = $_POST['username'];
$password = $_POST['password'];


if(isset($_POST['submit'])) {
    $query = "INSERT INTO users(username, password) ";
    $query .= " VALUES('$username', '$password')";

    $result = mysqli_query($connection, $query);

    if (!$result) {
        die("Query failed" . mysqli_error($connection));
    } else {
        echo "check database";
    }
}

1个回答

Do not use a type="submit" button. Use a type="button" or a <button>. If your form didn't have a submit, the problem is solved.

Obviously, in your JS code you need to send the information. You can collect it and send to demo.php without triggering form submit. I'll show you a basic example for doing it.

    var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
    var user = (document.getElementById(form).username) ? encodeURIComponent(document.getElementById(form).username.value) : '';
    var pass = (document.getElementById(form).password) ? encodeURIComponent(document.getElementById(form).password.value) : '';
    var data = 'username=' + user + '&password=' + pass;
    request.open('POST', document.getElementById(form).action, false);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset:UTF-8");
    request.setRequestHeader("Content-length", data.length);
    request.send(data);
    if (request.status == 200) {
            alert('Send OK.');
    } else {
            alert('Send error.');
    }

The included snippet get the URL to send information from the form action itself. You can optimize the code a lot probably, but it's a starting point. This code uses plain JS, you can change it to jQuery for example (jQuery version its shorter for example).

Also, if you need to eventually do a redirect, use a JS redirect instead.

douchong8393
douchong8393 喔好吧! 我明白你的意思了
接近 2 年之前 回复
douchong4730
douchong4730 这是一些基于您的需求。 想想如果你没有在同一个函数中获得代码,你可以重用代码。 如果需要重用它,请使用多个函数。 如果在相同的位置处理所有相同的变量/表单,则只将所有代码集成到一个函数中。
接近 2 年之前 回复
dtuy84033
dtuy84033 我应该摆脱我现在拥有的东西并把它放在我的getPHP()方法中吗?
接近 2 年之前 回复
dougang6821
dougang6821 我编写了一个响应示例,用于从JS代码发送信息。
接近 2 年之前 回复
donglv6960
donglv6960 哦,好吧,我明白你的意思了。 我刚把它改成了<按钮>请你用我的代码向我展示一个工作示例? 我已经坚持这么久了:(
接近 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐