简体   繁体   English

使用AJAX和Jquery从MySQL填充表单字段

[英]Popuating form fields from MySQL using AJAX and Jquery

I followed a tutorial to adapt the code. 我按照教程改编了代码。 Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. 在这里,我尝试在提供“ ID”值时使用AJAX自动填充表单字段。 I am new to Jquery and can't get to work this code. 我是Jquery新手,无法使用此代码。

Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request. 编辑1:在测试代码时,Jquery不会阻止表单提交和发送AJAX请求。

HTML form HTML表格

<form id="form-ajax" action="form-ajax.php">
    <label>ID:</label><input type="text" name="ID" /><br />
    <label>Name:</label><input type="text" name="Name" /><br />
    <label>Address:</label><input type="text" name="Address" /><br />
    <label>Phone:</label><input type="text" name="Phone" /><br />
    <label>Email:</label><input type="email" name="Email" /><br />
    <input type="submit" value="fill from db" />
</form>

I tried changing Jquery code but still I couldn't get it to work. 我尝试更改Jquery代码,但仍然无法正常工作。 I think Jquery is creating a problem here. 我认为Jquery在这里造成了问题。 But I am unable to find the error or buggy code. 但是我找不到错误或错误代码。 Please it would be be very helpful if you put me in right direction. 请给我正确的方向,这将非常有帮助。

Edit 2 : I tried using 编辑2:我尝试使用

return false; 

instead of 代替

event.preventDefault(); 

to prevent the form from submitting but still it isn't working. 以防止表单提交但仍然无法正常工作。 Any idea what I am doing wrong here ? 知道我在做什么错吗?

Jquery jQuery的

jQuery(function($) {

// hook the submit action on the form
$("#form-ajax").submit(function(event) {
    // stop the form submitting
    event.preventDefault();

    // grab the ID and send AJAX request if not (empty / only whitespace)
    var IDval = this.elements.ID.value;
    if (/\S/.test(IDval)) {

        // using the ajax() method directly
        $.ajax({
            type : "GET",
            url : ajax.php,
            cache : false,
            dataType : "json",
            data : { ID : IDval },
            success : process_response,
            error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
        });


    }
    else {
        alert("No ID supplied");
    }
};


function process_response(response) {
    var frm = $("#form-ajax");
    var i;

    console.dir(response);      // for debug

    for (i in response) {
        frm.find('[name="' + i + '"]').val(response[i]);
    }
}

});

Ajax.php Ajax.php

if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
    // tell the browser what's coming
    header('Content-type: application/json');

    // open database connection
    $db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');

    // use prepared statements!
    $query = $db->prepare('select * from form_ajax where ID = ?');
    $query->execute(array($_GET['ID']));
    $row = $query->fetch(PDO::FETCH_OBJ);

    // send the data encoded as JSON
    echo json_encode($row);
    exit;
 }
}

I don't see where you're parsing your json response into a javascript object (hash). 我看不到您要将json响应解析为javascript对象(哈希)的位置。 This jQuery method should help. 这个jQuery方法应该会有所帮助。 It also looks like you're not posting your form using jquery, but rather trying to make a get request. 看起来您不是在使用jquery发布表单,而是尝试发出get请求。 To properly submit the form using jquery, use something like this: 要使用jquery正确提交表单,请使用以下方法:

$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );

Also, have you tried adding id attributes to your form elements? 另外,您是否尝试过向表单元素添加id属性?

<input type="text" id="name" name="name"/>

It would be easier to later reach them with 以后与他们联系会更容易

var element = $('#'+element_id);

If this is not a solution, can you post the json that is coming back from your request? 如果这不是解决方案,那么您可以发布请求中返回的json吗?

Replace the submit input with button: 将提交输入替换为按钮:

<button type="button" id="submit">

Note the type="button" . 注意type =“ button” It's mandatory to prevent form submition 防止表单提交是强制性的

Javascript: Javascript:

$(document).ready(function() {
    $("#submit").on("click", function(e) {
          $.ajax({type:"get",
                  url: "ajax.php",
                  data: $("#form-ajax").serialize(),
                  dataType: "json",
                  success: process_response,
                  error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
           });
    });
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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