how to put condition alert box in ajax - javascript

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.

Related

How can I pass id of multiple row selection to print page at the time of inserting data

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();

Requesting data from php through ajax

Trying to request the posts made by users and loading more posts on user's request.
Getting Unexpected end of JSON input error while making ajax request in console.
Javascript
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
url: "action.php?action=morePosts",
success: function(response){
var result = $.parseJSON(response);
console.log(result);
}
});
});
Making request to following code.
$_SESSION['posts']) stores the number of posts to be loaded in the session.
if($_GET['action']=="morePosts"){
if(isset($_SESSION['posts'])){
$_SESSION['posts'] = $_SESSION['posts'] + 4;
echo fetchAllPosts($_SESSION['posts']);
} else if(isset($_SESSION['posts'])&& $_SESSION['posts']>4){
$_SESSION['posts'] = 4;
}
}
Function for requesting all posts
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
for($i=0; $i<$array_length; $i++){
if(!empty($row[$i])){
for($j=0;$j<count($row);$j++){
$post['id']=$row[$i][0];
$post['user_id']=$row[$i][1];
$post['title']=substr($row[$i][2], 0 ,75);
$post['text']=strip_tags(mb_substr($row[$i][3],0,50));
$post['image']=$row[$i][4];
$post['date']=$row[$i][5];
}
return json_encode($post);
}
elseif(empty($row[count($row)])){
return json_encode(array());
}
}
}
Please suggest better ways of achieving this functionality,
Try to use echo instead of return and change ajax like also you din not echo the code inside elseif part:
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
dataType: "json",
url: "action.php?action=morePosts",
success: function(response){
console.log(response);
}
});
});
try this :
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
if($result && mysqli_num_rows($result) > 0) {
foreach($row as $key=>$value){
$post[$key]['id']=$value['id'];
$post[$key]['user_id']=$value['user_id'];
$post[$key]['title']=substr($value['title'], 0 ,75);
$post[$key]['text']=strip_tags(mb_substr($value['text'],0,50));
$post[$key]['image']=$value['image'];
$post[$key]['date']=$value['date'];
}
return json_encode($post);
}
return json_encode(['error'=>"no post found"]);
}

How can i use this kind of var in AJAX?

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();
?>

How to access function in separate PHP page using jquery ajax process?

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)

Ajax separate data which came from mysql

I am doing an ajax call like this:
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("image").attr('src',data);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
This is my ajax.php:
<?php
$connection = mysql_connect ("",
"", "");
mysql_select_db("");
// QUERY NEW ONE
$myquery = "SELECT * FROM mytable ORDER BY rand() LIMIT 1";
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
echo $currenturl,$currentnam, $currenturl,$currentimage;
}
mysql_close($connection);
?>
My data variable from the ajax call now contains all variables at once:
($currenturl,$currentnam, $currenturl,$currentimage)
How can I separate them so I can do something like:
request.done(function(data) {
$("id").attr('src',data1);
$("name").attr('src',data2);
$("url").attr('src',data3);
$("image").attr('src',data4);
});
jQuery :
$.ajax({
type:"POST",
url:"ajax.php",
dataType:"json",
success:function(response){
var url = response['url'];
var name = response['name'];
var image = response['image'];
// Now do with the three variables
// $("id").attr('src',data1);
// $("name").attr('src',data2);
// $("url").attr('src',data3);
// $("image").attr('src',data4);
},
error:function(response){
alert("error occurred");
}
});
From your code:
echo $currenturl,$currentnam, $currenturl,$currentimage;
Replace the above line with the code below:
$array = array('url'=>$currenturl, 'name'=>$currentname, 'image'=>$currentimage);
echo json_encode($array);
instead of string return an array i.e. use json type for returning value
i.e instead of
echo $currenturl,$currentnam, $currenturl,$currentimage;
use
echo json_encode array('current' => $currenturl,'currentnam' => $currentnam, 'currenturl' => $currenturl,'currentimage' => $currentimage);
and also write 'dataType' as 'json' in ajax

Categories