How to autofill other form fields upon click with PHP

…衆ロ難τιáo~ 提交于 2019-12-06 14:44:41

Make a php endpoint (basically a url in which you can call your special php function, which returns only the data you want) that returns a json_encode'd array with all of the other fields' info.

Call that function via ajax when the first field either loses focus or changes (or a button is pressed), depending on your preference.

Then using javascript, use what you've gotten back from the ajax response to populate the other fields.

autoFill.php

$name = $_GET['name'];
$return = mysql_query("SELECT * FROM someTable WHERE username = '$name' LIMIT 1");
$rows = mysql_fetch_array($return);
$formattedData = json_encode($rows);
print $formattedData;

Javascript (using jquery) //gets the val from the first field

$(document).ready(function() {
    function myrequest(e) {
        var name = $('.username').val();
        $.ajax({
            method: "GET",
            url: "/echo/json/", /* online, change this to your real url */
            data: {
                username: name
            },
            success: function( responseObject ) {
                alert('success');
                $('#posts').val( 'posts' );
                $('#joindate').val('testing join date');
                /*
                once you've gotten your ajax to work, then go through and replace these dummy vals with responseObject.whatever
                */
            },
            failure: function() {
                alert('fail');
            }
        });
    }

    $('#fetchFields').click(function(e) {
        e.preventDefault();
        myrequest();
    });
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!