Populating form fields in ajax - php

I am trying to populate my form fields with AJAX when a request is being made. I was able to successfully made the request and fetched data, but the issue I am facing is that the input fields are not being populated.
If I populate the return data into a div it will display but not displaying in a form fields.
My HTML code
<form id="fm" method="post" novalidate>
<div style="margin-bottom:10px">
<input class="easyui-textbox" name="descr" id="descr" multiline="true" data-options="label:'Description:'" style="width:100%;">
</div>
<div style="margin-bottom:10px">
<input class="easyui-textbox" name="unit" id="unti" style="width:100%" data-options="label:'Unit:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="rate" id="rate" style="width:100%" data-options="label:'Rate:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="fixing" id="fixing" style="width:100%" data-options="label:'Fixing:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="quantity" id="quantity" style="width:100%" data-options="label:'Quantity:'">
</div>
</form>
jQuery Code
function load_click(param)
{
var resp = $("#loadstatus");
$.ajax({
type: "POST",
url: "boqs/load.php",
data: {},
dataType: 'json',
beforeSend: function(){
resp.html(' <img src="../assets/img/rot_small.gif" />');
},
success: function (data) {
if (Array.isArray(data) && data.length) {
for (var i = 0; i < data.length; i++) {
//for each value in the json response
$(".descr").val(data[i].descr);
$(".unit").val(data[i].unit);
$(".rate").val(data[i].rate);
$(".fixing").val(data[i].fixing);
$(".quantity").val(data[i].quantity);
//alert(data[i].descr);
} // for
resp.html('');
}
});
}
PHP source code
$sql = "SELECT * FROM bill_preparation ORDER BY id DESC LIMIT 1";
$ret2 = $db->query($sql);
$json_resp = array();
while($row = $ret2->fetchArray(SQLITE3_ASSOC)){
$json_array['descr'] = $row['descr'];
$json_array['unit'] = $row['unit'];
$json_array['rate'] = $row['rate'];
$json_array['fixing'] = $row['fixing'];
$json_array['quantity'] = $row['quantity'];
//$json_array['amount'] = $row['amount'];
array_push($json_resp, $json_array);
}
//$result["rows"] = $items;
echo json_encode($json_resp, true);

Thanks to very one for your support. #Patrick suggestion pointed me to the right direction.
I discovered using $(".descr").val(data[i].descr); doesn't work in easyui form so I used $(".descr").textbox('setValue',data[i].descr); which worked.
I hope this help someone working with easyui.

Related

Receiving and Processing a multi dimensional array

I have asked this question twice, with no satisfactory answer, that is, the problem I faced two questions ago still remains and none the wiser as how I am going to proceed with this.
This time I will provide all the code and what I receive, plus where the problem is occurring, I know what the issue is but since I'm relatively new to using AJAX it has me puzzled.
I have a form, which when you click the second to last field, duplicates itself, with the help of another user all the id's get changed to be unique.
<form role="form" class="batchinvoice form-horizontal" id="batchinvoice">
<div class="row">
<div class="form-group col-md-2">
<select class="form-control" name="sl_propid" >
<?php foreach($property as $row) :?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row[ 'property_name'] . " " . $row[ 'property_address1']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-1">
<input type="text" name="sl_date" placeholder="Date" class="sl_date form-control" id="datepicker">
</div>
<div class="form-group col-md-2">
<input type="text" name="sl_ref" placeholder="Invoice Reference" class="form-control" id="sl_ref">
</div>
<div class="form-group col-md-2">
<select class="form-control" name="sl_nom_id" id="sl_nom_id">
<?php foreach($subitem_nominals as $row) :?>
<option value="<?php echo $row['subnom_id']; ?>">
<?php echo $row[ 'nom_subitem_name']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-2">
<input type="text" name="sl_desc" id="sl_desc" placeholder="Invoice Description" class="form-control">
</div>
<div class="form-group col-md-2">
<input type="text" name="sl_vat" placeholder="VAT Amount" class="vat form-control" id="vat">
</div>
<div class="form-group col-md-1">
<input type="text" name="sl_net" placeholder="Net" class="form-control" id="sl_net">
</div>
</form>
The JS for the form clone
<script>
var clone_iterator = 0;
$(function () {
var i = 0;
$.datepicker.setDefaults($.datepicker.regional['']);
$.datepicker.formatDate("yy-mm-dd");
$('#datepicker').datepicker();
$('#batchinvoice .vat').click(function () {
// alert("ok");
var id = "batchinvoice" + clone_iterator;
$('#batchinvoice').clone(true).attr("name", id).attr('id', id).appendTo(".panel-body"); // here I added this .attr('id',id)
// here we'll change the id's of all the elements who actualy have an attribute
$('#' + id + ' *[id]').each(function () {
$(this).attr('id', $(this).attr('id') + clone_iterator); //we set the attribute id
});
clone_iterator++;
});
$('#submit').click(function () {
var res = {};
console.log(res);
$('.batchinvoice').each(function (i) { //the class is a good use to do things like that you can repeat it more than once !
res[i] = new Array();
console.log(res);
res[i].propid = $(this).find('*[name=sl_propid]').val();
res[i].date = $(this).find('.sl_date formcontrol').val();
res[i].ref = $(this).find('*[name=sl_ref]').val();
res[i].id = $(this).find('*[name=sl_nom_id]').val();
res[i].desc = $(this).find('*[name=sl_desc]').val();
res[i].vat = $(this).find('*[name=sl_vat]').val();
res[i].net = $(this).find('*[name=sl_net]').val();
console.log(res);
alert(res[i].propid);
// i++;
//$.each('',function( index, value ){}
//(int)i is already incremented if you use class and not IDS
});
console.log(res);
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>FinancialInput/addInvoiceToLedger',
data: res,
sucess: function (e) {
alert(e);
},
error: function (e) {
alert(e.toString());
}
});
});
});
</script>
This is the particular controller function in CodeIgniter, Note I have tried multiple things.
function addInvoiceToLedger(){
// $this->load->model('SalesLedgerModel');
// $propid = $this->input->post('propid');
// print_r($this->input->post());
// $date = $this->input->post('date');
// $ref = $this->input->post('ref');
// $nomid = $this->input->post('id');
// $desc = $this->input->post('desc');
// $vat = $this->input->post('vat');
// $net = $this->input->post('net');
$res = $this->input->post(NULL, TRUE);
//problem is probably here, it's
//for($x = 0; $x < count($res); $x++){
foreach($res as $row){
$this->SalesLedgerModel->addInvoiceToLedger($row.propid, $row.date, $row.ref, $row.nomid, $row.desc, $row.vat, $row.net);
}
//}
//redirect('home/financial_input/');
}
the Model Function
function addInvoiceToLedger($propid, $date, $ref, $nomid, $desc, $vat, $net){
$data = array('sl_prop_id' => $propid, 'sl_date' => $date,
'sl_ref' => $ref, 'sl_nominal_sub' => $nomid, 'sl_invoice_desc' => $desc, 'sl_vat' => $vat, 'sl_amount' => $net);
$this->db->insert_batch('salesledger', $data);
}
Which all have the relevant field data for each form inside them.
My question is how do I receive and handle the array? Every loop I've tried doesn't work, I've tried getting variables singularly(as you can see above commented out) but that doesn't make sense (or work) because in the $.ajax data it is set to res, but $this->input->post('res') doesn't return anything nor does $this->input->post(NULL, TRUE)
Majorly stuck, I feel this should be a simple thing, but I clearly don't understand it.
Edit, still same problem can't find an answer anywhere D:, tried many things.
Still the same problem "res" is sent as post, but I can't retrieve it in the controller with $this->input->post()...anyone?
I only wanted to submit a comment but apparently I need 50 rep for that so I'll take my chances with an answer.
In your $.ajax block what if you change the data section to this:
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>FinancialInput/addInvoiceToLedger',
data: { res : res },
sucess: function (e) {
alert(e);
},
error: function (e) {
alert(e.toString());
}
});

No alert in success function

I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>

JQuery adds unwanted div after an ajax call

I have an jquery ajax call where I add a new comment to a database. It saves just fine but when i want to reaload the div where the comments are shown, I always get an additional div which I do not want. When I reaload the page everything is just fine and displayed as wanted!
The script:
<script>
$("#addcmt").click(function() {
var UserID = $("#UserID").val();
var ClassID = $("#ClassID").val();
var text = $("#appendedInputButton").val();
var option;
if($("#option").is(':checked')) {
option = 3;
} else {
option = 1;
}
$.ajax({
type: "GET",
url: "/comment/functions/add_class_comment.php",
data: "text=" + text + "&UserID=" + UserID + "&ClassID=" + ClassID + "&option=" + option,
success: function(msg) {
$("#CommentList").load(location.href+' #CommentList');
$('#appendedInputButton').val("");
$('.criticalcomment').attr('checked', false);
}
});
});
</script>
The php+html where they comments are shown:
<div class="bs-docs-example" id="message">
<div id="CommentList">
<?php
for ($i=0; $i<$l; $i++) {
switch($commentarr[$i]->getOption()) {
case 1:
$option="alert-success";
break;
case 2:
$option="alert-info";
break;
case 3:
$option="alert-error";
}
echo '<div class="Comments alert '.$option.'"><div class="CommentsName">'.$userarr[$i]->getFirstname().' '.$userarr[$i]->getLastname().'</div>';
echo '<div class="CommentsDate">'.renderDate($commentarr[$i]->getDate()).'</div><div class="CommentsText">'.$commentarr[$i]->getText().'</div>';
if ($deletebutton == 1) {
echo '<div class="deleteButtonAdmin"><input type="button" class="btn btn-small btn-primary delcmt" value="Löschen" name="'.$commentarr[$i]->getID().'"></div>';
}
echo '</div>';
}
?>
</div>
<form class="Comments postmessage">
<div class="input-append" style="margin-top: 10px;">
<input type="hidden" name="ClassID" id="ClassID" value="<?php echo $c->getID(); ?>">
<input type="hidden" name="UserID" id="UserID" value="<?php echo $u->getID(); ?>">
<textarea class="span12" name="text" id="appendedInputButton" type="text"></textarea>
<label for="option">Kritisch?</label><input type="checkbox" id="option" class="criticalcomment" name="option" value="1">
<input type="button" class="btn" id="addcmt" value="Post">
</div>
</form>
</div>
I hope someone got an idea or hint for me!
Well, $("#CommentList").load(location.href+' #CommentList'); tells jQuery to replace the contents of #CommentList with #CommentList, so you get two nested #CommentLists, correct?
You might have to do $("#CommentList").remove().load(location.href+' #CommentList'). If that does not work, try introducing a temporary div:
$("<div />").load(location.href+' #CommentList', function (div) {
$('#CommentList').replaceWith($(div));
})
try adding this after loading the div!
$("#CommentList").find('div').unwrap(); or
$("#CommentList").find('#CommentList').unwrap();//I am doubtful about this

Ajax stopped working after executing a query

I am trying to load comments from a php file using ajax.
index.php
<div id="commentsonpost" value="<?php echo $_GET['post'];?>">
</div>
<script type="text/javascript">
$(document).ready(function() {
var postid = $('#commentsonpost').attr("value");
alert(postid);
var dataString = 'getpostcomm=1&postid='+ postid;
$.ajax({
type: "get",
url: "getcomments.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
alert("re");
$("#commentsonpost").append(html);
}
});
return false;
});
</script>
getcomments.php
if(isset($_GET['getpostcomm'])){
$var=$_GET['postid']; // Adding this line causing problems
$querycomm = "select U.fname,U.lname,U.usernick,C.bcommentid,C.comment,C.date,C.visible from blogcomments as C natural join users as U where C.visible=1 and U.visible=1 and C.bpostid='{$var}' ORDER BY C.date ASC";
$resultcomm = mysql_query ( $querycomm, $connection );
echo "<div id='pcomments'>";
while($commentonpost=mysql_fetch_array($resultcomm)){
if($commentonpost['visible']==1){
echo '
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;" id="comment'.$commentonpost['commentid'].'">
<div style="width:10%;float:left;"><a href="profile.php?user='.$commentonpost['usernick'].'" >'.$commentonpost['fname']." ".$commentonpost['lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;">'.$commentonpost['comment'].'</div>
<div style="width:8%;float:right;margin-left:2%;">
';
if($commentonpost['usernick']==$_SESSION['user_nick']){
echo ' <form action="" method="post">
<input type="submit" name="delcomm" value="X" class="delcombutton" id="'.$commentonpost['commentid'].'">
</form>
';
}
echo '<h5 class="msg">'.datetime($commentonpost['date']).'</h5>
</div>
<br/>
</div>
';
}
}
echo "</div>";
echo '
<form name = "form" method = "post" action="" onsubmit="return validateform()" style="width:100%">
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;">
<div style="width:10%;float:left;"><a href="profile.php?user='.$_SESSION['user_nick'].'" >'.$_SESSION['user_fname']." ".$_SESSION['user_lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;"><textarea placeholder="Comment..." name="commenttext" id="commenttext" class="inputcomment" ></textarea></div>
<br>
<input type="submit" id="'.$_POST['post'].'" name="SubmitComment" value="Comment " class="commentbutton" style="font-size:1em;width:100px;float:right;margin-top:4px;margin-right:9%;">
</div>
</form>
</div>
';
}
Whenever i add that $var=$_GET['postid']; line in getcomments.php ajax script stop working. As soon as i remove $var=$_GET['postid']; from getcomments.php, excluding query part(obviously) form is displaying correctly.
Any ideas?
At ajax better set data fields as array values as:
$.ajax({
type: "get",
url: "getcomments.php",
data: {'getpostcomm':1,'postid':postid},
And at your PHP you have to sanitize your Id.. (if its int you may at least cast (int) )...
$var = (int) $_GET['postid'];
Also at your PHP add check if isset($_GET['postid'])...
if(isset($_GET['getpostcomm']) && isset($_GET['postid'])){
var dataString = 'getpostcomm=1&postid='+ toString(postid);

Radio/Checkboxes not saving to db

I have this form in a foreach loop, so it shows multiple times on the same page.
Everything submits fine in each form EXCEPT the radio buttons and checkboxes. They don't save the values to the db.
EDIT: I've narrowed it down to the ajax causing the error but can't figure out how to correct it.
<form action="process.php" method="post" name="editInvoice'.$invoice_id.'" id="editInvoiceForm'.$invoice_id.'" class="editInvoiceForm edit_invoice_container" enctype="multipart/form-data">
<div class="form_item_row">
<input type="radio" value="Unsent" '.$unsent.' name="status"/><span class="choice">Unsent</span>
<input type="radio" value="Sent" '.$sent.' name="status"/><span class="choice">Sent</span>
<input type="radio" value="Paid" '.$paid.' name="status"/><span class="choice">Paid</span>
</div>
<div class="form_item_row">
<label for="include_timelog'.$invoice_id.'">Include Time Log</label>
<input type="checkbox" value="true" '.$include_timelog.' name="include_timelog" id="include_timelog'.$invoice_id.'" />
</div>
<div class="clear"></div>
<div class="form_item_row_btns">
<input type="hidden" value="'.$invoice_id.'" name="hiddenInvoiceID"/>
<input type="submit" class="btn" value="Update Invoice" name="action"/>
</div>
</form>
$query = "UPDATE invoices SET status = ".$db->prep($_POST['status']).", include_timelog = ".$db->prep((isset($_POST['include_timelog'])?1:0))." WHERE invoice_id = ".$db->prep($invoice_id);
$(document).ready(function()
{
var action = '';
$(".due_date").datepicker();
$('input[name=action]').click(function(){
action = $(this).val();
});
$(".editInvoiceForm").submit(function() {
$('.editInvoiceForm .form_message').html('<img src="images/loadingAnimation.gif" alt="loadingAnimation" width="30" height="8"/>');
var dataToSend = {};
$(this).find(':input').each(function (i,el) {
dataToSend[el.name] = $(el).val();
});
dataToSend.action = action;
$.ajax({
type: "POST",
url: "process.php",
data: dataToSend,
dataType: "json",
cache: false,
success: function(data){
//console.log(data.status);
if(data.status == 'error'){
$('.editInvoiceForm .form_message').removeClass('status_green').addClass('status_red').html(data.message).append(data.script);
}else{
$('.editInvoiceForm .form_message').removeClass('status_red').addClass('status_green').html(data.message).append(data.script);
}
}
});
return false;
});
});
You need quotes around the value for status in your SQL since the value is a string. Your include_timelog and invoice_id values are integers and do not need quotes.
$query = "UPDATE invoices SET status = '".$db->prep($_POST['status'])."', include_timelog = ".$db->prep((isset($_POST['include_timelog'])?1:0))." WHERE invoice_id = ".$db->prep($invoice_id);

Categories