Initially I am trying to load two views from one controller.
On submission I am passing one view to one controller and another view to another controller using ajax dynamically. Here is the skeleton of the controller
function edit(){
if (!$this->login_model->is_logged_in())
{
redirect('auth/login', 'refresh');
}
$this->load->library('form_validation');
$this->data['custom_error'] = '';
//------------- Getting Student data----------------
if ($this->form_validation->run('students') == false)
{
$this->data['custom_error'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);
} else
{
$data = array(
'username' => $this->input->post('username'),
'city' => $this->input->post('city')
);
if ($this->student_model->edit('students',$data,'id',$this->input->post('id')) == TRUE)
{
redirect(base_url().'index.php/students/manage/');
}
else
{
$this->data['custom_error'] = '<div class="form_error"><p>An Error Occured</p></div>';
}
}
$this->data['result'] = $this->codegen_model->get('students','id,username,city,created_on,date_created','id = '.$this->uri->segment(3),NULL,NULL,true);
$this->data['message'] = $this->db->get('messages')->result();
//---------------------- Posting student data for Edit--------------
$this->load->view('pheader');
$this->load->view('/students/students_edit', $this->data);
//-------- loading comment controller for comment box --------------
$msg_data['result'] = $this->db->get('messages')->result();
$this->load->view('commentView', $msg_data);
}
So the problem is when I m submitting the messages_view both the controllers are loaded , but I need to load only one controller
Here is my student_edit view where I edit my details
<?php
echo form_open(current_url()); ?>
<?php echo $custom_error; ?>
<?php echo form_hidden('id',$result->id) ?>
<p><label for="username">Username<span class="required">*</span></label>
<input id="username" type="text" name="username" value="<?php echo $result->username ?>" />
<?php echo form_error('username','<div>','</div>'); ?>
</p>
<p><label for="city">City<span class="required">*</span></label>
<input id="city" type="text" name="city" value="<?php echo $result->city ?>" />
<?php echo form_error('city','<div>','</div>'); ?>
</p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
Here is the commentView that I am loading separately from the controller
<div id="content-table-inner">
<table border="0" width="100%" cellpadding="0" cellspacing="0">
<?php foreach ($result as $comment): ?>
<tr valign="top">
<p>Posted By : <?=$comment->created_by?></p>
<p>Posted On : <?=$comment->created->on?></p>
<p>Message : <?=$comment->message?></p>
</tr>
<br/>
<?php endforeach; ?>
</table>
<div class="submitComment" id="insertbeforMe">
<h3>Add a message</h3>
<form id="form" method="POST" action="">
<p>
<textarea name="message"></textarea>
</p>
<input type="hidden" value="<?=base_url()?>" id="baseurl"/>
<button name="submit comment">Submit Comment</button>
</form>
</div>
<script type="text/javascript">
function comment(){
var baseurl = $('#baseurl').val();
$('.submitComment').click(function(){
$.ajax({
url : baseurl + 'index.php/comment/insert',
data : $('form').serialize(),
type: "POST",
success : function(comment){
$(comment).hide().insertBefore('#insertbeforMe').slideDown('slow');
}
})
return false;
})
}
</script>
</div>
Can anyone tell me whats the problem ?
If I understand correctly...
The event you should be capturing is the form's "submit", not the submit-button's "click". You're essentially running the AJAX request and submitting the form.
Try something like this instead:
$('form').on('submit', function(e) {
e.preventDefault(); // this prevents the form from submitting
// do AJAX stuff
});
Unless I am mistaken you are attaching the event to a click event on the '.submitComment' div.
Should you not give the button an id and attach the .click event to it ?
Then you need to define the view you want to call via ajax to return some json which your function can use:
The Javascript:
$('#button').click(function(){
$.ajax({
url : baseurl + 'index.php/comment/insert',
data : $('form').serialize(),
type: "POST",
dataType: "json",
success : function(comment){
$('table').append('<tr><p>'+comment.createdby+'</p><p>'+comment.createdon+'</p><p>'+comment.message+'</p></tr>');
}
})
return false;
})
The Controller method (comment/insert):
function insert() {
$comment = $this->input->post('message');
$result = $this->commentModel->insert($comment);
if($result["OK"]) {
$data['json'] = json_encode(array('createdon' => $result["createdon"], 'createdby' => $result["createdby"], 'message' => $result["message"]));
$this->load->view('json_comment_view', $data);
}
//ELSE deal with errors (flashdata etc...)
}
The View (loaded via ajax):
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo $json;
?>
I haven't tested this code - or used codeigniter extensively in about a year, but the concepts covered should put you on the right track for what you want to achieve. Let me know!
Related
I hope someone can give me a hand because I've tried and tried to find the error with no luck, I'm trying to execute an update SQL statement which gets the values from a POST AJAX request and everything seems to work ok but the table's values doesn't get updated.
The App flow is like this (and it actually works, just without the data update):
In my view I have a button which detonates a modal window for the user to input values in 4 text fields, then the user can click on a button and it sends such values through a POST AjAX call, then the controller and the method takes care of the update, then the user is sent back to the same page where he/she originally clicked the button.
As additional information, paths are correct, the flow works correctly, the values are being sent correctly through the AJAX call to the controller but I'm lost from that point on... :S
Not sure what I'm doing wrong, any help is appreciated
// My View - HTML button //
<i class="fa fa-file fa-2x" aria-hidden="true" ></i>
// My View - HTML modal window code //
<div id="confirmation_box_service_report_additional_data" title="" style="display:none;">
<h1 align="center" style="color: #333333"><?php echo $this->lang->line('service_report_title') ?></h1><br />
<h2 align="center" style="color: #DF9E0A"><strong><?php echo $this->lang->line('project_service_comments') ?></strong></h2><br />
<form id="form_service_report_additional_data" name="form_service_report_additional_data" method="post" action="">
<table width="100%">
<tr>
<td width="45%" class="red_cell_background">
<div class="form-group">
<label for="client_images_comments"><?php echo $this->lang->line('client_images_comments') ?></label>
<textarea class="form-control" rows="5" id="client_images_comments"></textarea>
</div>
</td>
<td width="5%" class="purple_cell_background"> </td>
<td width="45%" class="purple_cell_background"><div class="form-group">
<label for="specialist_images_comments"><?php echo $this->lang->line('specialist_images_comments') ?></label>
<textarea name="specialist_images_comments" rows="5" class="form-control" id="specialist_images_comments"></textarea>
</div></td>
</tr>
<tr>
<td class="red_cell_background"><div class="form-group">
<label for="spare_parts_comments"><?php echo $this->lang->line('spare_parts_comments') ?></label>
<textarea name="spare_parts_comments" rows="5" class="form-control" id="spare_parts_comments"></textarea>
</div></td>
<td class="purple_cell_background"> </td>
<td class="purple_cell_background"><div class="form-group">
<label for="final_comments"><?php echo $this->lang->line('final_comments') ?></label>
<textarea name="final_comments" rows="5" class="form-control" id="final_comments"></textarea>
</div></td>
</tr>
</table>
</form>
</div>
// My Javascript modal window code //
function service_report_additional_data(jobId) {
$("#spare_parts_comments").val("<?php echo $jobDetails[0]['spare_parts_description']; ?>");
$("#confirmation_box_service_report_additional_data").dialog({
autoOpen: false,
resizable: false,
width: 900,
heightStyle: "content",
modal: true,
closeOnEscape: false,
open: function(event, ui) {
$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
},
buttons: [
{
text: "<?php echo $this->lang->line('save_and_close'); ?>",
class: "btn btn-warning",
click: function() {
var clientImagesComments = $('#client_images_comments').val();
var technicianImagesComments = $('#specialist_images_comments').val();
var sparePartsDescription = $('#spare_parts_comments').val();
var finalThoughts = $('#final_comments').val();
//alert(finalThoughts)
servicereportadditionaldatasaving(jobId, clientImagesComments, technicianImagesComments, sparePartsDescription, finalThoughts);
},
},
{
text: "<?php echo $this->lang->line('Cancel'); ?>",
class: "btn btn-default",
click: function() {
$(this).dialog("close");
}
}
],
close: function() {
$(this).dialog("close");
}
});
$("#confirmation_box_service_report_additional_data").dialog('open');
}
//My AjAX call //
function servicereportadditionaldatasaving(jobId, clientImagesComments, technicianImagesComments, sparePartsDescription, finalThoughts) {
//alert(clientImagesComments)
$.ajax({
type: "POST",
url: "<?php echo base_url() . DISPATCHERADMIN . '/jobs/servicereportadditionaldatasaving/' ?>",
data: {
'jobId': jobId,
'clientImagesComments': clientImagesComments,
'technicianImagesComments': technicianImagesComments,
'sparePartsDescription': sparePartsDescription,
'finalThoughts': finalThoughts
},
success: function (data){
//alert(data);
location.href = '<?php echo base_url() . DISPATCHERADMIN . '/myjob/details/' ?>' + jobId;
},
error: function (jqXHR, textStatus, errorThrown){
console.log('error:: ' + errorThrown);
}
});
}
// My Controller //
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Jobs extends CI_Controller {
public function __construct() {
// Construct the parent class
parent::__construct();
$this->lang->load('message', 'english'); // language file
$this->load->model('dispatcher/jobs_model');
}
public function servicereportadditionaldatasaving() {
$postData = $this->input->post();
$data = array(
'table_name' => 'jobs',
'job_id' => $postData['jobId'],
'client_images_comments' => $postData['clientImagesComments'],
'technician_images_comments' => $postData['technicianImagesComments'],
'spare_parts_description' => $postData['sparePartsDescription'],
'final_thoughts' => $postData['finalThoughts']
);
$this->jobs_model->update_job_service_report_additional_data($data);
}
}
?>
// My Model //
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Jobs_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function update_job_service_report_additional_data($data) {
extract($data);
$this->db->where("job_id", $job_id);
$success = $this->db->update($table_name, array('client_images_comments' => $client_images_comments,
'technician_images_comments' => $technician_images_comments,
'spare_parts_description' => $spare_parts_description,
'final_thoughts' => $final_thoughts
));
if($success) {
return $success;
} else {
return false;
}
}
}
?>
I found the answer myself, after many attempts of looking into the code here and there I found that the problem was at the Ajax call at the following line:
url: "<?php echo base_url() . DISPATCHERADMIN . '/jobs/servicereportadditionaldatasaving/' ?>",
it was expecting an ID to be passed as part of the original URL as follows:
url: "<?php echo base_url() . DISPATCHERADMIN . '/jobs/servicereportadditionaldatasaving/' ?>" + jobId,
To be honest I need to review my code more in detail but that was the issue, everything is working as expected.
I'm trying to get a pop-up message saying if it was successfully submitted or not without having to go to a different page.
Now chrome gives me the pop-up message but it redirects me to a blank page after.
Here is my current code.
<?php
include "header.php";
include "conexao.php";
echo "<h1 align='center'>Pagina para alterar produtos</h1><div class='container'><hr>";
$referencia=$_GET['id'];
$sql = "SELECT * ";
$sql = $sql . " FROM tb_produto ";
$sql = $sql . " WHERE pr_codigo='".$referencia."'";
$produtos = $db->query($sql);
foreach ($produtos as $produto) {
$referencia = $produto["pr_codigo"];
$nome = $produto["pr_descricao"];
$preco = $produto["pr_preco"];
$disponivel = $produto["disponivel"];
}
echo "<h2>Referencia: ".$referencia."</h2>";
echo "<h2>Nome: ".$nome."</h2><hr>";
?>
<form action="confirmaAlterar.php">
<div class="form-group">
<label>Referencia</label>
<input class="form-control" type="text" name="referencia" value="<?php echo $referencia?>">
</div>
<div class="form-group">
<label>Nome</label>
<input class="form-control" type="text" name="nome" value="<?php echo $nome?>">
</div>
<div class="form-group">
<label>Preço</label>
<input class="form-control" type="text" name="preco" value="<?php echo $preco?>">
</div>
<button class="btn btn-primary">Alterar</button>
</form>
Here is where it submits the information of the form.
<?php
include "header.php";
include "conexao.php";
$nome=$_GET['nome'];
$referencia=$_GET['referencia'];
$preco=$_GET['preco'];
$sql="UPDATE tb_produto SET pr_descricao='".$nome;
$sql.="', pr_preco=".$preco;
$sql.= " WHERE pr_codigo='".$
try{
$comando=$db->prepare($sql);
$comando->execute();
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
header( "refresh2;Location:index.php" );
}
catch (PDOException $e){
echo "A";
}
To pass values using ajax. Form:
<form id="form">
<input type="text" value="test" name="akcija">
</form>
All inputs fields values in your form will be passed.
Ajax:
jQuery(function(){
$('#form').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'yoururl.php', //URL of page where u place query and passing values
data: $('#form').serialize(), //seriallize is passing all inputs values of form
success: function(){ //on success function
$("#input").attr("disabled", true); //example
$("#input").removeClass('btn-primary').addClass('btn-success');//example
},
});
}
});
And on the ajax page you can get values by
$akcija = $_POST['akcija']
for this Problem you must use ajax method .
1- create html form and all input Required .
<form id="contactForm2" action="/your_url" method="post">
...
</form>
2- add jQuery library file in the head of html page .
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
...
3- add this method Under the jQuery library
<script type="text/javascript">
var frm = $('#contactForm2');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data == 'pass')
alert('ok');
else(data == 'fail')
alert('no');
}
});
ev.preventDefault();
});
</script>
4- in your_url .php file
<?php
$a = ok ;
if( $a == 'ok' ){
echo 'pass';
}else{
echo 'fail';
}
?>
this top answer is easy management form with jquery , but you need managment Complex form better use this library http://jquery.malsup.com/form/
This is my form code which i was using with code ignitor
<div id="tab_register_content"class="content-form hidden">
<?php echo form_open('renty/sign_up_user')?>
<div>
<?php echo form_error('register_email');?>
<input id="register_email"class="input_placeholder email"type="text"value=""placeholder="Email address"name="register_email"/>
</div>
<div>
<?php echo form_error('password');?>
<input id="register_name" class="password" type="password" value="" name="password" onfocusout="get_form_value_from_user()"/>
</div>
<div>
<input id="register_remember_me_checkbox"type="checkbox"class="styled"name="remember_me"value="1"/>
<label for="register_remember_me_checkbox">
Remember me next time
</label>
</div>
<input class="admin-form-submit orange_button"type="submit"value="Continue"/>
<div class="admin_form_link">
<span class="sign_in">
<a class="tab_link_button"href="#sign_in"title="">
Already registered?
</a>
</span>for
</div>
</form>
</div>
I was using this form and i want to submit the from without reloading the page i was trying to the ajax code but its not working any suggestions? i commented the form_open line
<?php //echo form_open('renty/sign_up_user')?>
and then tried it with ajax but it's not working
<script type="text/javascript">
function get_form_value_from_user(){
var email = $(".email").val();
var password = $(".password").val();
if(email != "" && password != ""){
$.ajax({
url: '<?php echo base_url(); ?>/index.php/renty/sign_up_user?email='+email+'&password='+password,
success: 'Working'
});
}
}
</script>
My Controller
public function sign_up_user(){
$this->form_validation->set_rules('register_email','Register Email','required|valid_email|is_unique[sign_up.email]');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run() == FALSE){
$this->load->view('application/index');
}
else
{
$data['email'] = $_GET['email'];
$data['password'] = $_GET['password'];
$this->load->model('renty/db_data');
$this->db_data->insert($data);
$this->home();
}
}
There is no need to add renty/sign_up_user to your form open action.
url attributes does the work in jquery.
If you remove <?php echo form_open('renty/sign_up_user')?>
and replace with <?php echo form_open('')?> it will solve it.
This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Try Changing Your Code A bit like Below .
Jquery part
success: function(d){
var output=d[0].data; // Will output only first record
$('#cuentas').html(output);
} // End of success function of ajax form
PHP PART
$centro = $_POST['centro'];
$output_string = array('data'=>$centro);
echo json_encode($output_string);
if still not works Check The Developer tool in chrome or firebug in firefox to monitor the Requests
Looking at your code:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
I miss an ending-tag for the div id="centro". Therefore the click-event for jQuery("#centro") will not trigger.
I suppose it should be like this: (Always set <form> and </form> inside OR outside of a div, do not mix and put <form> outside and </form> inside of a div. Some things wont work as expected when you do a mix like that.
<?php
$result = 'works';
?>
<div id="centro">
<form id="form">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
</div> ><!-- end of div centro -->
<div id="cuentas">
</div>
I solved it, now this works, plus I added a gif loader:
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
var result = $("input#centro").val();
$.ajax({
url: 'request.php',
type:'POST',
data: { 'dataString': result },
beforeSend: function(){
$("#loader").show();
},
success: function(output_string){
$("#loader").hide();
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
<div id="loader" style="display:none"><img src="ajax-loader.gif" width="20px" height="20px"></div>
Click here
<br>
<input type="hidden" name="centro" id="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP
<?php
$data = $_POST['dataString'];
$output_string = '';
$output_string = '<h3>'.$data.' '.'testing'.'</h3>';
echo $output_string;
?>
Output: "works testing"
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);
?>
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