I have a problem with my code. I am studying jquery ajax. And I have a difficulty in it. I am creating an 'add to cart' function in my simple e-commerce site. And I am doing this with database interaction. Here's what I did so far.
Here's my PHP part
$product_id = $_GET['product'];
....
<input type="hidden" name="cart_product_id" id="cart_product_id" value="<?php echo $product_id; ?>" />
<input type="hidden" name="cart_user_id" id="cart_user_id" value="<?php echo $_SESSION['member']; ?>" />
Here's my javascript part
function notification_message(type) {
var confirmation = '';
if(type == 'cart') {
confirmation = '#cart_confirm';
} else {
confirmation = '#wishlist_confirm';
}
$(confirmation).dialog({
resizable: false,
height: 220,
modal: true,
draggable: false,
buttons: {
"Yes": function() {
if(type == 'cart'){
add_cart();
} else {
add_wishlist();
}
},
"No": function() {
$( this ).dialog( "close" );
}
}
});
}
//this is the main function I need to process
function add_cart(){
var cart_product_id = $("#cart_product_id").val();
var cart_user_id = $("#cart_user_id").val();
var url_add_cart = '<?php echo $_SERVER['DOCUMENT_ROOT'].'ahm/secure/aroma/aroma_shop.php'; ?>';
console.log(url_add_cart);
$.ajax({
type: 'POST',
url: url_add_cart,
data: { user_id: cart_user_id, product_id: cart_product_id },
dataType: 'json',
success: function(d) {
console.log(d);
}
});
}
function add_wishlist(){
alert('wishlist');
}
$('#register_user').click(function(){
$('#failed').dialog('close');
});
function failed() {
$("#failed").dialog({
resizable: false,
height: 220,
modal: true,
draggable: false,
});
}
$(document).ready(function(){
$("#mycart").click(function(){
var product_id = $('#mycart').data('cart-id');
var member_id = '<?php echo $_SESSION[member]; ?>';
var type = 'cart';
notification_message(type);
});
$("#mywishlist").click(function(){
var product_id = $('#mywishlist').data('wishlist-id');
var member_id = '<?php echo $_SESSION[member]; ?>';
var type = 'wishlist';
if (member_id == '') {
failed();
} else {
notification_message(type);
}
});
});
Now here's my separate PHP file that contains the sql query it contains.
function get_cart($user_id) {
$query = mysql_query("SELECT * FROM product_cart WHERE user_id = ".$user_id."");
$row = mysql_fetch_array($query);
return $row;
}
function count_cart($user_id) {
$query = mysql_query("SELECT COUNT(*) AS cart_total FROM product_cart WHERE user_id = ".$user_id."");
$row = mysql_fetch_array($query);
return $row['cart_total'];
}
//now, how can I access here the variable I set in the PHP?
function insert_cart(){
//this should be the query part but I dont know how to access the variable
}
In ajax call, you can pass some variable with the url, say url_add_cart+"type=insert_cart"
Then at start of PHP, check-
if(isset($_GET['type'] == "insert_cart"))
echo insert_cart();
Now, in that function just get your variables as- $_POST['user_id'] and $_POST['product_id']; do the processing and return whatever you want to return.
Note, return your array after json encoding it- echo json_encode($result_array) - also, use echo not return; since ajax call just get the contents of the url (just like curl)
Related
I am inserting data successfully by selecting multiple row table data but at the same time I want to print data on print page.
In above image I select only 3 record and insert in data base at the time of insert that selected data I want show on my print page.
Create page:
<form>
<table id="pending_collection_table"> </table>
<input type="button" id="allocate" value="allocate" name="allocate">
</form>
<script>
$('#allocate').click(function (event) {
event.preventDefault();
var allVals = [];
$('input[name=selectedBilties]:checked').each(function() {
allVals.push($(this).val());
});
var formData = new FormData();
var agent = $('#agent').val();
var rec_type = $('#rec_type').val();
formData.append("agent",agent);
formData.append("rec_type",rec_type);
for (var i = 0; i < allVals.length; i++) {
formData.append('due_ids[]', allVals[i]);
}
alertify.confirm('Payment Recovery Allocation', 'Do you want to Allocate ?', function(){
$.ajax({
url :"<?php echo base_url();?>crossing/payment_rec_allocation/PaymentRecAllocationController/createPaymentAllocation",
type:"POST",
dataType: "json",
data:formData,
contentType:false,
cache:false,
processData:false,
success: function(data){
if(data.PaymentRecAllocation.form_status=='false'){
}
else if(data.PaymentRecAllocation.form_status=='true'){
alertify.confirm('Payment Recovery Allocation', 'Do you want to print ? ', function(){
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
setTimeout(location.reload.bind(location), 2000);
},
function(){
location.href="<?php echo base_url(); ?>", 'refresh';
});
}
}
});
}, function(){
});
});
</script>
Contoller:
public function createPaymentAllocation()
{
$bilty_ids = $this->input->post('due_ids');
$biltyCount = count($bilty_ids);
$agent = $this->input->post('agent');
$due_to = $this->input->post('due_to');
for($i = 0; $i < $biltyCount; $i++) {
$data = array(
'agent_id' =>$agent,
'pay_dueto' =>$due_to,
'mr_no' =>$bilty_ids[$i],
);
$modelResult = $this->PayRecAllModel->inserPaymentAllocation($data);
}
if($modelResult){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate'
);
}else{
$data['PaymentRecAllocation'] = array(
'form_status' => 'false',
'form_message' => 'Something went wrong.'
);
}
echo json_encode($data);
}
Model:
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
return true;
}else {
return false;
}
}
And now my print function on controller
public function printCollectionRecPage(){
$this->load->view('template/header');
$data= array();
$data['collnR'] = $this->PayRecAllModel->printCollectionRecPage();
$this->load->view('crossing/payment_rec_allocation/printCollectionRecovery',$data);
$this->load->view('template/footer');
}
model of print page:
public function printCollectionRecPage(){
$this->db->select('*');
$this->db->from('payment_rec_allocn');
$this->db->join('crossing_cash_memo', 'payment_rec_allocn.mr_no = crossing_cash_memo.mr_no');
$this->db->where('total !=','0');
$query = $this->db->get();
return $query->result();
}
How I can pass ids in print page.
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
How can I pass that selected ids on print page.
And my print page I have table to show data of selected data on inset time.
You can use insert_id() function
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
$insert_id = $this->db->insert_id();
return $insert_id;
}else {
return false;
}
}
store returned ids into array
$modelResult[] = $this->PayRecAllModel->inserPaymentAllocation($data);
if(!empty($modelResult)){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate',
'form_ids' => $modelResult
);
}
Pass the ids to your controller for print
var ids = data.PaymentRecAllocation.form_ids.join(',');
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage?ids="+ids;
But in case of multiple inserts you should ideally use
$this->db->trans_start();
//all your insertion code here
//if anything breaks the db will be rollback
$this->db->trans_complete();
The Problem is in the var a I have created
<script>
$( "#EDITsave" ).click(function() {
var a = parseInt(window.id.charAt(window.id.length-1)) //a gets parsed correctly but nothing happens in ajax until i set a number myself
console.log(a)
$.ajax({
type: "POST",
datatype: "text",
url: "edit.php",
data: {
inputID: a,
inputtxt: //issue is in 'a' here!
document.getElementById("editinputtext").value
},
});
});
</script>
PHP: // PHP CODE FOR AJAX
$inputID = $_POST['inputID'];
$inputtxt = $_POST['inputtxt'];
$sql = "UPDATE Contributions SET inputtxt = '$inputtxt' WHERE inputID = $inputID";
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $connection->error;
}
$connection->close();
?>
I have a small script that runs a php file in the background and gets a variable every 3 seconds and put it in a div
script in document with div
<script>
$(document).ready(function() {
setInterval(function () {
$('#statmoney').load('safe.php');
}, 3000);
});
</script>
PHP FILE (safe.php)
$sql = "SELECT * FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$money = htmlspecialchars($row->money);
echo $money;
If i need to add another variable i would need to make a new document is there a easy way to go about it?
UPDATE
menu.php
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['money', 'ore', 'energy']; // array of needed fields
$.ajax({
type: "POST",
url: "menusafe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
console.log(response)
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
<div class="menustats"><img src="graphics/logos/moneylogo.png" class="menustatimage"><div class="menustattext" id='money'></div></div>
<div class="menustats"><img src="graphics/logos/energylogo.png" class="menustatimage"><div class="menustattext" id="energy"></div></div>
<div class="menustats"><img src="graphics/logos/orelogo.png" class="menustatimage"><div class="menustattext" id='ore'></div></div>
PHP(menusafe.php)
<?php
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
?>
Let's imagine that we want to retrieve three fields from users table : firstname, age and money. In such case it would be better to use $.post or $.ajax method:
js part:
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['firstname', 'age', 'money']; // array of needed fields
$.ajax({
type: "POST",
url: "safe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
php part: (safe.php)
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
I have status active/Deactive Buttons when user clicks on active status it turns into deactive with red color and vice versa
currently i'm able to update my status #backend but everytime i should refresh to see my changes!!
my requirement is during active/deactive process of changing status i want to load ajax image loader where loader image should overlay entire screen. and my status should be updated in mysql db!!
please any help is appricated Thanks!
Php Code
<?php
include 'db.php';
$sql = "select * from sections order by id asc";
$data = $con->query($sql);
$str='';
if($data->num_rows>0)
{
while( $row = $data->fetch_array(MYSQLI_ASSOC))
{
$str.="
"?>
<div class="row">
<div class="col-md-1">
<?php
if ($row['status'] == '1')
{
?>
<a href="#" class="btn btn-success btn-sm active" ida='<?php echo $row['id'];?>'></a>
<?php }
else if($row['status'] == '0')
{
?>
<a href="#" class="btn btn-danger btn-sm deactive" idde='<?php echo $row['id'];?>'></a>
<?php } ?>
</div>
</div>
<?php
}
}
else
{
$str .= "<p style='text-align:left;'>No Data Available</p>";
}
echo $str;
?>
Jquery Code
<script type="text/javascript">
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
$('body').delegate('.deactive','click',function(e){
var IdStatus = 1;
var id = $(this).attr('idde');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
</script>
PHP Updation Code
<?php
if(isset($_REQUEST['status']))
{
$status = $_REQUEST['status'];
$id = $_REQUEST['id'];
$sql = 'update sections set status='.$status.' where id='.$id.'';
$result = mysql_query($sql);
if($result)
{
echo 'updated successfully';
}
else
{
echo 'failed to update';
}
}
?>
Try this script with mentioned changes:
Changes:
Keep same attribute as data-id for both the operations
loaderElem will be the loader container which should be there in your DOM
BODY is nothing but a body selector, just to avoid redundant selectors
var elem = $(this); is used as I need this reference after success callback
Also make habit of using error callback as you might need to handle that case
var BODY = $('body');
var loaderElem = $('#loader');
BODY.delegate('.active', 'click', function(e) {
loaderElem.show();
var IdStatus = 0;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('active').addClass('deactive');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
BODY.delegate('.deactive', 'click', function(e) {
loaderElem.show();
var IdStatus = 1;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('deactive').addClass('active');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
Try using beforeSend option of $.ajax()
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
beforeSend: function() {
// do overlay stuff
},
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
// remove overlay stuff
alert('success');
}
});
e.preventDefault();
return false;
});
can anyone help me...how do i put an conditional alert dialog box in ajax that if the data in a query is successfully saved or the data already been saved.
I want to do is if the query is saved an alert box will pop-op same goes to if the data is already been saved.
script code:
<script type="text/javascript">
$(document).ready(function () {
$('#updates').click(function (e) {
e.preventDefault();
var data = {};
data.region_text = $('#t_region').val();
data.town_text = $('#t_town').val();
data.uniq_id_text = $('#t_uniq_id').val();
data.position_text = $('#t_position').val();
data.salary_grade_text = $('#t_salary_grade').val();
data.salary_text = $('#t_salary').val();
for(var $x=1;$x<=15;$x++) {
data['id'+$x+'_text'] = $('#id'+$x).val();
data['aic'+$x+'_text'] = $('#aic'+$x).val();
data['name'+$x+'_text'] = $('#name'+$x).val();
data['optA'+$x+'_text'] = $('#optA'+$x).val();
data['optB'+$x+'_text'] = $('#optB'+$x).val();
data['optC'+$x+'_text'] = $('#optC'+$x).val();
data['optD'+$x+'_text'] = $('#optD'+$x).val();
data['other_qual'+$x+'_text'] = $('#other_qual'+$x).val();
data['interview'+$x+'_text'] = $('#interview'+$x).val();
data['total'+$x+'_text'] = $('#total'+$x).val();
}
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
// We are using response to distinguish our outer data variable here from the response
}
});
});
});
</script>
insert.php code:
<?php
include('../connection.php');
date_default_timezone_set('Asia/Manila');
$region = #$_POST['region_text'];
$town = #$_POST['town_text'];
$uniq_id = #$_POST['uniq_id_text'];
$position = #$_POST['position_text'];
$salary_grade = #$_POST['salary_grade_text'];
$salary = #$_POST['salary_text'];
$dupesql = "SELECT * FROM afnup_worksheet WHERE funiq_id = '$uniq_id'";
$duperow = mysql_query($dupesql);
if(mysql_num_rows($duperow) > 0){
exit;
}else{
for($n=1;$n<=15;$n++) {
$id = #$_POST['id'.$n.'_text'];
$aic = #$_POST['aic'.$n.'_text'];
$name = #$_POST['name'.$n.'_text'];
$optA = #$_POST['optA'.$n.'_text'];
$optB = #$_POST['optB'.$n.'_text'];
$optC = #$_POST['optC'.$n.'_text'];
$optD = #$_POST['optD'.$n.'_text'];
$other_qual = #$_POST['other_qual'.$n.'_text'];
$interview = #$_POST['interview'.$n.'_text'];
$total = #$_POST['total'.$n.'_text'];
if(!empty($name)){
$query = "INSERT INTO afnup_worksheet (faic,fregion,ftown,funiq_id,fposition,fsalary_grade,fsalary,fnl_name,edu_attain,experience,seminars,eligibility,other_qual,interview,ftotal,dateinputed)
VALUES
('$aic','$region','$town','$uniq_id','$position','$salary_grade','$salary','$name','$optA','$optB','$optC','$optD','$other_qual','$interview','$total',CURRENT_TIMESTAMP)";
$resource = mysql_query($query) or die(mysql_error());
}
}
}
?>
Just return that status from PHP:
if(mysql_num_rows($duperow) > 0){
echo "1"; // Dup status
exit;
}else{
// All your else code.. echo must be the last thing inside your else block
echo "2"; // Saved status
}
Then in your ajax success callback you check it:
$.ajax({
type: "POST",
url: "insert.php",
data: data,
cache: false,
success: function (response) {
if (Number(response) == 1)
{
alert("Dup message");
}
else
{
alert("Saved message");
}
}
});
Instead of exit; in your conditinal for dupes, you could echo "duplicate". Also you should remove die() after your $resource and add if ($resource) echo "ok"; else echo "error";
Then in your success function(response) in javascript you can do if (response=="...") echo duplicate; else if ...
This is just basic explanation, but it should be enough to point you in the right direction.