Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My goal is to dynamically display information via PHP that is then editable via AJAX/json. I have this working for a single instance of the server data, but when I get into multiple instances I am getting lost on how to keep the element and div identities distinct via array on the json page as well as in the jQuery output on the main page.

This is the current main page (minus the irrelevant to this question PHP record grabbing). The references in the jQuery are not entirely correct, e.g.

data:$("#form_static_").serialize()

because it is placing the dynamic identifier after the static_ that I don't know how to handle.

<html>
<head>
<title>My Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("#myForm").submit(function(){
        $.ajax({
            type:"POST",
            url:"ajax_form_test2-json.php",
            data:$("#form_static_").serialize(),
            dataType:"json",
            success:function(msg){
                $("#formResponse_").removeClass('error');
                $("#formResponse_").addClass(msg.status_);
                $("#formResponse_").html(msg.message_);
                $("#static_name_").html(msg.name_);
                $("#static_description_").html(msg.description_);
            },
            error:function(){
                $("#formResponse_").removeClass('success');
                $("#formResponse_").addClass('error');
                $("#formResponse_").html("There was an error submitting the form. Please try again.");
                }
            });
        return false;
    });
});
</script>

</head>
<body>
  <div id="tabs-left-2" class="content">
    <h1 class="page-title">Static Info</h1>
      <?php do { ?>
        <div id="static_name_<?php echo $row_rsStatic['id']; ?>" class="small_content_heading"><?php echo $row_rsStatic['name']; ?></div>
        <div id="static_description_<?php echo $row_rsStatic['id']; ?>" class="small_content"><?php echo $row_rsStatic['description']; ?></div>
        <div id="static_update_<?php echo $row_rsStatic['id']; ?>" style="display:inherit">
        <form id="form_static_<?php echo $row_rsStatic['id']; ?>" name="form_static_<?php echo $row_rsStatic['id']; ?>" method="post" action="">
          <div id="formResponse_<?php echo $row_rsStatic['id']; ?>"></div>
          <div id="form_static_name_<?php echo $row_rsStatic['id']; ?>" class="small_content_heading">
            <input name="id<?php echo $row_rsStatic['id']; ?>" type="hidden" value="<?php echo $row_rsStatic['id']; ?>">
            <input name="name<?php echo $row_rsStatic['id']; ?>" type="text" value="<?php echo $row_rsStatic['name']; ?>"></div>
          <div id="form_static_description_<?php echo $row_rsStatic['id']; ?>">
            <textarea name="description<?php echo $row_rsStatic['id']; ?>"><?php echo $row_rsStatic['description']; ?></textarea>
          <script>CKEDITOR.replace('description<?php echo $row_rsStatic['id']; ?>');</script>
          </div>
        </form>
        </div>    
        <hr>
      <?php } while ($row_rsStatic = mysql_fetch_assoc($rsStatic)); ?>
    </div>
</body>
</html>

This is the json page, again with the dynamic identifiers left off after the respective "_" as I don't know how to make this happen programmatically:

<?php
//response array with status code and message
$response_array = array();

//validate the post form
//check the name field
if(empty($_POST['static_name_'])){

    //set the response
    $response_array['status_'] = 'error';
    $response_array['message_'] = 'Name is blank';

//check the message field
} elseif(empty($_POST['static_description_'])) {

    //set the response
    $response_array['status_'] = 'error';
    $response_array['message_'] = 'Description is blank';


//form validated
} else {

//(update record here)

    //set the response
    $response_array['status_'] = 'success';
    $response_array['message_'] = 'Success!';
    $response_array['name_'] = $_POST['static_name_'];
    $response_array['description_'] = $_POST['static_description_'];
}
echo json_encode($response_array);
?>

I have been doing PHP forever but am new to the AJAX/JSON/jQuery world, so not sure that the way this is set up is even ideal for dynamically produced/updated data. Any ideas or advice is greatly appreciated... thanks!

EDITS #1: I changed the files to the following, and know I am still missing something as it does not correctly update:

<html>
<head>
<title>My Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("form").submit(function(e){
        e.stopPropagation();

        var form = $(this);  // We're going to use this instead of all those IDs
        $.ajax({
            type:"POST",
            url:"ajax_form_test2-json.php",
            data: form.serialize(),
            dataType:"json",
            success:function(msg){
                $(".response", form)
                    .removeClass('error')
                    .addClass(msg.status)
                    .html(msg.message);
                $(".name", form).html(msg.name);
                $(".description", form).html(msg.description);
            },
            error:function(){
                $(".response", form)
                    .removeClass('success')
                    .addClass('error')
                    .html("There was an error submitting the form. Please try again.");
            }
        });
        return false;
    });
});
</script>

</head>
<body>
      <div class="small_content_heading name"><?php echo $row_rsSafety['name']; ?></div>
      <div class="small_content description"><?php echo $row_rsSafety['description']; ?></div>
      <div style="display:inherit">   
        <form method="post" action="">
          <div class="response"></div>
          <div class="small_content_heading">
            <input name="id" type="hidden" value="<?php echo $row_rsSafety['id']; ?>">
            <input name="name" type="text" value="<?php echo $row_rsSafety['name']; ?>">
          </div>
          <div>
            <textarea name="description"><?php echo $row_rsSafety['description']; ?></textarea>
            <script>CKEDITOR.replace('description');
            function CKupdate(){
    for ( instance in CKEDITOR.instances )
        CKEDITOR.instances[instance].updateElement();
}
            </script>
          </div>
          <input type="submit" name="submitForm" value="Edit" onClick="CKupdate();">
        </form>
     </div>    
     <hr>

</body>
</html>

JSON file:

<?php
//connect to DB
require_once('Connections/job_tool.php');
mysql_select_db($database_job_tool, $job_tool);

//response array with status code and message
$response_array = array();

//validate the post form
//check the name field
if(empty($_POST['name'])){
    //set the response
    $response_array['status'] = 'error';
    $response_array['message'] = 'Name is blank';
//check the message field
} elseif(empty($_POST['description'])) {
    //set the response
    $response_array['status'] = 'error';
    $response_array['message'] = 'Message is blank';
//form validated
} else {

    //set update variables
    $update_name = $_POST['name'];
    $update_desc = $_POST['description'];
    $update_id = $_POST['id'];

    //update file on server

    $sql = "UPDATE static_fields SET name='$update_name', description='$update_desc' WHERE id='$update_id'";
    $update_sql = mysql_query($sql, $job_tool) or die('Could not update data: ' . mysql_error());
    mysql_close();

    //set the response
    $response_array['status'] = 'success';
    $response_array['message'] = 'Update complete!';
    $response_array['name'] = $_POST['name'];
    $response_array['description'] = $_POST['description'];
}
echo json_encode($response_array);


?>
share|improve this question
 
Why not just use generic names for the inputs, and pass in the ID you're working with as a hidden input? –  landons Mar 14 at 16:34
 
Would that work if I end up with several (modal) forms on the page based on several sets of data dynamically generated? –  arT Mar 14 at 20:18
 
Yes. See my answer. –  landons Mar 19 at 21:52
 
I updated my files as well as I could see to do based on your answer (edit posted above) but I know I am still missing a change that I need as the file does not update correctly. –  arT Mar 20 at 4:51
 
I don't think I can help much more without writing it all for you. You'll need to update your HTML based on my bulleted "approach" list. –  landons Mar 20 at 21:23
add comment

1 Answer

up vote 0 down vote accepted

Rather than using IDs all the time, use jQuery context and classes:

<script type="text/javascript">
$(document).ready(function(){
    $("form").submit(function(e){
        e.stopPropagation();

        var form = $(this);  // We're going to use this instead of all those IDs
        $.ajax({
            type:"POST",
            url:"ajax_form_test2-json.php",
            data: form.serialize(),
            dataType:"json",
            success:function(msg){
                $(".response", form)
                    .removeClass('error')
                    .addClass(msg.status);
                    .html(msg.message);
                $(".name", form).html(msg.name);
                $(".description", form).html(msg.description);
            },
            error:function(){
                $(".response", form)
                    .removeClass('success')
                    .addClass('error')
                    .html("There was an error submitting the form. Please try again.");
            }
        });
        return false;
    });
});
</script>

So, rather than this:

<div id="static_description_<?php echo $row_rsStatic['id']; ?>" class="small_content"><?php echo $row_rsStatic['description']; ?></div>

You'll use a class instead:

<div class="small_content description"><?php echo $row_rsStatic['description']; ?></div>

The approach:

  • Use generic classes for your DIVs
  • Use generic names for your INPUTs
  • In your PHP $_POST handler, use the hidden ID field to know which record you're working with
  • In your JSON response, use generic status, message, name, and description keys
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.