I have an issue with JQuery and Ajax. Sometimes my code works just fine, sometimes it just will not. Other times I need to press a down arrow once in order to make the up arrows work, which is strange enough...
In IE or in Firefox, the lack of response happens more rarely than it does in Chrome.
The website in question is here:
http://www.dungeoncrawler.com/kickstarter_2013/calculator/
If you need to login, try:
ID: webmaster#geoste.ca
Pass: 123456789
Here is an example of my code:
Javascript JQuery function : first either chnQuantUp or chnQuantDn is called, and then the data gets passed to doCrtUpd which does the actual JQuery call.
function doCrtUpd(crtID,itmAmt,itmStrID)
{
// Call AJAX to update cart quantities
if (crtID)
{
$.ajax({
type: 'POST',
url: 'inc-kspldgman.php',
data: {cartordrnum: crtID,itmamt: itmAmt,storeitmkey: itmStrID, doaction: "UPDITM"},
async: true,
success: function (d)
{
reLoadDivs();
},
error: function (d)
{
alert(d);
}
});
}
}
function chnQuantUp(frmEle,frmEleID,crtID,itmStrID)
{
tmpvar2 = frmEle + frmEleID;
tmpvar1 = eval("document.frmStrItms."+ tmpvar2 +".value");
if (isNaN(tmpvar1))
{
tmpvar1 = 1;
}
else
{
tmpvar1 = parseInt(tmpvar1);
tmpvar1++;
}
eval("document.frmStrItms."+ tmpvar2 +".value = " + tmpvar1);
doCrtUpd(crtID,tmpvar1,itmStrID);
}
function chnQuantDn(frmEle,frmEleID,crtID,itmStrID)
{
tmpvar2 = frmEle + frmEleID;
tmpvar1 = eval("document.frmStrItms."+ tmpvar2 +".value");
if (isNaN(tmpvar1))
{
tmpvar1 = 0;
}
else
{
tmpvar1 = parseInt(tmpvar1);
}
tmpvar1--;
if (tmpvar1 < 0)
{
tmpvar1 = 0;
}
eval("document.frmStrItms."+ tmpvar2 +".value = " + tmpvar1);
doCrtUpd(crtID,tmpvar1,itmStrID);
}
Example of my HTML, one of the store items:
<div name="frmEle14" id="frmEle14" class="item" style=" background-image: url(./gallery/calc_ID_84.png);">
<div class="item_name">GREENKNEE, PPM</div>
<div class="item_count_5">
<div align="center">
<img src="images/calc_arrow_up_lw.jpg" border="0" class="arrow_btn1" /><br />
<input type="text" name="frmeleamt14" id="frmeleamt14" class="count_box" value="0" size="3" maxlength="3" onkeyup="javascript:doManChng('0',document.frmStrItms.frmeleamt14.value,'38','frmeleamt14');" /><br />
<input type="hidden" name="frmelesku14" id="frmelesku14" value="GVN-DCM-0005-CHAMP-PPM" />
<input type="hidden" name="frmelesalecode14" id="frmelesalecode14" value="NONE" />
<input type="hidden" name="frmeleitmkey14" id="frmeleitmkey14" value="38" />
<input type="hidden" name="frmgvnlinekey14" id="frmgvnlinekey14" value="0" />
<img src="images/calc_arrow_down_lw.jpg" border="0" class="arrow_btn2" />
<input type="hidden" name="frmelepicnme14" id="frmelepicnme14" value="calc_ID_84.png" />
</div>
</div>
<div class="item_price">$3.00</div>
</div>
And the PHP code that handles the actual addition to the database:
if ($cartordrnum)
{
// Start UPDATE
if ($doaction == "UPDITM")
{
$rspns = "";
// Get store item's data that we need, such as price per unit
$sql = "SELECT item_unitprice,salecode FROM store_items WHERE itemkey = ".$storeitmkey.";";
$getitmdata1 = mysqli_query($conn,$sql);
$getitmdata = mysqli_fetch_array($getitmdata1);
$itemunitprice = $getitmdata['item_unitprice'];
settype($itemunitprice,"float");
$salecode = $getitmdata['salecode'];
settype($salecode,"string");
$getitmdata = null;
$getitmdata1 = null;
// Do new item total if it has not already been calculated via salecode
if ($itmttl == 0)
{
$itmttl = ($itmamt * $itemunitprice);
}
$gvnlinekey = 0;
$dbitmamt = 0;
$sql = "SELECT lineitmkey, linequant FROM gvn_lineitems WHERE storeitmkey = ".$storeitmkey." AND code_note IS NULL ORDER BY lineitmkey DESC LIMIT 0,1;";
$chklineitm1 = mysqli_query($conn,$sql);
if (mysqli_num_rows($chklineitm1))
{
$chklineitm = mysqli_fetch_array($chklineitm1);
$gvnlinekey = $chklineitm['lineitmkey'];
settype($gvnlinekey,"integer");
$dbitmamt = $chklineitm['linequant'];
settype($dbitmamt,"integer");
}
$chklineitm = null;
if ($gvnlinekey)
{
if ($itmamt)
{
// Check if amounts have changed.
if ($dbitmamt != $itmamt)
{
// We have a change, so do an update.
// Do DB update
$sql = "UPDATE gvn_lineitems SET linequant = ".$itmamt.", linesubttl = ".$itmttl.", linettl = ".$itmttl." WHERE lineitmkey = ".$gvnlinekey.";";
if (mysqli_query($conn,$sql))
{
$rspns = "UPDATED";
}
}
}
else
{
// Delete the lineitem because it has a zero or negative amount
$sql = "DELETE FROM gvn_lineitems WHERE lineitmkey = ".$gvnlinekey." AND code_note IS NULL;";
if (!mysqli_query($conn,$sql))
{
$rspns = "DELETED1";
}
}
}
else
{
// Insert new line item
if ($itmamt > 0)
{
$sql = "INSERT INTO gvn_lineitems (ordrnumkey,storeitmkey,linequant,linesubttl,linettl) VALUES (".$cartordrnum.",".$storeitmkey.",".$itmamt.",".$itmttl.",".$itmttl.");";
if (mysqli_query($conn,$sql))
{
$rspns = "ADDED";
}
}
else
{
// Delete the lineitem because it has a zero or negative amount
$sql = "DELETE FROM gvn_lineitems WHERE storeitmkey = ".$storeitmkey." AND code_note IS NULL;";
if(mysqli_query($conn,$sql))
{
$rspns = "DELETED2";
}
}
}
$chklineitm1 = null;
//echo $rspns;
}
Related
I have a form. I would like to get the input information and send it to the database via 'update_user_meta', however $_POST['this-user'] is giving a blank entry in the database.
The '$user_id' and '$meta_key' are posting to the database but the '$meta_value' is blank.
When I console log $_POST through ajax I get a blank entry in console. When I run .val() in jQuery I also get a blank entry not undefined or NULL.
I have tried having the data section of the code be
data: {
'action': 'hide_this',
'this-user': this-user,
'hidebtn2': hidebtn2
},
However a dash can't be in function i.e 'function doAjaxRequest4(hidebtn2,this-user)' is not allowed.
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;
$labelID4 = 0;
$postdVlaue2 = $_POST['hidebtn2'];
$this_user = $_POST['this-user'];
$alredyclick3 = 0;
$not_loggedin = 0;
$userlvlMeta2 = 0;
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;
} else {
$not_loggedin = 1;
}
if ($labelID4 == 10 ) {
$userlvlMeta2 = 1;
$alredyclick3 = get_user_meta($member_id, 'hidden-info', true);
if (empty($alredyclick3) && $postdVlaue2 == 1) {
update_user_meta($member_id, 'hidden-info', $postdVlaue2);
update_user_meta($member_id, 'this-user', $this_user);
$alredyclick3 = 1;
}
}
if ($alredyclick3 == 1) {
$this_hide2 = 1;
} else {
$this_hide2 = 0;
}
if ($userlvlMeta2 == 1) {
$this_Meta2 = 1;
} else {
$this_Meta2 = 0;
}
$return4 = array(
'hIdethis2' => $this_hide2,
'userlvlMeta2' => $this_Meta2,
'userlvlNolog' => $not_loggedin,
'levelid4' => $labelID4,
'test' =>$this_user
);
echo json_encode($return4);
die();
}
jQuery
function doAjaxRequest4(hidebtn2,getthisInfo) {
var getthisInfo = jQuery('.this-user > input').val();
console.log(getthisInfo);
jQuery.ajax({
url: ajax_sib_front_object.ajax_url,
data: {
'action': 'hide_this',
'this-user': getthisInfo,
'hidebtn2': hidebtn2
},
dataType: 'JSON',
type: "post",
success: function (data) {
console.log(data.test);
var input = jQuery('.this-user > input');
var input2 = jQuery('.this-number > input');
var is_name = input.length > 3;
var is_name2 = input2.length > 3;
if (!data.thisdisc2 == 1 && data.userlvlMeta2 == 1) {
jQuery("#this_col_1").addClass("enable_this");
} else if (data.thisdisc2 == 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);
}, 3500);
}, false);
}
HTML
<div role="form" class="wpcf7" id="wpcf7-f9999-p9999-o1" lang="en-US" dir="ltr">
<div class="screen-reader-response"><p role="status" aria-live="polite" aria-atomic="true"></p> <ul></ul></div>
<form action="/mysite/#wpcf7-f9999-p9999-o1" method="post" class="wpcf7-form init" novalidate="novalidate" data-status="init">
<div class="vc_row" id="this_row">
<div class="vc_col-sm-5">
<span class="wpcf7-form-control-wrap this-user"><input type="text" name="this-user" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="placeholder"></span>
</div>
<input type="submit" value="Submit" class="wpcf7-form-control has-spinner wpcf7-submit" id="sub_id">
</div>
I have a Ajax PHP MySQL live search that basically pulls out manufacturing items from a MySQL database and presents them in a drop-down list, as users enter they search term, one item per line, just like searching in Google.
What I need is a way to allow users to click on a particular link item, and for that to display data on the same page, just below the item(link) clicked.
Any help would be appreciated.
1.HTML form
<form class="navbar-form navbar-left" action="javascript:">
<div class="input-group">
<input type="text" class="form-control" id="searchbox1" name="q" token="<?=$csrf->token()?>" action='search1' placeholder="Search for Templates" autocomplete="off">
<div class="input-group-btn">
<button class="btn btn-default " id="searchbtn1" type="submit">
<i class="fa fa-search"></i></button>
</div>
</div>
<div id="livesearch1"></div>
</form>
2. AJAX Call seperate .js file
$('#searchbox1').on('keyup focus', function(e) {
var b = $(this).attr();
delete b.class, delete b.placeholder, delete b.id, delete b.name, delete b.type, delete b.autocomplete;
b.q = $(this).val();
if (b.q != '' && b.q.length > 0) {
$.ajax({
type: "POST",
url: api,
data: b,
cache: false,
success: function(a) {
$("#livesearch1").html(a);
$("#livesearch1").fadeIn();
}
});
} else {
$("#livesearch1").fadeOut();
}
});
$('#searchbox1').on('blur', function(e) {
$('#livesearch1').fadeOut();
});
3. api call
case 'search':
if($app->isAdmin() || $app->isEditor() || $app->isUser())
{
$app->escape('q');
ob_start();
ajaxsearch($q);
echo $result = ob_get_clean();
// json('success','true','results',$result);
}
break;
4. .php file
function ajaxsearch1($q){
$db = MysqliDb::getInstance();
$csrf = new Csrf_Protect();
$q = removeWhiteSpace($q);
$q = htmlspecialchars_decode($q,ENT_QUOTES);
$q = preg_replace('/[^a-zA-Z0-9.-. .).(]/', '', $q);
if(strlen($q) >0 )
{
$term = $q;
$searchterm = explode(' ',$term);
$searchColumns = array("name","slug");
$searchCondition = '';
for($i = 0; $i < count($searchColumns); $i++)
{
$searchFieldName = $searchColumns[$i];
$searchCondition .= "($searchFieldName LIKE '%" . implode("%' AND $searchFieldName LIKE '%", $searchterm) . "%')";
if($i+1 < count($searchColumns)) $searchCondition .= " OR ";
}
$res = $db->rawQuery("SELECT * FROM tbl_templates WHERE ($searchCondition) AND (version='1') order by id desc Limit 10 ");
foreach($res as $sr)
{ ?><li><?=ucfirst($sr['name'])?></li><?php
}
}
}
?>
This was a parameter issue.
data was not in the $q it was in the $name code should be something like this.
case 'search':
if($app->isAdmin() || $app->isEditor() || $app->isUser())
{
$app->escape('name');
ob_start();
ajaxsearch($name);
echo $result = ob_get_clean();
}
break;
I have a notification system that out puts the right value of 1 and updates the div accordingly when a user posts one on my wall.
{
"num":1,
"notification_id":"640",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=515",
"notification_triggeredby":"85",
"notification_status":"1"
}
But if a user posts twice it does nothing and doesn't update at all.
{
"num":1,
"notification_id":"641",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=516",
"notification_triggeredby":"85",
"notification_status":"1"
}
{
"num":1,
"notification_id":"642",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=517",
"notification_triggeredby":"85",
"notification_status":"1"
}
CLIENT SIDE
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="select MAX(notification_id) AS notification_id ,notification_status,notification_targetuser,notification_triggeredby,notification_throughurl from notifications WHERE notification_targetuser='$user1_id' AND notification_status='1'";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification=mysqli_fetch_array($chant)){
?>
<script type="text/javascript">
var notification_id="<?php echo $notification['notification_id']?>";
var notification_targetuser="<?php echo $notification['notification_targetuser']?>";
var notification_triggeredby="<?php echo $notification['notification_triggeredby']?>";
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"¬ification_targetuser="+notification_targetuser+"¬ification_triggeredby="+notification_triggeredby,
dataType:"json",
success: function(data){
if(data.notification_stream=1){
$("#notif_ui"+notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-" class="notif_actual_text"><img border="1" src="userimages/cropped'+data['notification_triggeredby']+'.jpg" onerror=this.src="userimages/no_profile_img.jpeg" width="40" height="40" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br/></div></div></div><hr/>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
if(!data.notification_id.length) {
//no results...
return;
}
notification_id = data.notification_id;
}
}
});
}
setInterval(loadIt, 10000);
</script>
<? } ?>
SERVER SIDE
$json = array();
$com=mysqli_query($mysqli,"SELECT * from notifications WHERE notification_targetuser='$idw' AND notification_triggeredby='$ide' AND notification_status='1' ORDER BY notification_id")or die($mysqli);
while($row = mysqli_fetch_assoc($com)){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
echo json_encode($json);
}}
$sql = "UPDATE notifications SET notification_status = '2' WHERE notification_targetuser='$idw'";
$go = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
You're echoing the JSON results inside a loop, so if the loop executes more than once, the final result is not valid JSON data. It's just multiple chunks of JSON.
while($row = mysqli_fetch_assoc($com)){
$id = $row['notification_id'];
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json[$id]['notification_id'] = $row['notification_id'];
$json[$id]['notification_content'] = $row['notification_content'];
$json[$id]['notification_throughurl'] = $row['notification_throughurl'];
$json[$id]['notification_triggeredby'] = $row['notification_triggeredby'];
$json[$id]['notification_status'] = $row['notification_status'];
}
echo json_encode($json);
Then you'll need to adjust your Javascript to expect an array instead of a flat object.
I have multiple dynamic textboxes where users input license plate no. I'm trying to retrieve the id corresponding to the license plate # inputted by the user from the database but I'm unable to get it. I want to store the license plate #'s id that's already in the database to a different table and not the license plate no itself, but It always returns null.
Thanks in advance.
search.js
function firetruckAddingTextBoxes() {
var NumOfText = $("#NumOfTextBoxes2").val();
$('.NewlyCreatedSelectBoxes2').empty();
var txtBox = "";
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="firetruck[]" class="search" placeholder="License Plate No" required/><br>';
}
$('.NewlyCreatedSelectBoxes2').append(txtBox);
$(".NewlyCreatedSelectBoxes2").on("keyup", ".search", function () {
var search_term = $(this).val();
$('#search_results2').html('Searching database...');
if (search_term !== '') {
$.post('php/firetruck_search.php', { search_term: search_term }, function (data) {
$('#search_results2').html(data);
});
} else {
$('#search_results2').html('Not Found');
}
});
return false;
}
search.php
<?php
require('connectdb.php');
if(isset($_POST['search_term']))
{
$search_term = mysql_real_escape_string(htmlentities($_POST['search_term']));
if(!empty($search_term))
{
$search = mysql_query("SELECT `fireTruckID`, `licensePlateNo` FROM `firetruckinfo` WHERE `licensePlateNo` LIKE '%$search_term%'");
$result_count = mysql_num_rows($search);
$suffix = ($result_count != 1) ? 's' : '';
echo '<p>Your search for ', $search_term, ' returned ', $result_count, ' result', $suffix, '</p>';
while($results_row = mysql_fetch_assoc($search))
{
echo '<p>', $results_row['licensePlateNo'], '</p>';
}
}
}
?>
occurrence.php
$firetrucks = $_POST['firetruck'];
foreach($firetrucks as $firetruck):
$vehicleID = mysql_query("SELECT `fireTruckID` FROM `firetruckinfo` WHERE `licensePlateNo`='$firetruck'");
$row2 = mysql_fetch_assoc($vehicleID);
$query3 = "INSERT INTO `truckonscene`(`FireTruckInfo_fireTruckID`, `IncidenceOfFire_incidentID`)
VALUES(
'".mysql_real_escape_string($row2['fireTruckID'])."',
'".mysql_real_escape_string($incidentid)."')";
mysql_query($query3) or die(mysql_error());
endforeach;
I want to update my database with the ids of characters, but when I drop them into the slot, it doesn't update the rows I want it to update. My question is can you point me in the right direction of how I can code this properly or fix my errors?
function updateTeam(){
var team = '', slot = [];
if($('input[name=s0]').val()!=""){
slot.push($('input[name=s0]').val());
}
if($('input[name=s1]').val()!=""){
slot.push($('input[name=s1]').val());
}
if($('input[name=s2]').val()!=""){
slot.push($('input[name=s2]').val());
}
$.each(slot, function(i,e){
if(i == 0) team = e;
else team = team + ',' + e;
});
$.ajax({
url : _path + "/core/ajax.php",
type : 'POST',
data : { f: 'setTeam', i: team},
dataType : 'json',
success : function(data) {
if(data.error){
errorMessage('Error: ' + data.error, data.error, data.error);
}
}
});
}
Php
function clean($content) {
$content = mysql_real_escape_string(htmlspecialchars($content));
return $content;
}
//Update the user team.
if (isset($_POST['f']) && $_POST['f'] == 'updateTeam') {
if (isset($_POST['s0'])) {
$cid1 = $secure->clean($_POST['s0']);
} else {
$cid1 = '1';
}
if (isset($_POST['s1'])) {
$cid2 = $secure->clean($_POST['s1']);
} else {
$cid2 = '2';
}
if (isset($_POST['s2'])) {
$cid1 = $secure->clean($_POST['s2']);
} else {
$cid1 = '3';
}
$updateTeam = $db->query("UPDATE accounts SET cid1 = '$cid1', cid2 = '$cid2', cid3 = '$cid3' WHERE id = '$id'");
}
When i inspect the element with Google Chrome it says i:1,5,2. Show how would I update my rows so that the 1 in "i"= $cid1, the 5=$cid2, and the 2= cid3, is my php code wrong?
Html:
<div id="droppable_slots" class="current_team">
<div class="slot 1">1</div>
<input type="hidden" name="s0" value="10">
<div class="slot 2">2</div>
<input type="hidden" name="s1" value="7">
<div class="slot 3">3</div>
<input type="hidden" name="s2" value="3">
</div>
Since you are sending a csv with a the key of i, you need to get your values from $_POST['i'] by exploding on the ,. So your code could be updated to something like-
//Update the user team.
if (isset($_POST['f']) && $_POST['f'] == 'updateTeam') {
//Explode the i post
if (isset($_POST['i'])) {
$vals = explode("," , $_POST['i'] );
}
if (isset($vals[0])) {
$cid1 = $secure->clean($vals[0]);
} else {
$cid1 = '1';
}
if (isset($vals[1])) {
$cid2 = $secure->clean($vals[1]);
} else {
$cid2 = '2';
}
if (isset($vals[2])) {
$cid1 = $secure->clean($vals[2]);
} else {
$cid1 = '3';
}
$updateTeam = $db->query("UPDATE accounts SET cid1 = '$cid1', cid2 = '$cid2', cid3 = '$cid3' WHERE id = '$id'");
}