Database entry removed on browser refresh, Ajax PHP jQuery - php

I have a form that updates columns in a database table on submit of a form via ajax. Everything works great, the database table columns get the information however once the browser is refreshed the information is removed from the database. I have php set to execute the database update if a meta_value isn't present but the meta_value is in the database as it's created when the form is submitted as well.
I would like the information to remain in the database until or unless the meta_value has been removed or isn't present.
Any insight is appreciated.
PHP
add_action('wp_ajax_hide_this', 'hide_this_by_id');
add_action('wp_ajax_nopriv_hide_this', 'hide_this_by_id');
function hide_this_by_id()
{
global $wpdb;
$wpdbPrefix = $wpdb->prefix . 'swpm_members_tbl';
$postdVlaue2 = $_POST['hidebtn2'];
$this_user = $_POST['thisuser'];
$this_num = $_POST['thisnum'];
if (is_user_logged_in()) {
$member_id = SwpmMemberUtils::get_logged_in_members_id();
$query = "SELECT * FROM " . $wpdb->prefix . "swpm_members_tbl WHERE member_id = %d";
$userData = $wpdb->get_row($wpdb->prepare($query, $member_id));
$membership_levels = $userData->membership_level;
$labelID4 = $membership_levels;
$insertdisUr = $wpdb->update( $wpdbPrefix, array( 'this_user' => $this_user), array( 'member_id' => $member_id));
$insertdisId = $wpdb->update( $wpdbPrefix, array( 'this_id' => $this_num), array( 'member_id' => $member_id));
} else {
$not_loggedin = 1;
}
if ($labelID4 == 10 ) {
$userlvlMeta2 = 1;
$alredyclick3 = get_user_meta($member_id, 'hidden-info', true);
if (empty($alredyclick3) && $postdVlaue2 == 1) {
$insertdisUr;
$insertdisId;
$alredyclick3 = 1;
}
}
$return4 = array(
'hIdethis2' => $this_hide2,
'userlvlMeta2' => $userlvlMeta2,
'userlvlNolog' => $not_loggedin,
);
echo json_encode($return4);
die();
}
jQuery
function doAjaxRequest4(hidebtn2,getthisInfo,getthisInfo2) {
jQuery.ajax({
url: ajax_sib_front_object.ajax_url,
data: {
'action': 'hide_this',
'thisuser': getthisInfo,
'thisnum': getthisInfo2,
'hidebtn2': hidebtn2
},
dataType: 'JSON',
type: "post",
success: function (data) {
console.log(data.test);
var input = jQuery('.thisuser > input');
var input2 = jQuery('.thisnumber > input');
var is_name = input.length > 3;
var is_name2 = input2.length > 3;
if (!data.hIdethis2 == 1 && data.userlvlMeta2 == 1) {
jQuery("#this_col_1").addClass("enable_this");
} else if (data.hIdedisc2 == 1 && is_name && is_name2 ) {
jQuery("#this_col_1").removeClass("enable_this");
jQuery("#this_col_2").addClass("enable_this");
}
}
});
}
Function Called by
if ($('body').is('.page-id-9999') || $('body').is('.page-id-1111')) {
var thisbtn = document.querySelector('#this_verf_form > div > .wpcf7');
thisbtn.addEventListener('wpcf7submit', function (event) {
var status = event.detail.status;
console.log(status);
if (status === 'mail_sent') {
jQuery('#this_submtID').val("Submitted");
}
setTimeout(function () {
doAjaxRequest4(1,getthisInfo,getthisInfo2);
}, 3500);
}, false);
}

If your form submission is programmatic, that is, happening in the background and not refreshing the page (like it is when using Ajax), then I'd suggest clearing form fields after submission.
Something like:
$(thisbtn).parents('form')[0].reset()

Turns out that the $wpdb->update was running based on user being signed in via PHP. The variables that were placed into the condition statements were being ignored. To fix the issue I removed the $wpdb->update portion of the code from the 'user is signed in' condition and moved it to the 'if empty' conditional statements.

Related

PHP code not executing when run thru AJAX

I am trying to execute data if the SMS OTP is equal to Session_oTp. So, that is working fine, I am able to verify the mobile OTP is verified or not. But when trying to execute some normal query it does not run.
case "verify_otp":
$otp = $_POST['otp'];
$orderId = $_POST['orderid'];
$params = array("status" => "completed");
$body = 'orders/'.$_POST['orderid'] ;
// $woocommerce->put('orders/'.$orderId, $params);
if ($otp == $_SESSION['session_otp'] && $orderId == $_SESSION['OrderID']) {
// if ($otp == $_SESSION['session_otp']) {
echo "$params";
// $params = array("status" => "completed");
// $woocommerce->put($body, $params);
// print_r($_SESSION['OrderID']);
unset($_SESSION['session_otp']);
unset($_SESSION['OrderID']);
echo json_encode(array("type"=>"success", "message"=>"Your mobile number is verified!"));
} else {
echo json_encode(array("type"=>"error", "message"=>"Mobile number verification failed"));
}
break;
If I turn off the $params or $woocommerce query it works perfectly. Even if I try to echo a normal words, it's returning the error code.
My AJAX code is below:
$('form.otp-ver-form').on('submit', function(e){
// $(document.body).on("submit", 'form.otp-ver-form', function() {
e.preventDefault();
$(".error").html("").hide();
$(".success").html("").hide();
var $form = $( this ),
url = $form.attr( 'action' );
// var otpnumber = $form.find('input[name="otpnumber"]').val();
var otpnumber = $form.siblings('.mobileOtp').val();
var Order_ID = $form.siblings('.orderID').val();
console.log(otpnumber);
console.log(Order_ID);
var input = {
"otp" : otpnumber,
"orderid" : Order_ID,
"action" : "verify_otp"
};
if (otpnumber.length == 6 && otpnumber != null) {
$.ajax({
url : 'controller.php',
type : 'POST',
dataType: 'json',//specify data type
data : input,
success : function(response) {
console.log(response.message);
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('You have entered wrong OTP.')
$(".error").show();
}
});
Please let me know where is my fault or if I missing something.

PHP like/dislike button working only the first time

I'm trying to implement a like/dislike button on my page. I managed to get the button to work (it changes like to dislike and vice versa when clicked) and it also creates or deletes the like on the database table. The problem now is the counter of likes. It works only the first time i click the button, i.e. if initially there are 2 likes and i dislike the post the post shows 1 likes, but if I try to click again on it, it keeps showing 1 like and I have to reload the page to see it change to 2 likes.
This is what I have so far:
JQUERY
$(document).on('click', ".miPiace", function() {
trova = '';
commentoORisposta = '';
valCOR = '';
var comOrisp;
try{
trova = $(this).parentsUntil("#fermamiQui");
commentoORisposta = trova.find(".idCommento");
comOrisp = 'commento';
valCOR = commentoORisposta.val();
} catch(err){
trova = $(this).parentsUntil(".infoCommento");
commentoORisposta = trova.find(".idRisposta");
comOrisp = 'risposta';
valCOR = commentoORisposta.val();
}
valCOR = commentoORisposta.val();
if ($(this).hasClass('fa-thumbs-o-up')) {
$(this).removeClass('fa-thumbs-o-up');
$(this).addClass('fa-thumbs-up');
$.get( "lib/ottieniCose.php", { like: "", id: valCOR, comOrisp: comOrisp } )
.done(function( data ) {
trova.find('.numDiLikes').replaceWith('<p>' + data + ' likes</p>');
});
}else if($(this).hasClass('fa-thumbs-up')){
$(this).removeClass('fa-thumbs-up');
$(this).addClass('fa-thumbs-o-up');
$.get( "lib/ottieniCose.php", { remLike: "", id: valCOR, comOrisp: comOrisp } )
.done(function( data ) {
trova.find('.numDiLikes').replaceWith('<p>' + data + ' likes</p>');
});
};
});
PHP
if (isset($_GET['like'])) {
if ($_GET['comOrisp'] == 'commento') {
$commento->set_likes($_GET['id'], true);
return print $commento->get_likes($_GET['id'], true);
} elseif ($_GET['comOrisp'] == 'risposta') {
$commento->set_likes($_GET['id'], false);
return print $commento->get_likes($_GET['id'], false);
}
} elseif (isset($_GET['remLike'])) {
if ($_GET['comOrisp'] == 'commento') {
$commento->remove_likes($_GET['id'], true);
return print $commento->get_likes($_GET['id'], true);
} elseif ($_GET['comOrisp'] == 'risposta') {
$commento->remove_likes($_GET['id'], false);
return print $commento->get_likes($_GET['id'], false);
}
}
Other PHP file where there is the $commenti class
public function get_likes($id, $commento){
$idComm = 0;
$idRisp = 0;
$retVal = ($commento) ? $idComm = $id : $idRisp = $id;
if ($idComm != 0){
$query = "SELECT commento,
(SELECT COUNT(*) FROM likes
WHERE commento = {$idComm})
AS like_count FROM likes";
} elseif($idRisp != 0){
$query = "SELECT risposta,
(SELECT COUNT(*) FROM likes
WHERE risposta = {$idRisp})
AS like_count FROM likes";
}
$trovaQuanti = mysqli_query($_SESSION['connessione'], $query);
$trovaDavveroQuanti = mysqli_fetch_assoc($trovaQuanti);
if ($trovaDavveroQuanti == null) {
return '0';
}
return $trovaDavveroQuanti['like_count'];
}
You may want to try a normal $.ajax call. And turn off caching. Sometimes this causes an issue where you need to refresh to see the changes.
$.ajax({
type: 'GET',
cache: false,
url: "lib/ottieniCose.php",
data: { like: "", id: valCOR, comOrisp: comOrisp },
dataType: "html",
success: function(html){
trova.find('.numDiLikes').html('<p>' + data + ' likes</p>');
}
});

Ajax response return undefined

Hi I have been using ajax for many times. But I can't figure out whats the problem with my code this time. My head is blowing up since 2 days. I am using pusher for the realtime notification in CodeIgniter. Here's my code.
$(document).on("click", ".myonoffswitch", function () {
if (confirm("Sure!!! You want to Change the post status?"))
{
var thiss = $(this);
var prod_id = $(this).attr('id');
var status = $(this).attr('value');
var tdid = $(this).parent().prev().attr('class');
var td = $(this).parent().prev();
var adsstatus = $.ajax({type: "POST", dataType: "json", url: base_url + 'init/ads_status', data: {'prod_id': prod_id, 'status': status}});
$.when(adsstatus).done(function (adsstatuss) {
var msg;
msg = adsstatuss;
alert(msg.length);
var updated_status = msg[0].post_status;
alert(updated_status);
//alert(updated_status);
if (updated_status == "0" && tdid == prod_id) {
td.css("background", "#ccffcc");
td.text("On");
thiss.val(updated_status);
}
if (updated_status == "1" && tdid == prod_id) {
td.css("background", "#ffcccc");
td.text("Off");
thiss.val(updated_status);
}
});
}
});
ads_status (method in CodeIgniter)
public function ads_status() {
$prod_id = $_POST['prod_id'];
$status = $_POST['status'];
if ($status == "1") {
$new_status = "0";
$this->cmsdbmodel->ads_status($prod_id, $new_status);
$dat = $this->cmsdbmodel->get_updated_status($prod_id);
$ads_type = "product";
$emailreturn = $this->send_email_ads_status($prod_id, $ads_type);
//send user alert of product//
if ($dat[0]->post_status == "0") {
$lastInsertedId = $prod_id;
$modelNBrandId = $this->dbmodel->checkProductContainsAlert($lastInsertedId);
$getAlertEmail = $this->dbmodel->getAlertEmailFromBrandNModelId($modelNBrandId);
if (!empty($getAlertEmail)) {
foreach ($getAlertEmail as $alerts) {
$alertsEmail = $alerts->email;
}
}
$alertsPost = $this->dbmodel->getPostAlerts($lastInsertedId);
$sendPostAlerts = json_encode($alertsPost);
$encrytpEmail = hash('sha256', $alertsEmail);
$this->pusher->trigger($encrytpEmail, 'alerts', $sendPostAlerts);
}
//send user alert of product//
$realtime = $this->realTime_charts();
$realtime["post_status"] = $dat[0]->post_status;
$realtime["emailres"] = $emailreturn;
$data = $realtime;
$this->pusher->trigger('recent_activity', 'new_event1', $data);
echo json_encode($data);
}
}
Here I want to trigger event in pusher as well as echo json object. But in ajax, response is undefined. Also in console I can see json but when alerting the reponse it says undefined. Wheres problem in my code. Please help me.

receive multiple values from db using ajax

i know how to validate form using it for 1 field. But i would like enter code and take back multiple values from my db. exmp: price, quantity etc.
It is posible to do using ajac?
php file:
$sql = "SELECT * FROM database WHERE code='$field_code'";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$query=sqlsrv_query($conn, $sql, $params, $options);
$row = sqlsrv_fetch_array($query);
if ($row == true)
{
$code = ($row['code']);
$life = ($row['life']);
$agree = ($row['agree']);
}
echo $code;
echo $life;
echo $agree;
?>
And script is:
$("#field_code").change(function() {
$("#message").html("<img src='pictures/ajax_loader.gif' width='26px' height='26px' /> checking...");
var data1 = $("#field_code").val();
$.ajax({
type: 'POST',
url: 'validation.php',
data: $('form').serialize(),
success: function validate(code) {
if (data == ? ) {
to do something
} else {
to do something
}
How to receive all 3 values from php file?
}
})
you need to use json encode for this
$values[]= array('code'=>$row['code'],
'life'=>$row['life'],
'agree'=>$row['agree']);
echo json_encode($values);
and in ajax
var data = jQuery.parseJSON(data);
and access values like data.life,data.code and data.agree

Returning a complex series of commands via ajax (or perhaps restructuring it once returned through ajax)

I currently have a function that looks like this:
function getEvents($weekNumStart, $weekNumEnd){
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (!$mysqli) {
die('There was a problem connecting to the database.');
}
else {
if ($weekNumEnd == '') {
$weekNumEnd = $weekNumStart;
}
$Group = $_SESSION['Group'];
$query = $mysqli->prepare("SELECT EventID, DAYOFWEEK(Start) AS wday, Events.Start, HOUR(Start) AS sHour, HOUR(End) AS eHour, Events.End, Events.Group, Events.Unit, Type, Room, Lecturer, Cancelled, StartName FROM Events, Week WHERE StartName >= '$weekNumStart' AND StartName <= '$weekNumEnd' AND Events.Start >= StartWeek AND Events.Start <=EndWeek AND (Events.Group = '$Group' OR Events.Group = '');");
$query->execute();
$query->bind_result($eventID, $dayofweek, $startDateTime, $startHour, $endHour, $endDateTime, $group, $unit, $type, $room, $lecturer, $cancelled, $weekName);
$data_arr = array();
while ($query->fetch()){
$data_arr[] = array(
$eventID, $dayofweek, $startDateTime, $startHour, $endHour, $endDateTime, $group, $unit, $type, $room, $lecturer, $cancelled, $weekName
);
}
return $data_arr; //
}
$mysqli->close();
}
This function works how I want it to. I currently manipulate it like this:
if (!isset($weekNumEnd)){
$weekNumEnd = '';
}
$data = getEvents($weekNumStart, $weekNumEnd);
foreach($data as $day) {
for($i=0;$i<7;$i++){
for($j=9;$j<=18;$j++){
if ($day[1] == $i && $day[3] == $j){
$unit = $day[7];
$type = $day[8];
$room = $day[9];
if ($i == 2){
?>
<script>
var mon<?=$j?>unit = '<?=$unit?>';
var mon<?=$j?>type = '<?=$type?>';
var mon<?=$j?>room = '<?=$room?>';
$('#mon-<?=$j?>').append(
"<p>"+mon<?=$j?>unit+"<br>"+mon<?=$j?>type+"<br>"+mon<?=$j?>room+"</p>"
);
</script>
<?php
if (($day[4] - $day[3]) > 1) {
for($q=($day[3]+1);$q<$day[4];$q++){
?>
<script>
var mon<?=$q?>unit = '<?=$unit?>';
var mon<?=$q?>type = '<?=$type?>';
var mon<?=$q?>room = '<?=$room?>';
$('#mon-<?=$q?>').append(
"<p>"+mon<?=$q?>unit+"<br>"+mon<?=$q?>type+"<br>"+mon<?=$q?>room+"</p>"
);
</script>
<?php
}
}
}
The problem is. I obviously cannot run it in real time to constantly update the events list whenever the week or whatever is changed.
So to fix it, I decided to try using Ajax. So far I have this:
function getEvents() {
var data = 'Events=Yes';
$.ajax({
type: "POST",
url: "functions/updateWeek.php",
data: data,
cache: false,
dataType: 'json',
success: function(html) {
alert(html.returned_val);
}
});
}
And I have this to return:
if($_POST['Events'] == "Yes"){
$weekNumStart = $_SESSION['startWeek'];
$weekNumEnd = $_SESSION['endWeek'];
$data = getEvents($weekNumStart, $weekNumEnd);
echo json_encode(array('returned_val' => $data));
}
And this...sort of works. at least that is to say it returns the data in one ugly great chunk.
The thing is I can no longer manipulate it as I did before as above:
data = getEvents($weekNumStart, $weekNumEnd);
foreach($data as $day) {
for($i=0;$i<7;$i++){
for($j=9;$j<=18;$j++){
if ($day[1] == $i && $day[3] == $j){
$unit = $day[7];
$type = $day[8];
$room = $day[9];
if ($i == 2){
?>
<script>
var mon<?=$j?>unit = '<?=$unit?>';
var mon<?=$j?>type = '<?=$type?>';
var mon<?=$j?>room = '<?=$room?>';
$('#mon-<?=$j?>').append(
"<p>"+mon<?=$j?>unit+"<br>"+mon<?=$j?>type+"<br>"+mon<?=$j?>room+"</p>"
);
</script>
That is to say - I don't know how to re-manipulate it when I've called the information back through ajax. Would I rewrite all of the above in an entirely javascript fashion? Is there a more logical way of doing this that I do not know/understand? Or is there a way I can just make that code work (complete with php and javascript) in that different window, and have it send it all back, correct through ajax, to automatically work on the page without having to rewrite it once the info is pulled back through ajax?
First of all, it's enough to use json_encode($data) and you'll get the array from AJAX.
Second, check it with Firebug, as you should get structured data, not big chunk.
alert() just tries to print everything as single string, that's all
for( var i = 0; i < html.length; i++ )
// do something with html[i]

Categories