Seeker
Seeker

Reputation: 43

Post some field values using ajax before submitting from submit button

Can I post some values using ajax before submitting fields from submit button ?

I'm using the following code. It reaches success but I'm not able to get the posted data. Any clue for this ? Your help/review will be greatly appreciated. Thanks!

function auto_fill(){  

        var that = $(this),
            url = './auto_fill.php',
            type = that.attr('method'),
            data = {};

        that.find('[name]').each(function(index,value){
            var that =$(this),
                name =that.attr('name'),
                value = that.val();
                data[name] = value;
        }); 

        $.ajax({
            url: url,
            type: type,
            data: data,
            success: function(response) {
                        document.getElementById("f_name").value="<?php echo $name ?>";
                        document.getElementById("phn_no").value="<?php echo $phn_num ?>";

            }
        });

        return false;
    }

Upvotes: 3

Views: 196

Answers (1)

Dexpras
Dexpras

Reputation: 426

Try this

function auto_fill(){
  $.getJSON("./auto_fill.php?id_num=" + $("#id_num").val(),
        function(data){
          $.each(data, function(i,item){
            if (item.field == "first_name") {
              $("#f_name").val(item.value);
            } else if (item.field == "phonenum") {
              $("#phn_no").val(item.value); 
            } 
          });
        });
}

auto_fill.php

$id = $_GET['id_num'];

//build the JSON array for return
$json = array(array('field' => 'first_name', 
                    'value' => 'Your name'),

              array('field' => 'phonenumber', 
                    'value' => $phn),
              array('field' => 'somethinglikeDiscription', 
                    'value' => 'You entered ID as '.$id));
echo json_encode($json );

you can pass any variable to this values by this JSON array.

Upvotes: 3

Related Questions