how to use onchange to update mysql automatically when change the value - php

I am editing a code which supposed to update database when value is change, however it doesn't work, hope someone could help me fix it.
I am using DISTINCT to get the data and need to update a few data at the same time. it can display the value, but it can't save in database.
for example, I will using DISTINCT to get a few data which with the same date and I will change values among those data at the same time by using that code.
index.php
<script>
window.onload = function() {
$(".cal_amount").change(function() {
var auto_array = {};
//Step 1- On change use The closest() method to get the all input elements value of selected element row.
form_data = $(this).closest('tr').find('input, select');
//Step 2- On change Use map to store input elements value with name as key in the array.
var myArray = $.map(form_data, function(element) {
auto_array[element.name] = element.value;
//return {name: element.name, value: element.value};
});
form_data = $(this).closest('tr').find('input,select').serialize();
$.ajax({
data: {
action: 'update_price',
form_data: form_data,
},
url: 'updates_ok.php',
type: 'post',
beforeSend: function() {
},
success: function(data) {
if(data == 1){
alert('update sucessful')}
}
});
});
};
</script>
<script>
window.onload = function() {
$(".day_record").change(function() {
var auto_array = {};
//Step 1- On change use The closest() method to get the all input elements value of selected element row.
form_data = $(this).closest('tr').find('input, select');
//Step 2- On change Use map to store input elements value with name as key in the array.
var myArray = $.map(form_data, function(element) {
auto_array[element.name] = element.value;
//return {name: element.name, value: element.value};
});
form_data = $(this).closest('tr').find('input,select').serialize();
$.ajax({
data: {
action: 'update_data',
form_data: form_data,
},
url: 'updates_ok.php',
type: 'post',
beforeSend: function() {
},
success: function(data) {
if(data == 1){
alert('update sucessful');}
}
});
});
};
</script>
update.php
<?php
if($_POST['action'] == 'update_price'){
//parse the serialize data
parse_str($_POST['form_data'], $my_form_data);
/*echo "<pre>";
print_r($my_form_data);*/
$id = $my_form_data['id'];
$gp_name = $my_form_data['gp_name'];
$price = $my_form_data['price'];
$cost = $my_form_data['cost'];
$sql= $query = $finalquery = $sqlresult = '';
if($cost){
$sql.="cost='$cost',";
}
if($price){
$sql.="price='$price',";
}
$finalquery = rtrim($sql,',');
$query="UPDATE `gp_info` SET $finalquery where id=$id";
$sqlresult=mysql_query($query);
if($sqlresult){
$reback=1;
}else{
$reback=0;
}
echo $reback;
}
if($_POST['action'] == 'update_data'){
//parse the serialize data
parse_str($_POST['form_data'], $my_form_data);
/*echo "<pre>";
print_r($my_form_data);*/
$gp_name = $my_form_data['gp_name'];
$date = $my_form_data['date'];
$day = $my_form_data['day'];
$sql= $query = $finalquery = $sqlresult = '';
if($date){
$sql.="date='$date',";
}
if($day){
$sql.="day='$day',";
}
$finalquery = rtrim($sql,',');
$query="UPDATE `gp_info` SET $finalquery where gp_name='$gp_name' AND date='$date' AND day='$day'";
$sqlresult=mysql_query($query);
if($sqlresult){
$reback=1;
}else{
$reback=0;
}
echo $reback;
}
?>

Try the below code. I mention the details in code with comments.
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<script>
window.onload = function() {
$(".update_row_data").change(function() {
//On change of update_row_data get the action name from current row
action = $(this).closest('tr').data('action');
form_data = $(this).closest('tr').find('input,select').serialize();
$.ajax({
data: {
//Use that action name in ajax request.
action: action,
form_data: form_data,
},
url: 'updates_ok.php',
type: 'post',
beforeSend: function() {
},
success: function(data) {
if(data == 1){
alert('update sucessful')}
}
});
});
};
</script>
<table border="1" align="center" style="table-layout:fixed">
<tbody id="_editable_table">
<!-- Add action name in row item with data attr-->
<tr data-action="update_price">
<!-- Add common class 'update_row_data' to all required field. -->
<input name="gp_name" style="border-style:none" type="hidden" class="update_row_data gp_name" value="">
<th>Date</th><td width="350px"><input name="date" size="10" style="border-style:none" type="text" class="update_row_data date" value=""></td>
<th>Country</th><td><input name="country" size="6" style="border-style:none" type="text" class="update_row_data country" value=""> </td>
<th>City</th><td><input name="city" size="8" style="border-style:none" type="text" class="update_row_data city" value=""></td>
</tr>
</tbody>
</table>
<table border="1" align="center" style="table-layout:fixed">
<tbody id="_editable_table">
<!-- Add action name in row item with data attr-->
<tr data-action="update_data">
<!-- Add common class 'update_row_data' to all required field. -->
<input name="gp_name" style="border-style:none" type="hidden" class="update_row_data gp_name" value="">
<th>Date</th><td width="350px"><input name="date" size="10" style="border-style:none" type="text" class="update_row_data date" value=""></td>
<th>Country</th><td><input name="country" size="6" style="border-style:none" type="text" class="update_row_data country" value=""> </td>
<th>City</th><td><input name="city" size="8" style="border-style:none" type="text" class="update_row_data city" value=""></td>
</tr>
</tbody>
</table>

Related

Laravel 5 get AJAX array POST in Controller

I have the following form:
<td>
<input type="text" name='name[]' class="form-control"/>
</td>
<td>
<input type="text" name='mail[]' class="form-control"/>
</td>
<td>
<select name="gender[]" class="form-control">
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</td>
<td>
<input type="date" name='birth[]' class="form-control"/>
</td>
<td>
<input type="number" name='dni[]' class="form-control"/>
</td>
<td>
<input type="number" name='phone[]' class="form-control"/>
</td>
My ajax call when i try to submit my form
$('#form-reserve-list').on('submit', function(e) {
e.preventDefault();
var names = $("input[name='name[]']").serialize();
var mails = $("input[name='mail[]']").serialize();
var genders = $("select[name='gender[]']").serialize();
var births = $("input[name='birth[]']").serialize();
var dnis = $("input[name='dni[]']").serialize();
var phones = $("input[name='phone[]']").serialize();
var _token = $('input[name=_token]').val();
var est_id = $('input[name=est_id]').val();
var event_id = $('input[name=event_id]').val();
var url = 'http://localhost:82/boulevard/public/event/reserve/list';
$.ajax({
type: 'POST',
url: url,
data: {names:names, mails:mails, genders:genders, births:births, dnis:dnis, phones:phones, _token: _token, est_id:est_id, event_id:event_id},
cache: false,
success: function(data){
alert(data);
}
});
I want to receive this in my Controller and do a foreach or for loop and save it to my db, but the problem is when i try:
$names = Input::get('names'); //from ajax names
foreach($names as $name){
$name[];
//also tried $name[$key] after i added $key =>
}
am i doing something wrong? thank you for the help.
EDIT:
when i do alert($names) in ajax it shows as name%5B%D=carlos&name%5B%D=kevin is this the way its suppose to be? i also did dd($names); and also shows name%5B%D=carlos&name%5B%D=kevin but when i use foreach loop as mentioned above, the chrome console shows me internal error 500, am i suppose to use foreach?
EDIT2:
when i do dd(Input::all())
name%5B%5D=carlos&name%5B%5D=mendieta&name%5B%5D=cordero
how do i loop thru these?
//No need to serialize each field.
//You could do it like this:
$('#form-reserve-list').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
var url = 'http://localhost:82/boulevard/public/event/reserve/list';
$.ajax({
type: "POST",
url: url,
data: formData,
dataType: "json",
success: function(data) {
},
error: function(){
alert('opps error occured');
}
});
});

Assigning AJAX response for two separate DIV tags

This is my ajax call code..
<script type="text/javascript">
$(document).ready(function(){
$('#itemcode').blur(function(){
var itemcode = $(this).val();
$.ajax({
type: "POST",
url:'ajax.php',
data: {'itemcode' : itemcode} ,
cache: false,
success: function(data) {
alert(data)
$("#desc").val(data);
$("#bal").val(data);
}
});
});
});
</script>
include "db.php";
$itemcode=$_POST['itemcode'];
$sql="select * from itemmaster where Item_Code='$itemcode'";
$result = mysql_query($sql, $con);
while($row = mysql_fetch_array($result)) {
echo $row['Item_Desc'];
echo $row['Balance_Stock'];
}
This is simple html form..
<form action="add.php" method="post">
<table style="border: 1px solid black;padding:20px;"cellspacing="1px">
</br></br>
<tr>
<td>Issue No:</td> <td><input name="issueno" type="text" id="issueno"/></td>
<td>Issue Date:</td> <td><input name="issuedate" type="date" id="issuedate"/></td></tr></br></br><tr></tr>
<tr>
<td>Item Code:</td> <td><input name="itemcode" type="text" id="itemcode" /></td>
<td>Description:</td> <td><input name="des" type="text" style="width:250px; height:23px" id="desc"/></td>
<td>Bal Quantity:</td> <td><input name="bal" type="text" id="bal"/></td>
</tr></br>
<tr> <td>Issue Quantity:</td> <td><input name="issuequ" type="text" id="issuequ"/></td></tr></br><tr></tr>
<tr><td>Remark:</td> <td><input name="remark" type="text" style="width:250px; height:23px" id="remark"/></td></tr></br>
<tr><td colspan="6"><center><input type="submit" value="submit"></center></td></tr>
</table>
</form>
When I alert(data) I am getting this samsung20.00. where samsung is description and 20.00 is bal. I want to assign description desc id an bal to bal id. So How do I do that??
In your ajax.php file, you need to use json_encode function so you can parse it after get response:
include "db.php";
$itemcode=$_POST['itemcode'];
$sql="select * from itemmaster where Item_Code='$itemcode'";
$result = mysql_query($sql, $con);
while($row = mysql_fetch_array($result)) {
$json = array("Item_Desc" = > $row['Item_Desc'],
"Balance_Stock" => $row['Balance_Stock']
);
}
echo json_encode($json);
After making adjusts that you can encode your response, Your ajax need to parse it.
Example:
<script type="text/javascript">
$(document).ready(function(){
$('#itemcode').blur(function(){
var itemcode = $(this).val();
$.ajax({
type: "POST",
url:'ajax.php',
data: {'itemcode' : itemcode} ,
cache: false,
success: function(data) {
var obj = JSON.parse(data);
$("#desc").html(obj.Item_Desc);
$("#bal").html(obj.Balance_Stock);
}
});
});
});
Its very simple.
Hope it helps you
in your php file join the value Samsung and 20.00 with || sign
include "db.php";
$itemcode=$_POST['itemcode'];
$sql="select * from itemmaster where Item_Code='$itemcode'";
$result = mysql_query($sql, $con);
while($row = mysql_fetch_array($result)) {
echo $row['Item_Desc'].'||'.$row['Balance_Stock'];
}
java script code add the var response = data.split('||'); function
<script type="text/javascript">
$(document).ready(function(){
$('#itemcode').blur(function(){
var itemcode = $(this).val();
$.ajax({
type: "POST",
url:'ajax.php',
data: {'itemcode' : itemcode} ,
cache: false,
success: function(data) {
alert(data)
var response = data.split('||');//spilt the value
$("#desc").val(response[0]);
$("#bal").val(response[1]);
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#itemcode').blur(function(){
var itemcode = $(this).val();
$.ajax({
type: "POST",
url:'ajax.php',
data: {'itemcode' : itemcode} ,
cache: false,
success: function(data) {
alert(data)
var str1 = data.replace(/\d.+/g, '');
var str2 = data.replace(/[^\d.-]/g, '');
$("#desc").val(str1);
$("#bal").val(str2);
}
});
});
});
</script>

Ajax not posting when value based on selectbox

What I have here is ajax that's post information into textbox from database. This ajax work's in input field, but when I tried to use select box it doesn't working. Why is that?
not working
<select id="tag"><option value="">none</option><option value="crs">crs</option></select>
working
<input name="tag" id="tag" type="text" value="" />
Index.php
<select id="tag"><option value="">none</option><option value="crs">crs</option></select>
<input name="output" id="output" type="text" value="" />
<script type="text/javascript">
$(document).ready(function()
{
$('input[id="tag"]').change(function()
{
var prjt_code = $("#tag").val();
$.ajax({
type: "POST",
url: "autocomplete-ajax.php",
data :"prjt_code="+prjt_code,
dataType:'html',
type:'POST',
success:function(data){
//alert(data);
$('#output').val(data);
}
});
return false;
});
});
</script>
autocomplete-ajax.php
<?php
if(isset($_POST['prjt_code'])) {
$prjt_code = $_POST['prjt_code'];
$sql = $mysqli1->query("SELECT * FROM project WHERE project='$prjt_code'");
while($row1 = $sql->fetch_assoc())
{
$code = $row1['project_code'];
}
echo $code;
}
?>
You are targeting input[id="tag"] when you want select[id="tag"]
http://jsfiddle.net/releaf/U28jb/
$(document).ready(function() {
$('select[id="tag"]').on('change', function() {
var prjt_code = $("#tag").val();
alert(prjt_code);
$.ajax({
type: "POST",
url: "autocomplete-ajax.php",
data :"prjt_code="+prjt_code,
dataType:'html',
type:'POST',
success:function(data){
//alert(data);
$('#output').val(data);
}
});
return false;
});
});

How to delete all entry from table using checkBox clickall after confirmation is true? jQuery Ajax PHP

I am trying to delete all records from the table using the checkbox. When the user checked the topmost checkbox, it will check all other checkboxes inside the loop then a confirmation box will appear about deleting the records. if the user click OK, the the all the records will be deleted using $.ajax, if he clicked Cancel, then, the page will return to the same state, and the checkboxes are not checked anymore.
<?php
include 'dbconn.php';
?>
<table border="1" >
<tr><td align="center" width="20"><input type="checkbox" name='checkALL' id='checkALL'></td><td>Name</td>
</tr>
<?php
$sql=mysql_query("SELECT * FROM names ORDER BY names ASC") or die(mysql_error());
while($rows=mysql_fetch_assoc($sql)){
?>
<tr>
<td><input type="checkbox" name="id[]" id="id[]" value="<?php print $rows['id'];?>">
</td><td>Name</td>
</tr>
<?php
}
?>
</table>
JQUERY
<script>
$(function(){
//click all
$('#checkALL').click(function(){
$(':checkbox').attr({checked: 'true'});
var del=confirm("You checked all the box. Delete All?");
if(del==true){
//delete here using $.ajax
}
else{
window.location.reload(false);
$('#checkAll').attr({checked: 'false'});
}
});
});
</script>
Place this in your if block.
$.ajax({
type: "GET",
url: '<php file which truncates table>',
success: function (data) {
if (data == 'truncated') {
alert('success');
} else {
alert('not truncated');
}
}
});
Return the string truncated from your php file on success.
Here U- PageUrl, A- Action on page, P- Parameter
if (confirm('Are you sure to delete this record?')) {
Operation(U, A, P);
}
function Operation(U, A, P) {
$.ajax({
type: "POST",
url: U + '/' + A,
data: P,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (r) {
var str = r.d;
}
});
}
You can use something like this in your HTML check all page
<html>
<head><title>Select/Delete ALL with jQuery/PHP</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<table border="1" cellpadding="5">
<tr>
<th>
<input type="checkbox" id="checkAll" />
</th>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="100" /></td>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="200" /></td>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="300" /></td>
</tr>
</table>
<script>
$(document).ready(function(){
var checked = false;
$('#checkAll').click(function(){
if (checked == false){
checked = true
} else {
checked = false
}
$('input.check').attr("checked",checked);
var confirmDelete=confirm("You checked all the box. Delete All?");
if (confirmDelete==true){
var csv = '';
$('.check').each(function() {
csv += $(this).attr("value") + ",";
});
$.ajax({
type: "POST",
url: "delete.php",
data: { tobeDeleted: csv }
}).done(function( msg ) {
console.log( "Data has been deleted: " + msg );
});
} else {
$('#checkAll').attr("checked", false);
$('input.check').attr("checked", false);
}
});
});
</script>
</body>
</html>
and use something like this in your PHP script
<?php
$postDeleted = substr($_POST['tobeDeleted'], 0, strlen($_POST['tobeDeleted'])-1);
$arrDeleted = explode(",", $postDeleted);
$sql = "DELETE FROM employee WHERE 1=1 ";
foreach($arrDeleted as $key=>$value){
$sql .= "OR employee_id = $value ";
}
echo $sql;
?>
if(del==true){
$.ajax({
type: "POST",
url: 'your_file_url',
async:false,
cache: false,
success: function(data){
if (data == 1) {
alert('success');
} else {
alert('Error');
}
}
});
}
In your php file, echo 1 for successful delete and 0 for some error

why is my ajax unable to get the currently typed string in the input form?

I have a simple form, then I placed some data from the table to each of the input forms value attribute. now my problem is, whenever i typed something new to the input form, to update the data, it's unable to pick up the currently typed string, am not sure how to solve this, because I think it is picking up the value echoed out instead of the currently typed string when on this update page,
here's my front-end
<fieldset id="personaldetails">
<legend>Personal Details</legend>
Resume Title: <input type="text" name="resumetitle" id="resumetitle" value="<?php echo $v['ResumeTitle']; ?>" size="50" maxlength="50" /><br />
Name: <input type="text" name="cvname" id="cvname" size="30" maxlength="30" value="<?php echo $v['Name']; ?>" /><br />
DOB: <input type="text" id="datepicker" name="dob" value="<?php $date = new DateTime($v['DOB']); echo $date->format('m/d/Y'); ?>" /><br />
Gender: <input type="radio" name="gender" id="gender-male" value="1" <?php if($v['Gender'] == 1){ echo "checked"; } ?>/> <b>Male</b> |
<input type="radio" name="gender" id="gender-female" value="0" <?php if($v['Gender'] == 0){ echo "checked"; } ?>/> <b>Female</b><br /><br />
<input type="hidden" name="cvid" id="cvid" value="<?php echo $v['ResumeID']; ?>" />
<button name="pdetails" id="pdetails">Update</button>
</fieldset><br /><br />
//here's my js
$(document).ready(function(){
var resumetitle = $('#resumetitle').val();
var cvid = $('input[type="hidden"]').val();
var name = $('#cvname').val();
var dob = $('#datepicker').val();
var gender = $('input[name="gender"]:checked').val();
$('button#pdetails').click(function(){
$.ajax({
type: "POST",
url: "classes/ajax.resumeupdate.php",
data: "resumeid="+cvid+"&resumetitle="+resumetitle+"&name="+name+"&dob="+dob+"&gender="+gender,
success: function(){
//window.location = "resumeview.php?cvid="+cvid;
},
});
});
});
//here's my php code
require 'class.resume.php';
$db = new Resume();
if(isset($_POST['resumetitle']) || isset($_POST['name']) || isset($_POST['dob']) ||
isset($_POST['gender']) || isset($_POST['cvid'])){
$result = $db->updatepdetails($_POST['resumetitle'],$_POST['name'],$_POST['dob'],$_POST['gender'],$_POST['cvid']);
if($result){
echo "success!";
} else {
echo "failed! ".$db->error;
}
}
You are only reading the values on document ready, move that code into the click event:
$(document).ready(function(){
$('button#pdetails').click(function(){
var resumetitle = $('#resumetitle').val();
var cvid = $('input[type="hidden"]').val();
var name = $('#cvname').val();
var dob = $('#datepicker').val();
var gender = $('input[name="gender"]:checked').val();
$.ajax({
type: "POST",
url: "classes/ajax.resumeupdate.php",
data: "resumeid="+cvid+"&resumetitle="+resumetitle+"&name="+name+"&dob="+dob+"&gender="+gender,
success: function(){
//window.location = "resumeview.php?cvid="+cvid;
},
});
});
});
Your javascript is resolving the form values just once (on page load), so if you enter something after the page has loaded, the variables don't change.
You can simply calculate the values inside the Ajax callback instead. But what you really should do is use jQuery's $.serialize() function, which creates a standard a=1&b=2&c=3 querystring including the (properly escaped) form data:
$(function(){
$('button#pdetails').click(function(){
$.ajax({
type: "POST",
url: "classes/ajax.resumeupdate.php",
data: $('form').serialize(),
success: function(){
//window.location = "resumeview.php?cvid="+cvid;
}
});
});
});
Also note that you had a trailing comma after the success function - this will fail in IE so I've changed that as well.

Categories