0

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. I am new to Jquery and can't get to work this code.

Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.

HTML form

<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. I think Jquery is creating a problem here. 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

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(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

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;
 }
}

2 Answers2

0

I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:

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

Also, have you tried adding id attributes to your form elements?

<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?

Marcelo Ribeiro
  • 1,718
  • 1
  • 13
  • 27
  • Is it necessary to parse json response into javascript object ? I have directly used echo json_encode and using the response from console. JSON that should come back is : {"ID":"123","Name":"Test Only","Address":"123 Smith Street Jonestown 2000 NSW","Phone":"0123456789","Email":"test@example.com"} – Developer Vidit Sep 21 '14 at 07:30
  • If you've been able to access it as a javascript object (I dont know what exact error you were having) then maybe using element ids should work well for you. Just set the id attributes to be like the name attributes and my suggestion should work – Marcelo Ribeiro Sep 21 '14 at 07:35
  • But jQuery isn't preventing the form to submit and sending the AJAX request. On submitting the form it is redirected to 'form-ajax.php'. Any idea where I am wrong ? – Developer Vidit Sep 21 '14 at 07:41
  • Looks like you're not posting the form using jquery. I edited the answer to include how to post a form with ajax + jquery. – Marcelo Ribeiro Sep 21 '14 at 07:45
  • I don't want to post the form, I want to prevent it from posting and make an AJAX request to bring the data and auto populate it in the form. – Developer Vidit Sep 21 '14 at 07:51
0

Replace the submit input with button:

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

Note the type="button". It's mandatory to prevent form submition

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); }
           });
    });
}); 
Gervs
  • 1,397
  • 9
  • 8