Question

currently I have following code:

home.php

<form name='myformname' id='myformid'>
    <input type='text' name='mytext1' value='abc'>
    <input type='text' name='mytext2' value='123'>
    <input type='submit' value='Submit'> 
</form>

<div id='textone'></div><div id='texttwo'></div>

_home.php

$arr = array( 'textone' => $_POST['mytext1'], 'texttwo' => $_POST['mytext2'] );
echo json_encode( $arr );

ajax.js

jQuery('#myformid').live('submit',function(event) {
    $.ajax({
        url: '_home.php',
        type: 'POST',
        data: $('#myformid').serialize(),
        success: function( data ) {
            // TODO: write code here to get json data and load DIVs instead of alert
            alert(data);
        }
    });
    return false;
});

Output on submit:

{"textone":"abc","texttwo":"123"}

Question

I want to load mytext1 value in textone DIV and mytext2 value in texttwo DIV using json data in _home.php

Hint: I am using this answer to do the same task on link click event. But how to do this on form submission ?

Thanks

Was it helpful?

Solution

You just wanna parse that JSON and set the divs to the values it contains right?

var divs = JSON.parse(data);
for (var div in divs) {
  document.getElementById(div).innerHTML = divs[div];
}

(Previous poster's syntax is probably more like what you're after, and maybe is more cross-browser compatible, but doesn't include the JSON parsing.)

Since JSON is just a subset of JavaScript, you can just eval() it. JSON.parse() basically does that, but gives you assurances that if 'data' contains some nasty code instead of a simple object, it won't be evaluated.

OTHER TIPS

In the success function

for (prop in data){
    $('#' + prop).html(data[prop]);
}

Here is my complete JS solution:

jQuery('#myformid').live('submit',function(event) {
    $.ajax({
        url: '_home.php',
        type: 'POST',
        dataType: 'json',
        data: $('#myformid').serialize(),
        success: function( data ) {
            for(var id in data) {
                //jQuery('#' + id).html(data[id]); // This will also work
                document.getElementById(id).innerHTML = data[id];
            }
        }
    });
    return false;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top