weixin_33670786 2017-02-21 13:14 采纳率: 0%
浏览 54

从PHP更新DIV标签

I'm a new developer. I've read a lot of question all around about my topic, and I've seen a lot of interesting answers, but unfortunately, I cannot find a way to resolve mine. I have a simple form in HTML and <div id="comment"></div> in it (empty if there is nothing to pass to the user). This DIV is supposed to give updates to the user, like Wrong Username or Password! when it's the case. The form is treated via PHP and MySQL.

    ...
    $result = mysqli_query($idConnect, $sql);

    if (mysqli_num_rows($result) > 0) {

        mysqli_close($idConnect);
        setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
        header("Location: ../main.html");
    } else {
        //Please update the DIV tag here!! 
    }
    ...

I tried to "read" PHP from jQuery (with AJAX), but whether I didn't have the solution, or it cannot be done that way... I used this in jQuery (#login is the name of the form):

$("#login").submit(function(e){
    var postData = $(this).serializeArray();
    var formURL = $(this).attr("action");
    $.ajax({
        url : formURL,
        type: "POST",
        data : postData,
        success:function(data) {
            $("#comment").replaceWith(data);  // You can use .replaceWith or .html depending on the markup you return
        },
        error: function(errorThrown) {
            $("#comment").html(errorThrown);
        }
    });
    e.preventDefault();    //STOP default action
    e.unbind();
});

But I'd like to update the DIV tag #comment with some message if the credentials are wrong. But I have no clue how to update that DIV, considering PHP is treating the form...

Can you help please ?

Thanks in advance ! :)

  • 写回答

2条回答 默认 最新

  • weixin_33713503 2017-02-21 13:17
    关注

    In order for AJAX to work, the PHP must echo something to be returned from the AJAX call:

    if (mysqli_num_rows($result) > 0) {
    
            mysqli_close($idConnect);
            setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
            echo 'good';
        } else {
            //Please update the DIV tag here!!
            echo 'There is a problem with your username or password.'; 
        }
    

    But this will not show up in error: function because that function is used when AJAX itself is having a problem. This text will be returned in the success callback and so you must update the div there:

    success:function(data) {
            if('good' == data) {
                // perform redirect
                window.location = "main.html";
            } else {
                // update div
                $("#comment").html(data);
            }
        },
    

    In addition, since you're calling the PHP with AJAX, the header("Location: ../main.html"); will not work. You will need to add window.location to your success callback dependent upon the status.

    评论

报告相同问题?