views:

81

answers:

3

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

+1  A: 

In the success function

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

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.

philo
I also answered the complete solution here.
NAVEED
If the Content-type header in the response is set to application/json, jQuery will automatically parse it in the data param passed to the success function.
mqsoh
+1  A: 

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