I'm trying to construct a page as a client logs in through php js interaction as fallows
$hold = ("< button onclick = `
function myFunction(){
alert('works!');
}
myFunction();
` >My balance</button>");
echo hold;
and then i want to send dinamicly to html through js
var Permition = localStorage.getItem("Permition");
$.post('MenuConstructor.php',
{
Permition:Permition
},
function(data){
menu = data;
//alert(data);
document.getElementById("div").innerHTML = menu;
}
);
but for some reson the alert don't work do you guys have any suggestions?
some times i get the error not defined some times i get the error "Unterminated template literal"
"Unterminated template literal"
:) You need escape illegal character.
<div onclick="alert("123")">
<div onclick="alert("123")"> // php htmlspecialchars (maybe) (single ' is ') quot with no "e" at it's end
$url = 'index.html?a='.urlescape($value);
echo ''
Related
Edit: Im using XAMPP with built in Apache, vscode
I make a live search input(html>js>php>js>html) , it run smoothly at first key-in, but it's getting slower and slower when i delete and key-in again , wonder what's causing the delay and how to fix it.
And i have a question,
For this example , it is better to use jquery or pure javascript?
Thank you
html
<div>
<input type="text" class="search" placeholder="find..." autocomplete="off" autocapitalize="characters">
<div class="result"></div>
</div>
js
$(document).ready(function(){
$(document).on("keyup input",".search",function(){
var input = $(this).val();
var result = $(this).next(".result");
if(input.length){
$.get("table.php", {term: input}).done(function(data){
result.html(data);
});
} else{
result.empty();
}
});
});
php
<?php
$link = mysqli_connect("localhost", "root", "******", "crypto");
// Check connection
if($link === false){
die("ERROR: " . mysqli_connect_error());
}
if(isset($_REQUEST["term"])){
$coin = "show tables from crypto where Tables_in_crypto LIKE ?";
//prepare the statement
if($prepare = mysqli_prepare($link, $coin)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($prepare, "s", $param_term);
// Set parameters
$param_term = $_REQUEST["term"] . '%';
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($prepare)){
$result = mysqli_stmt_get_result($prepare);
// Check number of rows in the result set
if(mysqli_num_rows($result) > 0){
// Fetch result rows as an associative array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["Tables_in_crypto"] . "</p>";
}
} else{
echo "<p>no result</p>";
}
} else{
echo "ERROR: $coin. " . mysqli_error($link);
}
}
// Close statement
mysqli_stmt_close($prepare);
}
// close connection
mysqli_close($link);
?>
<script type="text/javascript" src="data.js"></script>
JavaScript
Don't use "keyup input", use just the "input" Event.
Trim $(this).val().trim() your input values, you don't want an empty space to trigger a search for data!
Cooldown! You don't want to perform an additional AJAX ($.get()) request while one is already on the way. Instead create a setTimeout throttle which - only once the user stopped typing for N milliseconds the request will be triggered.
A pseudocode logic to picture it is quite simple:
jQuery($ => { // DOM ready and $ alias in scope
const search = ($input) => {
const input = $input.val().trim(); // Trim your strings!
const $result = $input.next(".result");
if (!input) {
$result.empty();
return; // end it here
}
$.get("table.php", {term: input}).done((data) => {
console.log(data);
// Exercise for the reader:
// Make sure data is an Object
// create "<p>" elements with text and populate $result
});
};
let searchCooldown; // Search input cooldown
$(document).on("input", ".search", function() {
clearTimeout(searchCooldown); // clear occurring search timeout
searchCooldown = setTimeout(() => {
search($(this)); // will be triggered once user stops typing for 300ms
}, 300); // 300ms seems like a good typing timeout?!
});
});
No, you don't need jQuery. The Fetch API is mature enough.
PHP
Don't place <script> tags inside a PHP file — which its only job should be querying the data from a database and returning it.
Don't return HTML from PHP! That's a waste. You might want a PHP file to return JSON data instead - that way it can be used by your HTML page, your watch, fridge, etc. It's usually done using echo json_encode($result);. If you need to attach also an "error" property to your $result data JSON, do so.
I don't deserve a credit for myself because everything i find mainly is on stackoverflow (after many hours spent) just I model everything to my own needs and like to give back in return.
If your page has no pagination a nice and easy way to live search all the items in javascript by doing the following (the html code may not be related to the script):
-you need to use XPath in chrome dev tools, to get the element needed:(right click on an element node->Copy -> copy full xpath)
-lets say we want to search for all the <h2> text tags inside :
-in blade file we have products.blade.php:
<html>
<body>
<input type="text" placeholder="search" id="search" onkeyup="myFunction()"></input>
<ul id="myList" class="myList-class">
<li><h2>item 1<h2></li>
<li><h2>item 2<h2></li>
</ul>
//the script below is not related to the tags above, but just to give you an idea.
<script>
function myFunction() {
var lis = document.querySelectorAll('.columns-3.products.snip-ul > li');//get all the <li> tags, change it to your needs(get the value from Ranorex selocity extension in chrome).
var x = document.getElementById("search").value; //item to search for(textbox)
if (document.getElementById("search").value.length == 0) { //if nothing is typed in textbox get all the products back
lis.forEach(node=>node.setAttribute("style","display:flex")); // restore all the display attribute to flex
return;
}
for (var i = 1; li = lis[i-1]; i++) {
var searchTitles = ((document.evaluate('/html/body/div[1]/ul/li[' + i + ']/div/div[2]/a/h2/text()', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue).data);
//change the above xpath to your own needs : (document.evaluate('XPATH HERE', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue).data;
// li.parentNode.removeChild(li);
if (searchTitles.toLowerCase().includes(x.toLowerCase())) {
document.evaluate('/html/body/div[1]/ul/li[' + i + ']', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.style = "display:flex";
} else {
document.evaluate('/html/body/div[1]/ul/li[' + i + ']', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.style = "display:none"; //hide all <li> tags
}
}
}
</script>
I feel like this should be easy. The character < (and following characters) refuses to be sent to $_POST. My max_input_vars is set to 10000, my memory limit is set to 3GB in my php.ini file, and I'm using PHP 8.0.
I have a text area where the text gets posted to a PHP file.
# HTML
<div class="add-comment">
<textarea style="margin-left: -15px;" placeholder="Add your commentary here" style="white-space:pre-wrap;" id="add-comment" class="form-control" rows="3"></textarea>
</div>
# JS
let comment = $('#add-comment').val();
const post_variables = {
'comment' : comment
};
console.log(post_variables);
$.post('/?c=comments&a=add_comment', post_variables, function(data){});
# PHP
echo '<pre>post:<br>';
print_r($_POST);
echo '</pre>';
Lets say I submit the text 'a < b'.
In JS, the log shows: a < b
In PHP the log shows: a
Is there something I need to do before passing it off to PHP? I'm genuinely surprised I haven't run into this before..
You can print the "<" on PHP using print_r(htmlspecialchar($_POST['comment'])) and if you want to convert it before sending to PHP use below function
# JS
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g,'<').replace(/>/g, '>').replace(/"/g, '"');
}
let comment = $('#add-comment').val();
const post_variables = {
'comment' : htmlEntities(comment)
};
I am trying to post a form through AJAX jQuery. The PHP script to which it points returns a JSON encoded array. But, at the receiving end on the main page JSON.parse() is not working.
Please suggest if I am missing on some file types which need to be included
Here is my code.
< script type = "text/javascript" >
$(document).ready(function() {
$("#send").submit(function() {
//$("#submit_form").html('');
$("#modal-text2").html("<img src=" + "img/loader1.gif "
+ "/></br</br><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>");
$("#myModal2").modal('show');
$.post($("#send").attr("action"), $("#send").serialize(), function(data) {
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}
});
//Important. Stop the normal POST
return false;
});
});
< /script>
The JSON encoded array which is being sent back by the PHP script is:
{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}
don't know if its the cause of hte problem or if its just a typo in here, but you have a typo in the following line:
<img src="+"img/loader1.gif "+"/></br</br>
you aren't closing the first linebreak, and the slash should come after the br - also not sure why you have so many quuotes in that html block - it should be :
$("#modal-text2").html("<img src='img/loader1.gif'/><br/><br/><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>")
You should console.log(data) to check if the data value has any problem.
use try/catch to catch message if error happened in JSON.parse.
try {
var decode = JSON.parse(data);
}catch(e){
console.log(e) ;
}
Make sure your php responses the json in the right way. Or there may have some invisible character and make the problem.
<?php
$data = ... ;
header('Content-type:application/json;charset=utf-8');
echo json_encode($data) ;
?>
I thought there is a sytax error in your script just check it out in the last line of script the closing tag of < /script> has space, remove it and try -
</script>
i execute the parsing snippet of your code it is working fine.
var data = '{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}';
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}
i need a little help using the jquery countdown keith wood - jquery countdown plugin
I am creating several countdowns by retrieving data from mysql database (php ajax call) and putting it into a div:
in php (getdetails.php -> gets $mid and $time from mysql-database):
$mrow="TimeCounter inserted here:"
$mrow.="<div id=\"RowDiv\"><div id=\"timecount".$mid."\"><script> $('#timecount".$mid."').countdown({until: ".$time."}); </script></div></div>";
$mrow.="TimeCounter ends here";
in JS i set the innerHTML with the data i got:
var url="getDetails.php";
var what="getTimeData";
console.log("call getTimeData");
var p1 = $.post(url,{what:what,selId:selValue,conName:"GId"});
p1.done(function(data){
console.log("Data -> : "+ data);
document.getElementById("CounterDiv").innerHTML=data
});
console.log(data) shows me the set html:
<div id="RowDiv" ><div id="timecount2"><script> $('#timecount2').countdown({until: 1454713200}); </script></div></div>
I get no errors but i dont see the counter... I do see the surrounding TimeCounter inserted here: TimeCounter ends here on the page. I suppose it is a client / server side issue. Maybe i need to call the function again after setting the innerHTML with the data. But i dont know how.
How can i solve this? Any ideas?
Instead of adding an inline script within your HTML element, you can initiate the counter within your callback/success function of jQuery.post(). In order to do this, you will have to change your PHP and JS like below:
PHP
$mrow="TimeCounter inserted here:"
$mrow.="<div id=\"RowDiv\"><div id=\"timecount" . $mid . "\" data-time=\"" . $time . "\"></div></div>";
$mrow.="TimeCounter ends here";
JS
var url = "getDetails.php",
what = "getTimeData";
$.post(url, {what:what,selId:selValue,conName:"GId"}, function(data){
$('#CounterDiv').html(data).find('[id^="timecount"]').countdown({until: $(this).data('time')*1});
});
UPDATE:
I don't know the plugin, but the scope of this might get changed when .countdown() is called. In such a case, you can use .each() function of jQuery to pass the element. Here is how you do that:
$.post(url, {what:what,selId:selValue,conName:"GId"}, function(data){
var $counters = $('#CounterDiv').html(data).find('[id^="timecount"]'),
$el,t;
$counters.each(function(index,element){
$el = $(element);
t = $el.data('time')*1;
$el.countdown({until: t});
});
});
Haven't tested the code but the point of my suggestion would be to avoid sending HTML in response and make getdetails.php respond with $mid and $time like:
$data = array(
'mid' => $mid,
'time' => $time
);
$response = json_encode($data);
Your JS code should look something like:
var url = "getDetails.php";
var what = "getTimeData";
console.log("call getTimeData");
$.post(url, {what: what, selId: selValue, conName: "GId"}, function (data) {
console.log("Data -> : " + data);
var id = 'timecount' + data.mid;
var row = '<div id="RowDiv"><div id="' + id + '"></div</div>';
$("#CounterDiv").html(row);
$('#' + id).countdown({until: data.time});
}, 'json');
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I hope to run a php code inside a javascript code too and I do like that :
<?php function categoryChecking(){
return false;
}?>
....
function openPlayer(songname, folder)
{
if(<?php echo categoryChecking() ?> == true)
{
if (folder != '')
{
folderURL = "/"+folder;
}else
{
folderURL = '';
}
var url = "/users/player/"+songname+folderURL;
window.open(url,'mywin','left=20,top=20,width=800,height=440');
}else{
alerte('you should click on a subcategory first');
}
}
....
<a href='javascript:void();' onClick="openPlayer('<?php echo $pendingSong['id']; ?>','')">
finally I get this error instead the alert message "you should click on a subcategory first"
ReferenceError: openPlayer is not defined
openPlayer('265','')
You're reduced your test case too far to see for sure what the problem is, but given the error message you are receiving, your immediate problem has nothing to do with PHP.
You haven't defined openPlayer in scope for the onclick attribute where you call it. Presumably, the earlier JS code is either not inside a script element at all or is wrapped inside a function which will scope it and prevent it from being a global.
Update: #h2ooooooo points out, in a comment, that your PHP is generating the JS:
if( == true)
Check your browser's error console. You need to deal with the first error messages first since they can have knock on effects. In this case the parse error in the script will cause the function to not be defined.
Once you resolve that, however, it looks like you will encounter problems with trying to write bi-directional code where some is client side and some is server side.
You cannot run PHP code from JavaScript, because PHP is a server-side language (which runs on the server) and JavaScript is a client-side language (which runs in your browser).
You need to use AJAX to send a HTTP request to the PHP page, and then your PHP page should give a response. The easiest way to send a HTTP request using AJAX, is using the jQuery ajax() method.
Create a PHP file ajax.php, and put this code in it:
<?php
$value = false; // perform category check
echo $value ? 'true' : 'false';
?>
Then, at your JavaScript code, you should first add a reference to jQuery:
<script type="text/javascript" src="jquery.js"></script>
Then, use this AJAX code to get the value of the bool:
<script type="text/javascript">
$.ajax('ajax.php')
.done(function(data) {
var boolValue = data == 'true'; // converts the string to a bool
})
.fail(function() {
// failed
});
</script>
So, your code should look like this:
function openPlayer(songname, folder) {
$.ajax('ajax.php')
.done(function (data) {
var boolValue = data == 'true'; // converts the string to a bool
if (boolValue) {
if (folder != '') {
folderURL = "/" + folder;
} else {
folderURL = '';
}
var url = "/users/player/" + songname + folderURL;
window.open(url, 'mywin', 'left=20,top=20,width=800,height=440');
} else {
alert('you should click on a subcategory first');
}
})
.fail(function () {
// failed
});
}