简体   繁体   中英

How to pass user input value from a PHP page to HTML page using AJAX

I have a course table in the database which stores course information (ie code, name, date and description). Admin is allowed to update the course information. Let's assume that a course information is already in my database and the admin intends to update the course info.

When he heads to the Update page (pls see managemodule.php), my page will show him a dropdown options with a list of courses that are in the database. He will then choose a particular course from the dropdown list and then the course information will be shown (achieved thru' ajax) in different HTML input fields (info is output thru. the placeholder attr.).

What I want to achieve here is that, admin can update whatever info they want in the input fields directly, and when he presses 'update', these data will be sent over and update in my database.

However I failed to do so. I know it's the problem of the ajax code in managemodule.js. The course table in the database has 4 columns which is code, name, date and description

managemodule.php:

<form id="moduleform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <h2 class="fs-title">Module Info Update</h2>
    <p>Please select a module for more information:</p><br />

    <select id="modulelist" name="module" onchange="showModuleInfo(this.value)">
        <option>-- Select a module --</option>
        <option value="CS2102">Database Systems</option>   ***hard coded here for simplicity*****
    </select>

<?php    ****This php part is not updating my course table********
            if(isset($_POST['update']))
            {   
                mysql_query("UPDATE module SET code = '".$_POST['update_moduleCode']."' ");
            }
?>


    <div id="moduleinfo"><b><-- Module info will be listed here --></b></div>   
</form>

managemodule.js:

function showModuleInfo(str)
{
    if (str == "")
    {
        document.getElementById("moduleinfo").innerHTML = "";
        return;
    } 
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            document.getElementById("moduleinfo").innerHTML = xmlhttp.responseText;
        }
    }

    xmlhttp.open("GET","moduleinfo.php?q="+str,true);
    xmlhttp.send();
}

moduleinfo.php

    session_start();

    $q = $_GET['q'];
    $result = mysql_query("SELECT * FROM module WHERE code = '".$q."'");

    while($row = mysql_fetch_array($result))
    {
        echo '<input type="text" name="update_moduleCode" placeholder="Module Code" value="'.$row['code'].'" required />';
        echo '<input type="text" name="update_moduleTitle" placeholder="Module Name" value="'.$row['name'].'" required />';
        echo '<textarea name="update_moduleDescription" rows="14" placeholder="Module Description" required></textarea><br />';
        echo '<input type="submit" name="update" class="next action-button" value="Update" />'; 

*****I guess this 'Update' button is not passing the user input to my managemodule.php
    }

The php part in managemodule.php above is not working (means it doesnt update my course table). I guess it is because the 'Update' button is not passing user input to managemodule.php. I used $_POST['update_moduleCode'] wanted to get the value from moduleinfo.php but I didnt manage to get.

So how am I supposed to pass the input from moduleinfo.php to managemodule.php

It appears that in moduleinfo.php file your update button is doing nothing when you click it. That's because it is not inside a HTML form and there is nothing binded to the onclick event. You should either create a function like showModuleInfo() but POSTing the data to a separate PHP file (that will update the database) or create a HTML form in moduleinfo.php that POST data to managemodule.php.

Despite that, I have some considerations about your code:

PHP extension mysql is deprecated

According to PHP documentation ( http://br2.php.net/manual/en/intro.mysql.php ) this extension is deprecated. You should use mysqli or pdo_mysql instead.

Your code is vulnerable to SQL injection

Note that you are using a information from $_GET directly into a MySQL query.

$q = $_GET['q'];
$result = mysql_query("SELECT * FROM module WHERE code = '".$q."'");

It makes your code vulnerable to a kind of attack named SQL injection. Instead, you should treat variables got from $_POST and $_GET with mysqli_real_escape_string ( http://br2.php.net/manual/en/mysqli.real-escape-string.php ) or using PDO prepared statements ( http://br2.php.net/manual/en/pdostatement.execute.php ).

You are mixing your business logic with the view (HTML code)

You are writing both the business logic code and the view code (HTML) in the same file. It makes your application very hard to maintain. You should have a look at some design patterns, starting with MVC (Model-View-Controller).

You are writing pure javascript code

Well, that's not exactly a bad thing. But you should consider that there are inconsistencies between browsers and sometimes, writing pure javascript code, your code may work in a browser but not in another. You should consider taking a look in the available javascript frameworks (I recommend jQuery), they take care of these inconsistencies and also have a lot of ready functionality.

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