Hello friends this i am facing some problem...I have multiple check boxes and by selecting each check box i am inserting the users details to database by Ajax. the records records are inserting to database but my problem is that , suppose i have 5 users in the page, suppose i am selecting the 3 user check boxes and submit , and if the insertion succeed then i want that the 3 selected users will not shown on page. i use Google many tips but can't solve the problem.
//this is the menu.php
<li class="invitetab"><span>Invite</span></li>
$('.invitetab').one('click', function(){
var rp = '<?php echo $baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $_SESSION['db_user_info']['id'] ?>';
$( document ).ready(function() {
$.ajax({
url: ""+rp+"invite.php?pageid="+v+"&userid="+userid,
type: 'POST',
beforeSend: function()
{
$("#loading_img").show();
},
success: function(data)
{
$("#loading_img").hide();
$("#Invite").append(data);
}
});
});
});
//And this is the invite.php
$('.gr-post-btn-submit').click(function(){ // when a feature button is selected
var rp = '<?php echo $config->baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $user_id ?>';
var serialize = $('.abc').serialize(); // takes all the values of the filter
$.ajax({
type : 'POST',
url: ""+rp+"sendinv.php?pageid="+v+"&userid="+userid, // sends the values to ajax file
data : serialize,
beforeSend: function()
{
$("#loading_own").show();
$("#Invite").css({ opacity: 0.5 });
},
success: function(data)
{
$("#loading_own").hide();
$("#Invite").css({ opacity: 5.6 });
// $("#Invite").show();
//this is the portion where we have to do some thing to hide the inserting check boxes
}
});
});
<form method="post" class="abc" id="" name="inviteform"
enctype="multipart/form-data" action="#">
<?php
$sql = "select * from gr_user_friendships where toid=$user_id and status = 1";
$pagd = $_GET['pageid'];
$liked_users = $db->select($sql);
$count = 0;
for($i=0; $i<count($liked_users); $i++)
{
$extrct_fr = "select * from gr_page_likes where page_id=".$pagd." and receiver_id=".$liked_users[$i]['fromid'];
//echo $extrct_fr;
$frnd = $db->select($extrct_fr);
if(count($frnd)>0)
{
$invt = $db->select("select * from gr_user_friendships where toid=$user_id and fromid!=$frnd[0]['receiver_id']");
$invt_id = $invt[0]['fromid'];
}
else
{
$invt_id = $liked_users[$i]['fromid'];
}
if(!empty($invt_id))
$count = 1;
$user = "Select * from gr_users where id = $invt_id";
//echo $user;
$table = mysql_query($user);
$dbc = mysql_fetch_array($table);
$usid= $dbc['id'];
$bab = $dbc['name'];
$imgs = $dbc['avatar'];
$image_of_fr = $_SERVER['DOCUMENT_ROOT']."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
$image_location_f = $config->baseUrl."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
if(file_exists($image_of_fr))
{
$imgp = $image_location_f;
}
else
{
$imgp = $config->baseUrl."/themes/gr-mist/includes/images.jpg";
}
if(!empty($invt_id)){
?>
<style type="text/css">
#users_<?php echo $invt_id ?>
{
width:147px;
height:54px;
display:inline-block;
}
</style>
<input type="checkbox" class="checkbox1" id="gcc_<?php echo $invt_id ?>" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
<?php
}
}//end of for
?>
<br>
<?php if($count){ ?>
<span style="color:blue; font-weight:bold;" >
<input type="checkbox" id="selecctall"/> Select All</span>
<input type="button" name="gr_submits" class="gr-post-btn-submit" value="invite" id="submits"/>
<?php } ?>
</form>
and this is the sendinv.php
global $db;
$myliker = $_POST['pgliker'];
$pageid = $_GET['pageid'];
$userid = $_GET['userid'];
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
}
/**In you invite.php put the element which you want to hide after success
form submission into one div*//
//replace your one with this one.
<div id="gcc_<?php echo $invt_id ?>">
<input type="checkbox" class="checkbox1" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
</div>
/**Now make an array in your sendinv.php and encode it with json incode***/
//replace your sendinv.php with this one.
$arr = array();
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
$arr[] = $tps;
}
echo json_encode($arr);
exit;
/**After in your invite.php in the success block run
jquery foreach with the data and hide the checked boxes with the ids associted after submission. */
$.each( data, function( key, value ) {
// alert( key + ": " + value );
$("#gcc_"+value).hide();//the div for each checked user
});
Related
I am deleting records with ajax and php. When I click the button it erases the record but when I click to delete another record it does nothing. What am I doing wrong?
HTML
<form id="prop_remove">
<input type="hidden" name="id" id="last_id" value="<?php echo $id; ?>">
<input type="hidden" name="user" id="last_user" value="<?php echo $user; ?>">
<input type="button" name="submit" id="last_prop" class="button fullwidth margin-top-5" value="Delete">
</form>
AJAX
<script>
$(document).ready(function() {
$('#last_prop').click(function() {
var id = $('#last_id').val();
var user = $('#last_user').val();
$.ajax({
url: "delete.php",
method: "POST",
data: {
ilan_id: id,
ilan_user: user
},
success: function(response) {
if (response == 1) {
$('#last_prop').closest('tr').css('background', 'tomato');
$('#last_prop').closest('tr').fadeOut(800, function() {
$(this).remove();
});
} else {
alert('Invalid id');
}
}
});
});
});
</script>
PHP
<?php
require_once 'config.php';
$id = $_POST['ilan_id'];
$user = $_POST['ilan_user'];
$checkRecord = "SELECT * FROM last_tbl WHERE id = '$id' AND user = '$user'";
$check_result = mysqli_query($conn, $checkRecord);
$totalrows = mysqli_num_rows($check_result);
if($totalrows > 0){
$delete_sql = "DELETE FROM last_tbl WHERE id = '$id' AND user = '$user';";
$delete_result = mysqli_query($conn, $delete_sql);
echo 1;
exit;
}
?>
Your problem is that you're overwriting the HTML element IDs. You can remove your forms and use a single button instead, and pass data through the data attribute of the buttons.
Replace your form by a single button
<button class="button fullwidth margin-top-5 last_prop" data-last-id="<?= $id; ?>" data-last-user="<?= $user; ?>">Delete</button>
Then adapt your jQuery to use the class last_prop instead of the ID, and fetch the values from the data attributes we set above.
<script>
$(document).ready(function () {
$('.last_prop').click(function () {
var id = $(this).data('last-id');
var user = $(this).data('last-user');
$.ajax({
url:"delete.php",
method: "POST",
data: {ilan_id: id, ilan_user: user},
success:function(response){
if (response == 1 ){
$('#last_prop').closest('tr').css('background','tomato');
$('#last_prop').closest('tr').fadeOut(800,function(){
$(this).remove();
});
} else {
alert('Invalid id');
}
}
});
});
});
</script>
Also, your query can be reduced to one (you don't need that SELECT), and should be with a prepared statement.
<?php
require_once 'config.php';
$id = $_POST['ilan_id'];
$user = $_POST['ilan_user'];
$sql = "DELETE FROM last_tbl WHERE id = ? AND user = ?;";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $id, $user);
$stmt->execute();
if ($stmt->affected_rows) {
// rows were deleted
echo 1;
}
$stmt->close();
I'm trying to receive post data with php from ajax in same page but seems like i have some issues that i have no idea to solve them
here is my html/php code :
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php
while ($row = $result->fetch_assoc())
{
echo "<option value=".$row['N_omran'].">".$row['N_omran']."</option>";
}
?>
</select><br>
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row) {
echo " <h4>Nom : {$row['nom']}</h4>
<h4>Prénom : {$row['prenom']}</h4>
<h4>Téléphone : {$row['tel']} </h4>
<h4>Maticule d'assurance : {$row['matricule_assu']}</h4>
<h4>Adresse : {$row['adress']}</h4>";
}
} ?>
And here is my Ajax post request :
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function () {
alert("Post request successfully done")
}
});
}
});
the code below can replace all your data with the new ones with clean writing :)
// get data from Database
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
} ?>
// show rows to be selected
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?= $row['N_omran'] ?>"> <?= $row['N_omran'] ?></option>
<?php } ?>
</select><br>
// show recieved data
<?php if ($row) { ?>
<div id="informations">
<h4>Nom : <span id="nom"><?= $row['nom'] ?></span></h4>
<h4>Prénom : <span id="prenom"><?= $row['prenom'] ?></span></h4>
<h4>Téléphone : <span id="tel"><?= $row['tel'] ?> </span></h4>
<h4>Maticule d'assurance : <span id="matricule_assu"><?= $row['matricule_assu'] ?></span></h4>
<h4>Adresse : <span id="adress"><?= $row['adress'] ?></span></h4>
</div>
<?php } ?>
// script for making ajax call
<script>
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function (response) {
$("#nom").text(response.nom);
$("#prenom").text(response.prenom);
$("#tel").text(response.tel);
$("#matricule_assu").text(response.matricule_assu);
$("#adress").text(response.adress);
}
});
}
});
</script>
$json_data=file_get_contents('php://input');
$json=json_decode($json_data,true);
if(array_key_exists("selectName",$json)){
$selectOption =$json["selectName"];
}
I want Ajax to apply only in the div (#usersDiv)
When selector is changed into 'body' it loads the whole page repeatedly. (Cannot type in the box)
but when selector changed as #userDiv, it shows the search box twice in the page. In the first box can be typed, but again second box loads over and over.
PHP file is as follows (test.php)
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function users($connection){
if(!empty($_POST)){
$country = $_POST['userCountry'];
$sql = "SELECT * FROM users WHERE country = '$country' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userName = $row['username'];
$city = $row['city'];
echo '<div><h4>'. $userName. " ". $city. '</h4></div>';
}
} else {
echo "Use search box!";
}
} else {
echo "Use Search Box!";
}
}
?>
<html>
<head><script src = "jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("http://freegeoip.net/json/", function(data) {
var country = data.country_name;
$.ajax({
method:"POST",
url:"test.php",
data:{userCountry:country},
success:function(result){
$('#usersDiv').html(result);
}
});
});
});
</script>
</head>
<body>
<form name = "searchForm" action = "search.php" method = "POST">
<input type = "text" name = "searchPlace" required />
<input type = "submit" value = "Search"/>
</form>
<div id = "usersDiv"> <?php users($connection); ?> </div>
</body>
<html/>
I have altered your code to wrap your PHP function within an if($_POST) to prevent the entire page loading
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
if($_POST){ // Check if form has been submitted
$country = $_POST['userCountry'];
$sql = "SELECT * FROM users WHERE country = '$country' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userName = $row['username'];
$city = $row['city'];
echo '<div><h4>'. $userName. " ". $city. '</h4></div>';
}
} else {
echo "Use search box!";
}
}else{ // If it hasn't then show the search form
?>
<html>
<head><script src = "jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#searchForm").on("submit",function(e){ // Check for form submission
$.getJSON("http://freegeoip.net/json/", function(data) {
var country = data.country_name;
$.ajax({
method:"POST",
url:"test.php",
data:{userCountry:country},
success:function(result){
$('#usersDiv').html(result);
}
});
});
});
});
</script>
</head>
<body>
<form name = "searchForm" action = "search.php" method = "POST" id="searchForm">
<input type = "text" name = "searchPlace" required />
<input type = "submit" value = "Search"/>
</form>
<div id = "usersDiv"></div>
</body>
<html/>
<?php } ?>
As Alexander suggests, read up on SQL Injection
How can I prevent SQL injection
I have this website wherein I need to debug, but I can't seem to get the data from this checkbox ..
<?php
foreach ($callers as $block)
{
if($block->block_status==1)
{?>
<div class="col-md-1">
<input type="checkbox" name="block_cb[]">
</div>
<input class="block_id" name="block_id[]" type="hidden"
value="<?php echo $block->id;?>">
<div class="col-md-6"> <?php echo $block->block_number;?></div>
<div class="col-md-5"><?php echo $block->block_date;?></div>
</div>
</div>
</div>
<?php
}
}
?>
And I have this button ..
<button class="btn btn-danger" href="<?php echo base_url(); ?>admin/block/update/<?php echo $block->id;?> "id="unblock">Unblock</button>
This goes to the function updateblock()
Eventually discovered this Javascript, but don't know how to apply this script to the code above.
function unBlock(){
var id = [];
var status = [];
var curpage = $('#curpage').val();
hidden = [];
$('input[name="block_id[]"]').each(function(){
id.push($(this).val());
});
$('input[name="block_cb[]"]').each(function(){
if($(this).is(':checked'))
{
toastr.success('Number Unblocked');
status.push(0);
var hiddenpush = $(this).parents('#idfind').find('.block_id').val();
hidden.push(hiddenpush);
$(this).parents('.gbItem').addClass('hidden');
}
else{
status.push(1);
}
for(var a = 0; a < id.length ; a++){
$.ajax({
url: "<?php echo base_url(); ?>"+curpage+"/dashboard/updateblock",
type: 'POST',
data:{
'user_id' : id[a],
'block_status': status[a],
},
});
}
This is where the link goes.
function updateblock(){
//This is the original code.
$id = $_POST['id'];
$data['block_status'] = $_POST['block_status'];
$this->block_model->update_blocked_number($id,$data);
/*
$id = $id;
//$data['block_status'] = $this->uri->segment(5);
$data['block_status'] = 111;
$this->block_model->update_blocked_number($id,$data);
*/
}
How can I get the data from the checkboxes (which is an array) to the button. I'll be passing the ID from the URL. Thank you.
E.g link/here/6 where 6 should be the ID I should get from the checkboxes.
You can try this
<?php echo anchor(BASE_URL.'link/here','Unblock',
array('class'=>"btn btn-danger",'onClick'=>'unBlock()')); ?>
OR
<?php echo anchor(BASE_URL.'link/here','Unblock', 'class="btn btn-danger new-action"'); ?>
$('.new-action').click(function(e){
e.preventdefault();
var id = [];
var status = [];
var curpage = $('#curpage').val();
hidden = [];
$('input[name="block_id[]"]').each(function(){
id.push($(this).val());
});
$('input[name="block_cb[]"]').each(function(){
if($(this).is(':checked'))
{
toastr.success('Number Unblocked');
status.push(0);
var hiddenpush = $(this).parents('#idfind').find('.block_id').val();
hidden.push(hiddenpush);
$(this).parents('.gbItem').addClass('hidden');
}
else{
status.push(1);
}
});
I have a code in which i am having checkboxes of two categories one of brand and and other of discount percentage.Based on those checkboxes,div s are getting filtered.Filteration of divs is happening ok but with a small issue.
Below is the firstphp page
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
#image{
width:250px;
height:250px;
border:1px solid black;
}
</style>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_disc_value(){
var d_value=[];
$('input[name="discount"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
checkboxValidate = function (e) {
if(e)e.preventDefault();
alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var disc=get_disc_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
// alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,disc:disc},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
}
$( "[type=checkbox]" ).change(checkboxValidate);
checkboxValidate();
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" id="check" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" id="check"/>Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="discount" value="10" />10
<br/>
<input type="checkbox" name="discount" value="20" />20
<br/>
<input type="checkbox" name="discount" value="30" />30
<br/>
<button id="btnSubmit">sort</button>
<div id="image">
<img src="http://img5a.flixcart.com/image/sunglass/4/u/y/mb-d4-09b-miami-blues-free-size-275x275-imadzkhuchryqjgp.jpeg" width="250px" height="250px"/>
</div>
<div id="results">
sdfsdfsdfsdfdsfgsdgsbsfgvf
</div>
</body>
</html>
Asortingajax.php-where i m checking with database
<?php
include('connection.php');
$query=$_POST['ser'];
$query2=$_POST['disc'];
$query=explode(",",$query);
$query = array_filter($query);
$query2=explode(",",$query2);
$query2 = array_filter($query2);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $query;
echo $query1;
echo $result1;
$parts = array();
$brandarray=array();
$discarray=array();
$limit = 10;
$offset = 0;
foreach( $query as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
foreach( $query2 as $discword ){
$discarray[] = '`DPERCENT` < '.$discword.'';
}
if(!empty($query) && !empty($query2))
{
echo "both loops";
$countsql2='SELECT * FROM xml WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') ';
print($countsql2);
$combinesql=mysql_query($countsql2);
$androws123 = mysql_num_rows($combinesql);
$countArray1=array();
echo "<br />";
echo $androws123;
$totalrows=0;
$orsqlrows=0;
while($row = mysql_fetch_array($countsql3)) {
// Append to the array
$countArray1[] = $row;
//echo $row['PID']."<BR />";
}
if(empty($countArray1))
{
echo "or";
$orsql='SELECT * FROM xml WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') ';
$orsql1=mysql_query($orsql);
$orsqlrows = mysql_num_rows($orsql1);
$countArray2=array();
echo $orsqlrows;
while($row = mysql_fetch_array($countsql1)) {
// Append to the array
$countArray2[] = $row;
//echo $row['PID']."<BR />";
}
}
$totalrows=$orsqlrows+$androws123;
echo $orsqlrows;
echo "hi";
echo $androws123;
if($totalrows==$androws123)
{
echo "and";
foreach( $brandcheck as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') limit '.$offset.', '.$limit.' ';
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
//print($brandsql);
echo "<br />";
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
else{
foreach( $brandcheck as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
echo "orloop";
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$brandarray).') AND ('.implode ('OR',$discarray).') limit '.$offset.', '.$limit.' ';
//print($brandsql);
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
//print($brandsql);
echo "<br />";
echo $numrows;
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
}
?>
<?php
foreach($countArray as $array)
{
?>
<div>
<img src="<?php echo $array['IMAGEURL']?>"/></div>
<?php $i++; } ?>
I n the first php page.when i m checking one brand checkbox and one discount checkbox at a time,means one from both brand and discount are checked.div s are getting filtered correctly.but when i check two checkboxes out of discount checkboxes and one from brand,I am not getting divs filtered correctly whereas div s should get filtered.
Help me guys where i m doing wrong in above code...
Have you echoed the query to see what you get? It seems to me it's working fine as long as there's no actual implode 'glue' used (the 'OR'). I think you need to change the glue part to ' OR ' (notice the spaces around it).