JQuery Calls Itself Recursively - javascript

I have a table that shows userid, name, internetstatus, button
If internet status is 0, when I click on the button it will update the database as 1 and vice versa.
Also row['internet'] == 0 //Red button and row['internet'] == 1 //Green button. When I click on Red Button internet's value will be changed to 1 and and vice versa.
Everything works as intended. The only problem is, when I click on User #2's button (according to image), it will also affect User #3 and both will be updated. If they all have the same status, then all will be updated instead of only clicked one.
What part should I fix to code work as intended?
Main Page:
...table code...
//If internet == 0, Red Button will display
if($row['internet'] == 0) {
echo "<td><button type='submit' style='width:100%' class='btn btn-danger' value='ariza' id='".$row['id']."'>Problem</button></td>
<script src='https://code.jquery.com/jquery-2.2.2.min.js'></script>
<script>
$(document).ready(function() {
$('.btn-danger').click(function() {
var clickBtnValue = $(this).val();
var kullanici = ".$row['id'].";
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue,
'kullanici': kullanici
};
$.post(ajaxurl, data, function(response) {
// Changes
$('#ariza').removeClass('btn-danger');
$('#ariza').addClass('btn-success');
$('#ariza').html('Düzeltildi');
$('#var').html('Arızalı');
$('#var').css('color', 'red');
alert(response);
setTimeout(function() {
location.reload();
}, 2000);
});
});
});
</script>";
// If internet == 1, Green Button will display
} else {
echo "<td><button type='submit' style='width:100%' class='btn btn-success' value='duzelt' id='".$row['id']."'>OK</button></td>
<script src='https://code.jquery.com/jquery-2.2.2.min.js'></script>
<script>
$(document).ready(function() {
$('.btn-success').click(function() {
var clickBtnValue = $(this).val();
var kullanici = ".$row['id'].";
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue,
'kullanici': kullanici
};
$.post(ajaxurl, data, function(response) {
// Changes
$('#duzelt').removeClass('btn-success');
$('#duzelt').addClass('btn-danger');
$('#duzelt').html('Arızalı');
$('#yok').html('Var');
$('#yok').css('color', 'green');
alert(response);
setTimeout(function() {
location.reload();
}, 2000);
});
});
});
</script>";
}
ajax.php:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'duzelt':
isaretle_arizali();
break;
case 'ariza':
isaretle_duzeltildi();
break;
}
}
Functions.php:
function isaretle_arizali()
{
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$content = $_POST['kullanici'];
$int = 0;
if ($stmt = $mysqli->prepare("UPDATE members SET internet=? WHERE id=?"))
{
$stmt->bind_param('ss', $int, $content);
$stmt->execute();
$stmt->close();
echo "Marked as Problem";
}
else
{
echo "Fail.";
}
}
function isaretle_duzeltildi()
{
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$content = $_POST['kullanici'];
$int = 1;
if ($stmt = $mysqli->prepare("UPDATE members SET internet=? WHERE id=?"))
{
$stmt->bind_param('ss', $int, $content);
$stmt->execute();
$stmt->close();
echo "Marked as Fixed";
}
else
{
echo "Fail.";
}
}

Here's an alternative solution which would also minimize code duplication. Put this JavaScript code only once.
Note again. Only put this JavaScript code in your page once. You don't need to put it in more times as it works depending on what is clicked.
Example PHP code
//...table code...
//If internet == 0, Red Button will display
if($row['internet'] == 0): ?>
<td>
<button type='submit' style='width:100%' class='btn btn-danger' value='ariza' id='<?=$row['id']?>'>Problem</button>
</td>
<?php else: ?>
<td>
<button type='submit' style='width:100%' class='btn btn-success' value='duzelt' id='<?=$row['id']?>'>OK</button>
</td>
<?php endif;
// Rest of PHP code?
?>
<script>
$(document).ready(function() {
$('.btn-success, .btn-danger').click(function() {
var clickBtnValue = $(this).val();
var kullanici = $(this).attr("id");
var ajaxurl = 'ajax.php',
var data = {
'action': clickBtnValue,
'kullanici': kullanici
};
var self = this;
$.post(ajaxurl, data, function(response) {
// Changes
if ($(self).is(".btn-success")) {
$(self).removeClass('btn-success');
$(self).addClass('btn-danger');
$(self).html('Arızalı');
$(self).parent().prev().html('Var');
$(self).parent().prev().css('color', 'green');
} else {
$(self).removeClass('btn-danger');
$(self).addClass('btn-success');
$(self).html('Düzeltildi');
$(self).parent().prev().html('Arızalı');
$(self).parent().prev().css('color', 'red');
}
alert(response);
setTimeout(function() {
location.reload();
}, 2000);
});
});
});
</script>

Related

Prevent echo line from AJAX response

I want to prevent an echo from an AJAX response. I have 2 buttons and I need to enable and disable them using JS by AJAX responses. The JS code to enable/disable the HTML elements has been already written inside the PHP if condition of the AJAX URL Page. From AJAX I can display the results on <span id="dupmsg"></span>.
The result will be "Already Exists" and "Not Exist". I only want to display the message and enable/disable the buttons based on the condition. Here it's not working:
Index Page in php:
<h2>Enabling and Disabling text field using JavaScript</h2>
<form id="registration-form">
Enter your name: <input type="text" id="name">
</form>
<button onclick="disable()">Disable the text field</button>
<button onclick="enable()">Enable the text field</button>
<p>Ajax Response is: <span id="dupmsg"></span></p>
<script>
function check_dup()
{
var barcode=$("#memb_barcode").val();
$.ajax({
type: 'POST',
url: "ajax_attendance.php",
data: {
barcode: barcode
},
success: function(msg)
{
//alert(msg); // your message will come here.
$('#dupmsg')
.css('color', 'red')
.html(msg)
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
</script>
Ajax URL Page:
<?php
$reg_no = mysqli_real_escape_string($con, $_POST['reg_no']);
$barcode = mysqli_real_escape_string($con, $_POST['barcode']);
$sql = "SELECT id from tblstudent where reg_no = '$reg_no' && barcode like '$barcode' ";
$query = mysqli_query($con, $sql);
$ecount = mysqli_num_rows($query);
if($ecount!=0)
{
printf("Already Exists");
echo'
<script>
function disable() {
document.getElementById("name").disabled = true;
}
</script> ';
}
else
{
printf("Not Exists");
echo'
<script>
function enable() {
document.getElementById("name").disabled = false;
}
</script> ';
}
?>
The problem is that the JS written inside the PHP echo is reflecting back to span id="dupmsg" with AJAX response. I don't want to bring it in AJAX response. Please help.
<h2>Enabling and Disabling text field using JavaScript</h2>
<form id="registration-form">
Enter your name: <input type="text" id="name">
</form>
<button id="disable" onclick="disable()">Disable the text field</button>
<button id="enable" onclick="enable()">Enable the text field</button>
<p>Ajax Response is: <span id="dupmsg"></span></p>
<script>
function check_dup()
{
var barcode=$("#memb_barcode").val();
$.ajax({
type: 'POST',
url: "ajax_attendance.php",
data: {
barcode: barcode
},
success: function(msg)
{
if(msg=='true'){
document.getElementById("name").disabled = true;
$("#disable").attr("disabled", true); // write the id of the button u want to hide
$('#dupmsg')
.css('color', 'red')
.html("Already Exists")
}
else if(msg=='false')
{
document.getElementById("name").disabled = false;
$("#enable").attr("disabled", false); // write the id of the button u want to hide
$('#dupmsg')
.css('color', 'red')
.html("Not Exists")
}
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
function enable() {
document.getElementById("name").disabled = false;
}
function disable() {
document.getElementById("name").disabled = true;
}
</script>
ajax_attendance.php
<?php
$reg_no = mysqli_real_escape_string($con, $_POST['reg_no']);
$barcode = mysqli_real_escape_string($con, $_POST['barcode']);
$sql = "SELECT id from tblstudent where reg_no = '$reg_no' && barcode like '$barcode' ";
$query = mysqli_query($con, $sql);
$ecount = mysqli_num_rows($query);
if($ecount!=0)
{
return true;
}
else
{
return false;
}
?>

Inactive and active PHP MySQL

Having problem to change the state if its active or inactive everytime I clicked one of them nothings happened.
This is my code on ajax.
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).on('click','.status_checks',function(){
var status = ($(this).hasClass("btn-success")) ? '0' : '1';
var msg = (status=='0')? 'Deactivate' : 'Activate';
if(confirm("Are you sure to "+ msg)){
var current_element = $(this);
url = "ajax.php";
$.ajax({
type:"POST",
url: url,
data: {id:$(current_element).attr('data'),status:status},
success: function(data)
{
location.reload();
}
});
}
});
</script>
my php code ajax.php
<?php $db= new mysqli('localhost','root','password','dbname');
extract($_POST);
$user_id=$db->real_escape_string($id);
$status=$db->real_escape_string($status);
$sql=$db->query("UPDATE user SET status='$status' WHERE id='$id'");
echo 1;
?>
this is my code for displaying it, on this part everything works fine, when the value are 0 it will display inactive and 1 for active, however when clicking the status theres nothing happen only the notification and reload the page.
<td><i data="<?php echo $user['id'];?>" class="status_checks btn
<?php echo ($user['status'])?
'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' : 'Inactive'?>
</i></td>
Try to configure your code to:
$(document).on('click','.status_checks',function(){
var status = '1';
var msg = 'Activate';
if($(this).hasClass("btn-success")){
status = '0';
msg = 'Deactivate';
}
if(confirm("Are you sure to "+ msg)){
var id= $(this).data('id');
url = "/ajax.php";
$.ajax({
type:"POST",
url: url,
data: {id:id,status:status},
dataType: "json",
success: function(data)
{
console.log(data);
location.reload();
}
});
}
});
<?php $db= new mysqli('localhost','root','password','dbname');
$user_id=$_POST['id'];
$newStatus=$_POST['$status'];
$sql = "UPDATE user SET status=".$newStatus." WHERE id=".$user_id."
";
if($db->query($sql) === TRUE){
echo json_encode(1);
}else{
echo json_encode(0);
}
?>
<td><i data-id="<?php echo $user['id'];?>" class="status_checks btn
<?php echo ($user['status'])?
'btn-success': 'btn-danger'?>"><?php echo ($user['status'])? 'Active' :
'Inactive'?>
</i></td>

Generic function to update DIV

In my display page I have a script that updates a div from another php page.
How do I re-write the below script to:
Be a function I can call with updateadiv(divid,content) in my display page (in php) where content is a php variable. (the script will then not call the php page but take the input variable).
<!DOCTYPE html>
<html>
<body>
function updatediv(divId, content)
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
(function($)
{
$(document).ready(function()
{
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#content').hide();
$('#loading').show();
},
complete: function() {
$('#loading').hide();
$('#content').show();
},
success: function() {
$('#loading').hide();
$('#content').show();
}
});
var $container = $("#content");
$container.load("http://192.168.1.90/json_output.php");
var refreshId = setInterval(function()
{
$container.load('http://192.168.1.90/json_output.php');
}, 9000);
});
})(jQuery);
</script>
<?php
function createarray() {
global $reindexed_devices_a ;
$feed_url = "http://192.168.1.90/JSON?request=getstatus&ref=all&location1=all&location2=all";
//$feed_url = "demoxml.xml";
$json = file_get_contents($feed_url);
$devices_a = json_decode($json, true);
//echo $devices_a[Devices][2][name] ;
//echo "<BR> ReIndexed:";
$reindexed_devices_a = array(Devices => array());
foreach ($devices_a[Devices] as $value) {
$reindexed_devices_a[Devices][$value[ref]] = $value;
}
//echo $reindexed_devices_a[Devices][59][name] ;
//need to do some conditional formatting before updating to DIV's
if ($reindexed_devices_a[Devices][59][name] == 'Coffee maker') {
$reindexed_devices_a[Devices][59][name] = "overwritten";
}
echo time();
//echo $reindexed_devices_a[Devices][59][name] ;
}
createarray();
$name59=$reindexed_devices_a[Devices][59][name];
//check if $name59 has changed - if yes update div
updatediv('59');
echo "This is a test <div id = 'name59'>.....</div>";
?>
</body>
</html>
function updateadiv(DivID , Url){
$('#loading').hide();
$('#' + DivID ).html('');
$.ajax({
url:url,
success:function(rData){
$('#' + DivID ).html(rData);
}
});
}

How to update database thruogh dropdown without page reload

Please look at this code first:
$(document).ready(function() {
$("#alternatecolor [type=button]").each(function() {
$(this).on('click', function() {
btnObj = $(this);
rowId = $(this).attr("rowId");
changeStatus = $(this).attr("changeStatus");
$.get("changeStatus.php?rowId="+rowId+"&changeStatus="+changeStatus,function(data,status){
if(changeStatus == 0){
str ="Unverify";
btnText = "Verify";
newStatus = 1;
}
else{
str ="Verify";
btnText = "Unverify";
newStatus = 0;
}
if(data == 'success'){
alert("Status updated successfully to "+str+".");
btnObj.val(btnText);
btnObj.attr("changeStatus",newStatus);
}
else{
alert("some error");
}
});
});
});
});
</script>
Here is my change status page:
$dbhost = 'xxxxxx';
$dbuser = 'xxxxxxx';
$dbpass = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('xxxxxxxx');
$sql ="update experiment set verification=".$_GET['changeStatus']." where row=".$_GET['rowId'];
$retval = mysql_query( $sql, $conn );
if(!($retval))
{
die('error');
}
else{
echo "success";
}
mysql_close($conn);
I was using a button in this code to query my database with values 0,1. If pressed once, database queried with 1, if pressed again, database queried with 0.
Now, I have to put a dropdown in place of button with 3 values to query database with: 0,1,2. If selected first value, database row to be updated with value 0 and so on.
How would I do that?
remove button and add select like this:
<select class="my-select">
<option value="0">update</option>
<option value="1">create</option>
<option value="2">delete</option>
</select>
you also need to add data-rowId attribute.
jquery:
$(document).ready(function() {
$(".my-select").change(function() {
btnObj = $(this);
rowId = $(this).attr("data-rowId");
changeStatus = $(this).val();
$.get("changeStatus.php?rowId="+rowId+"&changeStatus="+changeStatus,function(data,status){
if(data == 'success'){
alert("Status updated successfully to "+str+".");
}
else{
alert("some error");
}
});
});
});
update
create
delete
You can do using class name or ID. If it's id then do $("#id1").click(function () {... in below code.
Awlad has done using GET method, below is using POST method.
$(function () {
$(".my-select").click(function () {
var category = $(this).text();
//$('label').css('color', selText);
$.ajax({
url: "invite_db.php",
type: "POST",
data: {"category": category},
success: function(data) {
$(".articleContent").html(data);
//setInterval("messageDisable()", 5000);
}
});
});
});
I have used parameter name according to my code. Please you change it
Here is your HTML and Javascript code
<select onchange="getval(this);">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<script type="text/javascript">
function getval(sel) {
$.ajax({
type: "POST",
url: url, // url is page where you want to process this post request
data: 'val=' + sel.value,
});
}
</script>
On PHP side
<?php
// Your database connection code
$val = $_POST['val'];
mysql_query("UPDATE 'tablename' SET 'column name' = $val 'Your WHere caluse'")
?>

Error in Ajax submit

I am new to Yii and ajax I want to read some inputs for a model from view and save it by using ajax. I used the following code inside form
<input type="button" name="save" value="save" onclick="saveFile()" id="profile-update" class="btn button-main" live="false">
and saveFile() is
function saveFile()
{
var data;
data = new FormData();
data.append('file', $('#UserProfile_profile_picture')[0].files[0]);
data.append('UserProfile', $('#profile-update-form').serialize());
$.ajax({
url: '<?php echo CHtml::normalizeUrl(array('user/profileupdate?rand=' . time())); ?>',
type:"POST",
data: data,
processData: false,
contentType: false,
success: function (data) {
$("#AjaxLoader1").hide();
if(data.status=="success"){
$("#formResult1").html("Profile settings changed successfully.");
$("#profile-update-form")[0].reset();
}
else{
$.each(data, function(key, val) {
$("#profile-update-form #"+key+"_em_").text(val);
$("#profile-update-form #"+key+"_em_").show();
});
}
},
beforeSend: function(){
$("#AjaxLoader1").show();
}
}
)
return false;
}
and the code in controller is
$profile = UserProfile::model()->findByAttributes(array('user_id' => Yii::app()->user->id));
if (!$profile) {
$profile = new UserProfile;
$profile->create_time = time();
$profile->update_time = time();
}
if (isset($_POST['UserProfile'])) {
$profile->attributes = $_POST['UserProfile'];
$profile->profile_picture=$_FILES['file']['name'];
$images = CUploadedFile::getInstance($profile,'profile_picture');
// print_r($_POST);
// print_r($profile->phone);
// print_r($images);
// exit();
if (isset($images))
{
if(!is_dir(Yii::getPathOfAlias('webroot').'/images/profilepic/'. 'quy'))
{
mkdir(Yii::getPathOfAlias('webroot').'/images/profilepic/'. $profile->profile_picture);
// the default implementation makes it under 777 permission, which you could possibly change recursively before deployment, but here�s less of a headache in case you don�t
}
foreach ($images as $image => $pic)
{
echo $pic->name;if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/profilepic/'.$pic->name))
{
$profile->profile_picture = $pic->name;
}
}
}
$profile->user_id = Yii::app()->user->id;
$profile->update_time = time();
$valid = $profile->validate();
$error = CActiveForm::validate(array($profile));
if ($error == '[]') {
$profile->save(false);
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
} else {
$error = CActiveForm::validate(array($profile));
if ($error != '[]')
echo $error;
Yii::app()->end();
exit();
}
}
But here only the profile_picture is saving to the database all other fields are not changing. and the profile picture is not copying into the folder($images is blank) Please somebody help me to solve this problem. Thanks in advance
The code $profile->attributes = $_POST['UserProfile']; doesnt worked so i send it seperately by data.append('UserProfile[about_me]', $('#UserProfile_about_me').val());
data.append('UserProfile[city]', $('#inputCity').val());
data.append('UserProfile[phone]', $('#inputPhone').val()); and in controller i used $profile->profile_picture=$_FILES['file']['name'];
$profile->about_me = $_POST['UserProfile']['about_me'];
$profile->city = $_POST['UserProfile']['city'];
$profile->phone = $_POST['UserProfile']['phone']; I know this is not the correct way but may be helpful for someone who is hurry.

Categories

Resources