Multiple IF ELSE statements not working on blur - javascript

I am having issues using multiple "if else" statements. One statement on its own works fine, but adding more statements makes things break. As each if else statement is exactly the same as the previous one I cannot establish what is causing the issue!
My task is to update the variable when an input box is amended, or if no amendment to use the original result from a mySQL query
I am using PHP, HTML & Javascript
$('body').on('blur keyup paste input', '[contenteditable]', function() {
document.getElementById("cancelchanges").style.display='none';
document.getElementById("savechanges").style.display='block';
$d = document.getElementById("d").value;
if ($d == "") {
document.getElementById("nD").value = <? echo $dlr; ?>;
} else {
document.getElementById("nD").value = $d;
}
$c = document.getElementById("contact").value;
if ($c == "") {
document.getElementById("nC").value = <? echo $con; ?>;
} else {
document.getElementById("nC").value = $c;
}
});

Related

Javascript in functions.php

I cant seem to get the following code to work;
function add_js_functions(){
$gpls_woo_rfq_cart =
gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart');
if(is_array($gpls_woo_rfq_cart)){
$count = count($gpls_woo_rfq_cart);
}else{
$count = 0;
}
?>
<script type="text/javascript">
var getQuoteIcon = document.getElementsByClassName("icon-account");
if(1 != 0) {
getQuoteIcon[0].style.display = "none";
}
</script>
<?php }
add_action('init','add_js_functions');
The php above the script stores a variable from the quote form on the number of items in the form.
I tried the javascript by itself and its seemed to work but its not working in the functions file.
At the moment im using (1 != 0) to make sure its true and to hide the item so I know the JS works, what will happen afterwards is this will become;
if (<?php $count != 0 ?>) {
//rest of the JS here
}
So that when the page loads, if the form is empty of items then this icon will be hidden (it starts off as inline-block and i dont know how to change this).
I think you want your php to be <?php echo $count != 0 ?>.
Your PHP is executed server-side, and Javascript client side, the two don't communicate by passing variables between the two. In order to get your PHP variable into your Javascript, you need to echo it.
It looks like you are loading the JS too soon and the element you are targeting isn't available yet.
Use add_action('wp_footer') to load the JS in the footer.
function add_js_functions(){
$gpls_woo_rfq_cart =
gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart');
if(is_array($gpls_woo_rfq_cart)){
$count = count($gpls_woo_rfq_cart);
}else{
$count = 0;
}
?>
<script type="text/javascript">
var getQuoteIcon = document.getElementsByClassName("icon-account");
if(1 != 0) {
getQuoteIcon[0].style.display = "none";
}
</script>
<?php }
add_action('wp_footer','add_js_functions');

Carriage return in AJAX return text

When I run my ajax action the return text has a return character as the first char. However the echo text used to send is fixed with no spaces or returns. and if i alert the return text there is no carraige return.
I'm running the code from my Godaddy host, running MSQL with PHP5
innerHTML that crates the button - _("comment_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
js code -
function deleteComment(commentid,commentbox){
var conf = confirm("Press OK to confirm deletion of this status and its replies");
if(conf != true){
return false;
}
var ajax = ajaxObj("POST", "php_parsers/comments_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var deleteOk = ajax.responseText; //This is retuning a return carraige
if(deleteOk = "1"){
_(commentbox).style.display = 'none';
_("replytext_"+commentid).style.display = 'none';
_("replyBtn_"+commentid).style.display = 'none';
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action=delete_comment&commentid="+commentid);
}
This is the PHP code
if (isset($_POST['action']) && $_POST['action'] == "delete_comment"){
if(!isset($_POST['commentid']) || $_POST['commentid'] == ""){
mysqli_close($db_conx);
echo "comment id is missing";
exit();
}
$commentid = preg_replace('#[^0-9]#', '', $_POST['commentid']);
// Check to make sure this logged in user actually owns that comment
$sql = "SELECT author_name FROM comments WHERE parent_id=$commentid LIMIT 1";
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$author_name = $row[author_name];
}
if ($author_name == $log_username) {
mysqli_query($db_conx, "DELETE FROM comments WHERE parent_id=$commentid");
mysqli_close($db_conx);
echo "1";
exit();
}else{
echo "$sql - $author_name";
}
}
So I have had to edit my code at the moment to use the int values as it would seem the IF statements still match the return value, but if i use a text return then it does not match. I have an almost identical bit of code to create the comment but this work as expected.

Json.parse() behaves differently with apparently the same input from 2 different pages php

It's the first time that i ask something here, but this problem seems to me too strange and i have to do it.
I had a php code like this:
//Here i take from $_GET
if(isset($_GET["one"])){
$one= $_GET["one"];
}
if(isset($_GET["two"])){
$two= $_GET["two"];
}
if(isset($_GET["three"])){
$three= $_GET["three"];
}
//Here i process each variable for the query i want
if($one== "any"){
$one= "%";
}
else $one= "%".$one."%";
if($two== "any"){
$two= "%";
}
else $two= $two."%";
if($three== "any"){
$three= "%";
}
//
$query = "SELECT one, two, three FROM TABLE WHERE one LIKE ? AND two LIKE ? AND three LIKE ?"
//Here i put "manually" each variable in $params
$params = [];
$params_type = "sss";
$params[0] = $one;
$params[1] = $two;
$params[2] = $three;
echo json_encode(exec_query_header_params($query, $params_type, $params));
For future necessity i wanted to make it more dynamic and I rewrote it like this:
$i=0;
$params = [];
$params_type = "sss";
foreach ($_GET as $key => $value) {
if(isset($value)){
if($value == "any")
$params[$i] = "%";
else{
if($key == "one")
$params[$i] = "%".$value."%";
elseif($key == "two")
$params[$i] = $value."%";
else
$params[$i] = $value;
}
}
$i++;
}
echo json_encode(exec_query_header_params($query, $params_type, $params));
Now, the strange thing is that the codes apparently gives me in output the same array, something like this:
[["one","two","three"], //the table-head
,["aaa","bbb","ccc"], /*
,["aaa","bab","cbc"], the table-body
,["aaa","bgb","cgc"]] */
But this ajax request works only with the old code:
var query = 'getter.php?one='+one+'&two='+two+'&three='+three;
$.ajax({type:'GET', url:query, success:takeFromJSON, cache:false, async:false});
//(Inside takeFromJSON there is a call to JSON.parse(data);)
Can anybody explain to me why this happens?

Trying to convert Javascript recursion to PHP (easy)

I have to convert some javascript to PHP for a school project, but there seems to be something I'm missing, because the exact same code is suddenly exiting prematurely.
for(var j=0; j<asciiArray.length;j++) {
passwordFound[location] = String.fromCharCode(asciiArray[j]);
console.log(passwordFound.join(""));
if (password === passwordFound.join("")) {
document.getElementById("password").innerHTML = 'Password: ' + passwordFound.join("");
return true;
}
else if (location < 2) {
var newlocation = location+1;
if (characterDecryptFunction(newlocation,asciiArray,passwordFound,password)) return true;
}
}
This is the PHP:
function characterDecryptFunction($index, $maxIndex, $asciiArray, $passwordFound, $password) {
for ($j=0;$j<count($asciiArray);++$j)
{
$passwordFound[$index] = chr($asciiArray[$j]);
echo "<br>" . implode("", $passwordFound);
if ($password === implode("",$passwordFound)) {
echo "<br>Password is:" . implode($passwordFound);
return true;
}
elseif ($index < $maxIndex)
{
$index = $index+1;
if (characterDecryptFunction($index,$maxIndex, $asciiArray, $passwordFound, $password) == true) return true;
}
}
return false;}
EDIT:
The javascript is called as such:
function decryptFunction() {
var x,y,z,password,asciiArray=[],passwordFound=[];
password="abc";
asciiArray.push(0);
asciiArray.push(32);
for (x=48;x!=58;x++) {
asciiArray.push(x);
}
for (y=97;y!=123;y++) {
asciiArray.push(y);
}
for (z=65;z!=91;z++) {
asciiArray.push(z);
}
characterDecryptFunction(0, asciiArray, passwordFound,password);}
And the PHP:
function decryptFunction() {
$password = $_POST["password"];
$asciiArray=array();
$passwordFound=array();
for($x=48;$x!=58;$x++)
{
array_push($asciiArray, $x);
}
for($x=97;$x!=123;$x++)
{
array_push($asciiArray, $x);
}
for($x=65;$x!=91;$x++)
{
array_push($asciiArray, $x);
}
for ($x=0;$x<count($asciiArray);$x++)
{
echo $asciiArray[$x];
}
echo $password . "<br>";
characterDecryptFunction(0, 2, $asciiArray, $passwordFound, $password); }
It seems crucial that you do not update $index, just like you do not update location in JavaScript. So change the PHP code, introducing $new_index:
$new_index = $index+1;
if (characterDecryptFunction($new_index,$maxIndex, $asciiArray, $passwordFound, $password)) return true;
When the algorithm returns from the recursive calls, i.e. when it backtracks to previous characters, it should continue where it left off. For that $index must have retained its previous value.
NB: Note that in PHP, just as in JavaScript, you don't need to compare with true in the if statement when you know the expression is a boolean.

JQuery form submission generates a new form

I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}

Categories

Resources