简体   繁体   中英

How to get value from mysql, back to front end and used in a url

I am having trouble getting all the information I need back from a PHP script in response to an AJAX request made from a web page.

I have a front-end form:

<form method="post" id="register-form">
    <input class="form-control" id="firstname" name="first name" placeholder="Fornavn" type="text" />
    <button type="submit" class="btn btn-success" name="btn-save" id="btn-submit">
        Next page &nbsp; <i class="fa fa-arrow-right"></i>  
    </button>

which uses AJAX to post the data:

function submitForm(){
    $.ajax({
        type : 'POST',
        async: false, // NEW
        url  : 'register.php',
        data : $("#register-form").serialize(),
        dataType: 'json', 
        success :  function(data){
            if ( data.status==='success' ) {
                $("#btn-submit").html('<span class="fa fa-spinner fa-spin"></span> &nbsp; Saving  ...');
                $('#btn-submit').attr('disabled', 'disabled');
                $(".reg-form").fadeOut(500);
                $(".ChooseProductForm").fadeIn(500);
            }

        });
        return false;
    }

which after a successful response ends up displaying two link buttons:

<a href="goHome.php?userID=XX" class="btn btn-buy-now" role="button">Go home</a>
<a href="goAway.php?userID=XX" class="btn btn-buy-now" role="button">Go Away</a>

In the link href values, XX are placeholder charactersfor a $LastInsertedID value generated in PHP.

My PHP file:

<?php
$response = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $user_firstname         = trim_inputs($_POST['firstname']);
    $user_joining_date      = date('Y-m-d H:i:s');
    $response['status'] = 'success';
    $SaveData = "INSERT INTO Users (firstname, joined)
                VALUES ('".$user_firstname."', '".$user_joining_date."' )";

    if (mysqli_query($link, $SaveData)) {
        $LastInsertedID = mysqli_insert_id($link);
    } else {
        $response['status'] = 'error';
        //echo "Error: " . $SaveData . "<br>" . mysqli_error($link);
    }
    echo json_encode($response);
}
?>

Everything works just like it should, but can't understand how to get the $LastInsertedID value back to front-end to those two buttons.

I know there is an array for $response, but how to get the value back. Also displaying a message like:

$response['message'] = 'Welcome user';  

I can get out, but if I then add URL or < a href... tag into that message, nothing would be displayed.

Thanks for reading this question, hopefully it is understandable and maybe someone could help out :-)

Thanks in advance!

Send the new ID back:

if (mysqli_query($link, $SaveData)) {
    $LastInsertedID = mysqli_insert_id($link);
    $response['userId'] = $LastInsertedID;
} else {
    $response['status'] = 'error';
}

Use that ID:

success :  function(data)
{ 
    if ( data.status==='success' ) {
        $("#btn-submit").html('<span class="fa fa-spinner fa-spin"></span> &nbsp; Saving  ...');
        $('#btn-submit').attr('disabled', 'disabled');
        $(".reg-form").fadeOut(500);
        $(".ChooseProductForm").fadeIn(500);
        $("#id-of-go-away-button").attr("href", "goAway.php?userId=" + data.userId);
        $("#id-of-go-home-button").attr("href", "goHome.php?userId=" + data.userId);
    }
}

Small changes to the javascript. I moved the code to display the spinner and tell the user you are saving to before the ajax call. Then I added code to get the new ID from the data returned by the ajax call, and a mock up of putting into a field.

Javascript Code:

function submitForm(){
    $("#btn-submit").html('<span class="fa fa-spinner fa-spin"></span> &nbsp; Saving...');
    $('#btn-submit').attr('disabled', 'disabled');
    $.ajax(
        {
            type : 'POST',
            async: false, // NEW
            url  : 'register.php',
            data : $("#register-form").serialize(),
            dataType: 'json', 
            success :  function(data) { 
                if ( data.status==='success' ) {
                    $("#btn-submit").html('Saved.');
                    $(".reg-form").fadeOut(500);
                    $(".ChooseProductForm").fadeIn(500);
                    var new_id = data.new_id;
                    $("#field to hold the new id").val(new_id);
                }
            }
        }
    );
    return false;
}

On the server, we just need to add the new id to the data returned to the caller.

PHP Code:

<?php
    $response = array();
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $user_firstname = trim_inputs($_POST['firstname']);
        $user_joining_date = date('Y-m-d H:i:s');
        $response['status'] = 'success';
        $response['error_message'] = "";
        $SaveData = "INSERT INTO Users (firstname, joined) VALUES ('".$user_firstname."', '".$user_joining_date."' )";

        if (mysqli_query($link, $SaveData)) {
            $LastInsertedID = mysqli_insert_id($link);
            $response['new_id'] = $LastInsertedID;
            $response['message'] = "Welcome new user!";
        } else {
            $response['status'] = 'error';
            $response['error_message'] = $SaveData . "<br>" . mysqli_error($link);
        }
        echo json_encode($response);
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM