I have php inside javascript, and I made a query inside php, but the query cannot be fetched even in php area itself, why?
I have tried that query in PHPmyAdmin manually and it works fine. The "ca" field value is 1 not 0, but after i apply on code the result of "ca" is 0. What is wrong exactly? And there's no error message shows in console log.
image:
simple code:
<?php
include('ckcon.php');
include('logincheckmember.php');
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
<script>
function kampret(){
var ssloginmember = document.getElementById('id1').textContent;
var ambilun = document.getElementById('id2').textContent;
<?php
$ssloginmember=ssloginmember;
$ambilun=ambilun;
$q=mysql_query("SELECT COUNT(ai) AS ca,unnum FROM t_follow WHERE username='$ssloginmember' AND username2='$ambilun'");
$f=mysql_fetch_object($q);
$unnum2=$f->unnum;
$ca=$f->ca;
if($ca==0){
$status='follow';
$unnum=0;
}else{
$status='unfollow';
$unnum=$unnum2;
}
?>
var status='status = '+<?php echo json_encode($status);?>;
var unnum='unnum = '+<?php echo json_encode($unnum);?>;
var output1='output1 = '+<?php echo $ssloginmember;?>;
var output2='output2 = '+<?php echo $ambilun;?>;
document.getElementById('status').innerHTML = status;
document.getElementById('unnum').innerHTML = unnum;
document.getElementById('output1').innerHTML = output1;
document.getElementById('output2').innerHTML = output2;
}
</script>
</head>
<body>
<div id="status">status</div>
<div id="unnum">unnum</div>
<div id="output1">output1</div>
<div id="output2">output2</div>
<br>
<button onClick="kampret()" >button</button><br>
<br>
<div id="id1">melisavirgi</div>
<div id="id2">ririnputrian</div>
<br>
<?php
echo "ssloginmember=$_SESSION[ssloginmember]";
?>
</body>
</html>
result:
The problem seems to be that you are trying to get a javascript value in the PHP, ie $ssloginmember=ssloginmember;.
The PHP code is run before the page is loaded in the browser and generates parts of your javascript code. Your script seems to be acting as if it is run every time the javascript function is called, and as if both languages are the same.
AJAX is probably going to be your best solution - post the data to a PHP script that returns the values you need.
I suspect you may need to brush up on the difference between client side and server side code, too.
Related
I am updating my site content with AJAX by using this method i have found here: https://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html
This works very well but according to this tutorial i have to echo the values i want to show as an updated value in the background running "record_count.php". Later all values are shown up in my frontend file "index.php" within the specific <div id="xxx">. my problem is now that in my background "record_count.php" i have several values i echo but in need them in separate HTML <div id="1, 2, ...> In my example it is $name and $city. How can i connect the values to a specific HTML <div id="1, 2, ...> ? (Please ignore the old query method i have copy/paste here. In my code i am using prepared statements with PDO)
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php?q=<?php echo $id; ?>').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
<body>
<div id="load_tweets"> </div>
</body>
</script>
record_count.php
<?php
include("db.php");
$search_word=$_GET['q'];
$sql = mysqli_query($db,"Select name, city FROM users where id = $id");
$record_count=mysqli_num_rows($sql);
//Display count.........
echo $city;
echo $name
?>
I have having big issues with the execution order of my code.
HTML sample:
<div id="toast-container" class="toast-top-right"><div id="toast-type" class="toast" aria-live="assertive" style=""><div id="snackbar">message</div></div></div>
.
.<!--Somewhere more down the line-->
.
.
<div class="col_half col_last">
<label for="job-ctc-frm-heard-about">How did you find out about us?</label>
<input type="text" id="job-ctc-frm-heard-about" name="job-ctc-frm-heard-about" value="<?php echo $discovered;?>" class="sm-form-control" />
</div>
Javascript function:
<script>
function Toast(message, messagetype)
{
var cont = document.getElementById("toast-container");
cont.classList.add("show");
var type = document.getElementById("toast-type");
type.className += " " + messagetype;
var x = document.getElementById("snackbar");
x.innerHTML = message;
setTimeout(function(){ cont.classList.remove("show")}, 3000);
}
</script>
PHP sample:
<?php
$discovered ="";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$message = 'Let the games begin';
echo "<script type='text/javascript'>Toast('$message', '$Success');</script>";
$discovered = test_input( $_POST["job-ctc-frm-heard-about"] );
......
?>
Now heres my problem. My php uses a function Toast. My function Toast accesses the HTML div toast-container to set a message. The other div uses the php variable $discovered to remember the entered value on a failed form submit. If i position the JS anywhere before the DOM then var cont will be null so it has to be below.
However if I position the code order as PHP -> HTML -> JS then the function is undefined in PHP so it has to be after JS. But if i position it as HTML -> JS -> PHP then the variable $discovered won't be displayed in the HTML. The orders are conflicting with one another. Is there any work around for this?
The simplest would be to just move the relevant parts to where you need them. You need $discovered to be available throughout your file (when PHP is executed server-side) and you need it to echo the script specifically after your Toast-declaration:
<?php
$discovered ="";
if($_SERVER["REQUEST_METHOD"]=="POST") {
$message = 'Let the games begin';
$discovered = test_input( $_POST["job-ctc-frm-heard-about"] );
// ...
}
?>
<!-- HTML referencing $discovered here -->
<script>
function Toast(message, messagetype)
{
var cont = document.getElementById("toast-container");
cont.classList.add("show");
var type = document.getElementById("toast-type");
type.className += " " + messagetype;
var x = document.getElementById("snackbar");
x.innerHTML = message;
setTimeout(function(){ cont.classList.remove("show")}, 3000);
}
</script>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST") {
echo "<script type='text/javascript'>Toast('$message', '$Success');</script>";
}
?>
If you want to control these things from client-side, you can json_encode your PHP objects, meaning they will be sent in plain-text as if you had hard-coded them into the file. As #FZs mentions, PHP runs on the server and "prepares" the file by executing all <?php ... ?> blocks. When the result reaches the browser, it contains the resulting text and not PHP (browsers don't understand PHP).
I am trying to add some custom PHP code to a Wordpress custom post type.
In a separate php file I have this:
<?php
$BuildForm = '<script src="//app.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_1111"></form>
<script>MktoForms2.loadForm("//app.marketo.com", "345-XCL-354", 1111,
function(form) {
for ( var ss = document.styleSheets, i = 0, imax = ss.length; i < imax; i++ ) {
if ( ( ss[i].href && ss[i].href.indexOf("marketo.com") !== -1 )
|| ( (ss[i].ownerNode || ss[i].owningElement).parentNode == form.getFormElem()[0] ) ) {
}
}
form.onSuccess(function(values, followUpUrl){
location.href = "#";
return false;
});
form.vals({ "comments":"test"});
});
</script>';
?>
Then in the custom post type in Wordpress I have this:
<div id="TheForm" style="max-width:40%; margin: 0 auto;"></div>
<script type="text/javascript">
document.getElementById("TheForm").innerHTML = '<?php echo $BuildForm; ?>' ;
</script>
The problem I am having is that the contents of #TheForm appear as ';
I am not quite sure what the problem is. Do I need to be formatting the JavaScript that's in the PHP variable in a different way ?
I tried escaping " and / for example but that didn't help either.
(And before you ask, yes I am including the external php file in my Wordpress custom post type).
Of course it's not working! The PHP is executed on the server (which outputs nothing), then rendered by the client, and then your javascript runs. Your client-side javascript has no idea what do with PHP.
Your PHP should be returning the fully-formed HTML, like so:
<?
$BuildForm = '....';
?>
<div id="TheForm" style="max-width:40%; margin: 0 auto;">
<?= $BuildForm ?>
</div>
Alternatively, change your client-side javascript to fetch your $BuildForm HTML via ajax. But it's probably easier to just have your PHP produce the HTML you want.
As your $BuildForm variable contains </script>, there'll be a SyntaxError: Unexpected EOF. Example of the assigned code below:
<script type="text/javascript">
<script src="//app.marketo.com/js/forms2/js/forms2.min.js"></script> <!-- </script> tag will be closed here -->
</script>
<script type="text/javascript"> will be closed at ... forms2.min.js"></script>, which is closed too early.
Thus, the best alternative way is to echo the form directly into the div.
<div id="TheForm" style="max-width:40%; margin: 0 auto;"><?php echo $BuildForm; ?></div>
I'm trying to see whether a particular name I entered is on the list or not. And I want the response in XML. I've tried whatever I could but not getting the result. (I'm using firefox by the way).
HTML
<html>
<head>
<script type="text/javascript" src="javer.js"></script>
</head>
<body>
<h1>Testing ajax!</h1>
<form onsubmit="changer('inputing')">
enter name <input type="text" id="inputing" />
<input type="submit" />
</form>
<p id="ch">enter name to check</p>
</body>
</html>
JAVASCRIPT
function changer(a) {
var mo = new XMLHttpRequest();
var qry = document.getElementById(a).value;
mo.onreadystatechange = function() {
if(mo.readyState == 4 && mo.status == 200) {
var res = mo.responseXML;
document.getElementById("ch").innerHTML = res.firstChild.nodeValue;
}
}
mo.open("GET", "appr.php?name=" + qry, true);
mo.send(null);
}
PHP
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo "<cover>";
$b = array("sam", "norton", "maya", "sijosh", "noor", "timothy");
$c = $_GET["name"];
if(in_array($c, $b)) {
echo "he is here";
}
else { echo "sorry... we dont know him"; }
echo "</cover>";
?>
You probably don't see what is happening as the form gets submitted the non-ajax / regular way as well.
You can avoid that by using for example:
<form action='' onsubmit="changer('inputing'); return false;">
Although ideally you would get rid of the inline javascript altogether and handle everything in a javascript event handler.
Well at last I figured it out! There were two problems. First one was that the page was getting refreshed every time I submit the form, as you guys said. I corrected it. The second problem was in the parsing of XML data. I transferred the XML to the variable 'res' but after that I had to get the 'documentElement' from the XML. So I added another variable 'xmlde'.
xmlde = res.documentElement;
Then,
document.getElementById("ch").innerHTML = xmlde.firstChild.nodeValue;
Problem was solved!
I'm trying to teach myself how to use AJAX with PHP. However, I am unable to get my (likely broken) AJAX code to change the value of my $things variable. Instead, what happens is the index.php page gets reloaded and a brand new button gets added. Here is my code:
<?php
$things = 0;
?>
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
<script>
function changeMe()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("changetest").innerHTML=xmlhttp.responseText;
}
}
var things = "<?php echo $things; ?>";
things++;
xmlhttp.open("GET","index.php?things="+things,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
echo "<p>Things = <span id=\"changetest\"" . $things . "</span></p>";
?>
<button type="button" onclick="changeMe()">Change Content</button>
</body>
</html>
Any clue as to where I'm messing up?
There are at least two problems I can see:
You are not using the variable you are sending back to the server $_GET['things'] anywhere. Instead you are always setting it to 0 so you will never see anything else;
You are posting to the original php file. That means that the response will be the complete html page, including the head, etc. You probably want a separate file to only send back what you really need.
An example of a separate php file would just be to echo out what was sent in:
<?php
echo 'I sent the number: ' . intval($_GET['things']);
And now you should make an ajax request to this file and not index.php.
You should remove the quotes around "<?php echo $things; ?>"; and make it var things = <?php echo "'".$things."'"; ?> instead.