Passing string to jquery function - javascript

<script>
$(document).ready(function() {
$(".tweets").liveTweets({operator: "#google"});
});
</script>
I like to make the #google as a variable, so that I can change the ticker symbol as needed. I tried to echo with php. But, it's breaking the live tweet jquery.
Thanks!

<?php
$operator = "#google";
?>
<script>
$(document).ready(function() {
$(".tweets").liveTweets({operator: <?php echo json_encode($operator)?>});
});
</script>
EDIT: Thank you for your comment #icktoofay.
He is right, we don't need to wrap output in double quotes, it does that for us. I've just updated it.

HTML belongs in .html files, CSS belongs in .css files, and JS belongs in .js files. If you want to pass additional data from the server (PHP in this case) to JavaScript, you should use [data-*] attributes.
Wherever you're defining your .tweets element, you should pass the value you want used for operator as a custom data-* attribute:
HTML:
<?php
$operator = '#google';
?>
<div class="tweets" data-operator="<?php echo htmlspecialchars($operator) ?>">
...contents...
</div>
In your separate JS file, you can then use the custom server variable when initializing the widget:
JS:
$('.tweets').each(function () {
$(this).liveTweets({
operator: $(this).data('operator')
});
});
Alternatively, you can use the data-* attribute to contain the entire JSON object to initialize the widget:
HTML:
<?php
$liveTweets = array(
'operator' => '#google'
);
?>
<div class="tweets" data-live-tweets="<?php echo htmlspecialchars(json_encode($liveTweets)) ?>">
...contents...
</div>
JS:
$('.tweets').each(function () {
$(this).liveTweets($(this).data('liveTweets'));
});
Also, you could select elements based on the condition of having the appropriate data-* attribute:
JS:
$('[data-live-tweets]').each(function () {
$(this).liveTweets($(this).data('liveTweets'));
});

Related

How to call a function in a php file using jquery load?

I am trying to display the data i retrieve from the database but it is not being displayed. I have a function in the file getComments.php called "getComments(page)" page is just a integer parameter to choose that database. and as you can see that i need to call this function to print the users comments. I am trying to use "load" but it is not being successful i just want to call this function to load the comments on the page. thank you in advance.
<?php
use TastyRecipes\Controller\SessionManager;
use TastyRecipes\Util\Util;
require_once '../../classes/TastyRecipes/Util/Util.php';
Util::init();
function getComments($page){
echo "<br><br>";
$controller = SessionManager::getController();
$controller->getComments($page);
SessionManager::setController($controller);
}
and in my web page where i want to display it using java script, i tried the following
<div class="page" id="comments">
<p class="style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br><br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type='hidden' id='uid' value = '".$_SESSION['u_uid']."'>
<input type='hidden' id='date' value = '".date('Y-m-d H:i:s')."'>
<textarea id='message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'submitCom'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";
}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML =
$("#comments").load("../extras/getComments.php", getComments(1));
});
});
</script>
Just change your click handler to this:
$("#load-comments").click(function(){
$("#comments").load("../extras/getComments.php", { page: 1 }); //i also added where the elements are loaded
});
and in getComments.php (if practical, otherwise you might need to create a new PHP file which calls the getComments() function and call that from the click handler instead) add something like:
if (isset($_POST['page'])) {
getComments($_POST['page']);
// do any other necessary stuff
exit;
}

echo-ed HTML Element from PHP is not read in JAVASCRIPT

so i have some html elements generated from PHP since most contents are fetched from the database
i.e.
<?php
...
while($row = $sqlQry->fetch_object()) {
echo "<li class = 'lstOption' id = 'opt$row->name' data-value = '$row->total_count'>
<h3>$row->given_reference<h3>
</li>";
}
...
?>
and this is a sample structure based on my javascript
<script>
$("ul li").click(function(){
alert($(this).data('value'));
});
</script>
but if i inject an onClick= attribute while inside the echo. the script executed properly. what i need is for the script to work with the echo-ed html elements from php.
Try using variable interpolation syntax, i.e. wrap your variables around curly braces
"{$var}"
take note that you have to use double quotes("") for this
"<li class = 'lstOption' id = 'opt{$row->name}' data-value = '{$row->total_count}'>
<h3>{$row->given_reference}<h3>
</li>"
Just put your script inside document ready as below. That will fix the issue
$(document).ready(function(){
$("ul li").click(function(){
alert($(this).data('value'));
});
});
You should try the code binding with the $(document).ready() method.
This is because once your all DOM elements are ready then after code bind with document ready will appear.
so do the following code.
<?php
...
while($row = $sqlQry->fetch_object()) { ?>
<li class = 'lstOption' id = 'opt<?php echo $row->name?>' data-value = '<?php echo $row->total_count?>'>
<h3><?php $row->given_reference?><h3>
</li>";
}
<?php ...
?>
<script>
$(document).ready(function(){
$("ul li").click(function(){
alert($(this).data('value'));
});
});
</script>
or write as follows
<script>
$(document).ready(function(){
$("ul li").on("click",function(){
alert($(this).data('value'));
});
});
</script>
You can try to select by id and use the on() method:
$(document).on('click', '[id^="opt"]', function () {});
Works only if you don't have anything else with id starting with "opt".
In my opinion id selectors are always stronger than any other selector.
The on() method is also preferable as it is also valid for dynamically generated elements (in case of adding content via ajax for example)
Also if you want to print the actual value and not the formula in your data-value, your quotes are wrong, here is the correct version :
while($row = $sqlQry->fetch_object()) {
echo "<li class = 'lstOption' id = 'opt".$row->name."' data-value = '".$row->total_count."'>
<h3>".$row->given_reference."<h3>
</li>";
}
try like
$(document).ready(function(){
$("ul li").on('click', function(){
console.log($(this).data('value'));
});
});
Since your html elements are generating dynamically you have to use on()

How can I avoid using hidden fields to pass data from PHP to Javascript?

I am developping a website with some serious Javascript involved and I have to use generated data from PHP in my JS code.
For example, to be able to use my page ID in JS, I proceed like this:
<input type="hidden" id="pageId" value="<?php echo $page->getId() ?>" />
<button id="runJs">RUN</button>
And in my javascript (with jQuery):
$(function() {
$('#runJs').click(function() {
var id = $('#pageId').val();
});
});
It works, but is there a cleaner way to do it?
Since HTML5, one can now add user-made attributes to any HTML tag as long as it starts with data-.
In HTML5:
<button id="runJs" data-pageId="<?php echo $page->getId() ?>">RUN</button>
In JS:
$(function() {
$('#runJs').click(function() {
var id = $(this).attr('data-pageId');
});
});
Or, as said Eric Martinez in the comments, using jQuery:
var id = $(this).data('pageId');
Passing data this way is cleaner for two reasons:
It is not using a side tag that could be confusing.
The data you pass is included in the button, which means another button with its own data-XXX can use the same JS function, even on the same page.
Example
HTML:
<button data-value="5">Square it!</button>
<button data-value="7">Square it!</button>
<button data-value="12">Square it!</button>
JS:
$(function() {
$('button').click(function() {
var value = $(this).attr('data-value');
alert(value * value); // Shows 25, 49 or 144 depending of the button pressed.
});
});
The function doesn't know the button. The buttons don't even need an ID as long as JS is involved.
You can create variables inside the tag. Like this:
<script>
var pageId = '<?php echo $page->getId(); ?>';
</script>
Later in your script:
$(function() {
$('#runJs').click(function() {
var id = pageId;
});
});

Clear or Delete file from textField

I am working with PHP's Yii framework and having issues clearing or deleting the uploaded file from the textfield. Currently, it will delete the content from the fileField, but can't get it to delete the textfield. Any ideas?
UPDATE
I can now clear my textField because I've hard coded my clearFileInputField function by adding $('.getFile').val(""); I reference this in my HTML by adding the 'class' => 'getName' in the input section. While this clears the data, it doesn't remove the file after saving. Any suggestions?
HTML
<div id = "clearContent">
<?php echo $form->labelex($model,'info'); ?>
<?php echo $form->textfield($model,'info', array(placeholder => "No file chosen", readonly => true, 'class' => 'getName')); ?><br>
<?php echo $form->fileField($model,'info'); ?>
<?php echo $form->error($model,'info'); ?>
<input type="checkbox" onclick = "clearFileInputField('clearContent')" href="javascript:noAction();"> Remove File
</div>
JavaScript:
<script>
function clearFileInputField(tagId) {
document.getElementById(tagId).innerHTML = document.getElementById(tagId).innerHTML;
$('.getFile').val("");
}
</script>
I am not sure if I understood the problem you are having correctly. If I understood the question completely wrong, please elaborate and I will try to improve my answer.
If you want to remove the the content (the value attribute) of a text and file input you can use code like the following:
// listen to the click on the #clearnbtn element
document.getElementById('clearbtn').addEventListener('click', function() {
// Remove the value of the #foo and #bar elements
document.getElementById('foo').value = "";
document.getElementById('bar').value = "";
});
If you would like to remove an entire field you can do that like so:
// Retrieves the input element, gets its parents and removes itself from it
var fooElement = document.getElementById('foo');
fooElement.parentElement.removeChild(fooElement)
Or you can set the innerHTML attribute of the parent element to an empty string ('').
document.getElementById('clearContent').innerHTML = "";
https://jsfiddle.net/osjk7umh/1/

On click action not working properly

My javascript function
function ConfirmDelete()
{
if (confirm("Delete Account?"))
var id= $(this).attr('data-id');
alert(id);
location.href='config-project-delete.php?id='+id;
}
onclick event trigger
<?php
echo "<span onclick=\"ConfirmDelete()\" data-id={$row['project_id']} class='button-content'>
<i class='glyph-icon icon-trash-o float-left'></i>
Delete
</span>
</div>
</a>
</li>"; ?>
I cant able to get the data-id.It keep saying undefined.Any help would be appreciated.
In your example, this doesn't refer to the element where you called the function, but rather refers to the owner of the function (which, as you've defined it, looks like it's in the global scope). So you'd have to call the function with the parameter of the value you want, then use it within the function, as such:
<?php
echo "<span onclick=\"ConfirmDelete(\$(this).attr('data-id'))\" data-id={$row['project_id']} class='button-content'>
...
(The $ is escaped because you're echoing it with PHP).
And then your function would look something like this:
function ConfirmDelete(data_id)
{
if (confirm("Delete Account?"))
var id= data_id;
alert(id);
location.href='config-project-delete.php?id='+id;
}
If you aren't using the data-id attribute anywhere else and only for this purpose, you can simplify the HTML side as well by passing the value directly:
<?php
echo "<span onclick=\"ConfirmDelete('{$row['project_id']}')\" class='button-content'>
...
Note that I haven't tested any of this code, and when mixing HTML, JS, and PHP, it can be easy to screw this up (at least for me), so tweak the above as needed.
try this
<span onclick="javascript:deleteConfirm('<?php echo 'config-project-delete.php?id='.$row['project_id'] ?>');" deleteConfirm class='button-content'>
javascript
function deleteConfirm(url)
{
if(confirm('Do you want to Delete this record ?'))
{
window.location.href=url;
}
}
You have to pass the triggering object to your function.
function ConfirmDelete(triggering_object)
{
if (confirm("Delete Account?")) {
var id= $(triggering_object).attr('data-id');
alert(id);
location.href='config-project-delete.php?id='+id;
}
}
And add the 'this' to your object:
echo "<span onclick=\"ConfirmDelete(this);\" data-id={$row['project_id']} class='button-content'>";
Although Nick Coons answer is an easier way to do this (pass the variable to the function), to get the results you first asked about using the data attribute method, you have to pass event to the function to get the proper node. http://jsfiddle.net/2t4hK/
function ConfirmDelete(e) {
var target = $(e.target);
if (confirm("Delete Account?")) {
var id = target.attr('data-id');
alert(id);
//location.href='config-project-delete.php?id='+id;
}
}
<span onclick="ConfirmDelete(event)" data-id="1" class="button-content">Delete</span>
<?php
echo '<span onclick="ConfirmDelete(event)" data-id="'.$row['project_id'].'" class="button-content">';
echo '<i class="glyph-icon icon-trash-o float-left"></i>Delete</span>';
?>
Also, in your code, I suggest you wrap the value for data-id inside of quotes.

Categories

Resources