Moderator Stefan
Moderator Stefan

Reputation: 11

AJAX calling PHP Array - Using jQuery / JSON

So I have an array of default values in a php array the file (backend.php) has multiple functions and acts. I want to target just the array with the act="default". I need to take the the encoded json php array and populate and html form with it.

html page - frontend.html

<html>
    <head>
    </head>
    <body>
        <h1>Form Validation</h1>
        <form id="PersonForm">
            Name:
                <input id="name" type ="text" name="name"></input>
                <br><br>
            Postal Code:
                <input id="postal" type ="text" name="postal"></input>
                <br><br>
            Phone Number:
                <input id="phone" type ="text" name="phone"></input>
                <br><br>
            Address:
                <input id="address" type ="text" name="address"></input>
                <br><br>
            <input type="submit"></input>
        </form>
        <div id= "content"></div>
        <a href="frontend.html">Refresh</a>
        <a id="InsertDefault" href="#">Insert Default Data</a>
        <br><br>
        <ul id="errors"></ul>
        <p id="success"></p>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="main.js" type="text/javascript"></script>
    </body>
</html>

php page - backend.php

<?php
if ($_REQUEST['act'] == 'default'){
    $defaultData = array(
        'name' => "Jane",
        'postal' => "L5B4G6",
        'phone' => "9055751212",
        'address' => "135 Fennel Street"
    );
    echo json_encode($defaultData);
}
else if...
?>

main.js page (errors here)

$(document).ready(function()
{
  $("#InsertDefault").click(function()
  {      
  // make an AJAX call here, and place results into the form
    $(document).ready(function(){
    $('#content').load('backend.php', {'default':'defaultData'},  //this format
    function (){ $('#content').html('these are the default values')} 
    );

    // prevents link click default behaviour
    defaultData.preventDefault();
    return false;
    });


  $("#PersonForm").submit(function()
  {
     // Clear any success or error messages
     $("#success").html("");
     $("#errors").empty();
     // make an AJAX call here, and set error or success accordingly
    // prevents submit button default behaviour
    return false;
  });  
});

Upvotes: 1

Views: 324

Answers (1)

Tristan
Tristan

Reputation: 3321

Instead of using .load it would be better to use $.ajax or $.post since $.load will set the content of the selected returned data (which should be either text or HTML). In your case you want to return json so that you can set the form element values.

$(document).ready(function()
{
    $("#InsertDefault").click(function(e)
    {
        // prevents link click default behaviour
        e.preventDefault();
        // make an AJAX call here, and place results into the form
        $.ajax({
            url: 'backend.php',
            type: 'post',
            data: {
                act:'default'
            },
            dataType: 'json',
            success: function(data) {
                // set the form values
                $('[name=name]').val(data.name);
                $('[name=postal]').val(data.postal);
                $('[name=phone]').val(data.phone);
                $('[name=address]').val(data.address);
                // display message
                $('#content').html('Fields filled in with default values');
            },
            error: function() {
                // handle your error
                console.log('error');
            }
        });
        return false;
    });

    $("#PersonForm").submit(function()
    {
        // Clear any success or error messages
        $("#success").html("");
        $("#errors").empty();
        // make an AJAX call here, and set error or success accordingly
        // prevents submit button default behaviour
        return false;
    });  
});

Since your AJAX call is expecting json return you need to use header('Content-Type: application/json'); in your php script to set the data type.

It's also a good idea to use output buffering (see ob_start() and ob_clean() below) so that any notices outputted by php do not dirty the json your AJAX call is expecting.

ob_start();
if (isset($_POST['act']))
{
    if ($_POST['act'] == 'default')
    {
        ob_clean();
        header('Content-Type: application/json');
        $defaultData = array(
            'name' => "Jane",
            'postal' => "L5B4G6",
            'phone' => "9055751212",
            'address' => "135 Fennel Street"
        );
        echo json_encode($defaultData);
        exit();
    }
}

Upvotes: 1

Related Questions