PHP: Problem submitting form in AJAX / JSON?

I currently have the 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 to submit:

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

Question

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

Hint: I am using this answer to accomplish the same task in the click click event. But how to do this when submitting the form?

thank

0
source share
3 answers

Do you just want to parse this JSON and set the divs to the values ​​it contains correctly?

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

( , , , , , , , JSON.)

JSON - JavaScript, eval() . JSON.parse() , , "" - , .

+1

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

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;
});
+1
source

All Articles