Getting HREF Values from content on page - javascript

I am getting data from a page that is formatted like this
<span id="RANDOMINFO">
+
<span title="1">DATA I WANT HERE</span>
CLICK
MORE RANDOM DATA
</span>
<span id="RANDOMINFO">
+
<span title="2">DATA I WANT HERE</span>
CLICK
MORE RANDOM DATA
</span>
How can I get the href value from the page
Here is the code I have to get the data from the span ID but don't know how to do it for the href as there is no name or id
$doc = new DOMDocument();
#$doc->loadHTML($html2);
foreach($doc->getElementsByTagName('span') as $element )
{
if (!empty($element->attributes->getNamedItem('id')->value))
{
$filename = 'newpks/'.$f.'.txt';
$file = fopen($filename,"a");
$data = $element->attributes->getNamedItem('id')->value.PHP_EOL;
fwrite($file,$data);
fclose($file);
$i++;
$end = $start;
}
}

I assume you're only interested in links with the href attribute, and then we know the tags will be of type a. This should sufficient (I haven't been able to test the code though).
I optimized the code a bit, since the DOMNode class inherits from DOMElement you can use the hasAttribute and getAttribute instead.
foreach($doc->getElementsByTagName('a') as $element ) {
if ($element->hasAttribute('href')) {
$href = $element->getAttribute('href');
// Do your work here
}
}

Related

get href from php and use element in JQuery

I have xyz.php and working menu <li> elements. I need to get hreffrom php use it in Java script for navigate away. So I have list of li tag and in code it's displaying one for example. Each li tag has unique href.
My question is: If I have select only one li elements from the list. I want to use that li's associated href in IF condition in JavaScript and ELSE part is multiple Li's selected. The code is working for else part. But, I am having issue with IF part.
I am not getting the href value from PHP. you can get 'href'from $xyz['url'] in php.
xyz.php
<div class="global-wrapper">
<ul class="list">
<li>
<input id="retreat-<?php echo $xyz['api_id']; ?>" class="custom-check-input more-filter-experience" type="checkbox" value="<?php echo $xyz['name']; ?>" data-home-location="<?php echo $xyz['api_id']; ?>">
<label class="custom-check-label" for="retreat-<?php echo $xyz['api_id']; ?>"></label>
</li>
</ul>
</div>
Here, the java script code:
xyz.js
if(retreatIdArray.length === 1 && exploreDate === undefined) {
var categoryId = $('.global-wrapper').find('.loadProducts').attr('data-categoryid');;
window.location.href = "/categoryId"; // having issue
} else{
window.location.href = '/destination';
}
You wrote undefine instead of undefined. The statement inside if will never be true.
Also, to check for undefined, it's better to use typeof.
if(retreatIdArray.length === 1 && typeof exploreDate == 'undefined') {
retreats = $('.global_wrapper').find('.custom-check-input').val();
window.location.href = '/href';
} else {
window.location.href = '/destination';
}
Note: untested code, you may have to adjust it to your needs. Please let me know if it works.

PHP - Calling specific variable from an array in a list of items on click / Mixed with JavaScript

I have been trying to catch a variable in an array when an item is clicked on and have been struggling a great deal.
I have a list of items which each have their own name in a database. When the page is loaded these items are listed on the page and can be clicked on to open a new window which displays certain content depending on the items name in the array.
Currently I have managed to get the items names into an array when they are displayed on the page. But when I click on one item the variable used to open the unique window for that item contains every variable in the array (not just the variable name of the item I clicked on).
In my PHP code I go through the database (depending on if isLive == 1) and add each name of the items 'channel_title' into an array named $chName.
$chResult = mysql_query($chSQL);
if ($chResult) {
$chNum = mysql_num_rows($chResult);
if ($chNum>0) {
//Create the arraw
$chName = array();
while($row = mysql_fetch_array($chResult)) {
//Add channel name to array
$chName[] = ($row['channel_title']);
if ($row['is_live']=="1") {
$whatIsLive = "true";
} else {
$whatIsLive = "false";
}
echo
'<li id="'.$row['channel_id'].'" class="list-group-item col-xs-12 col-sm-6 col-md-4 col-lg-3">
<div class="item">
<div class="item-head">
<div class="badges">';
if ($row['is_live']=="1") {
echo '<span class="badge-live">Live</span>';
}
echo
'</div>
</div>
<div class="item-image">
<a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'"target="window" onclick="openStreamPopup(); return false;" data-islive="'.$whatIsLive.'" title="'.$row['channel_title'].'">';
$activeSSImage = 'userData/'.$row['user_id'].'/channelImages/ss_'.$row['channel_id'].'_t.jpg';
$defaultSSImage = 'images/ss_default.jpg';
if (file_exists($activeSSImage)) {
echo '<img src="'.$activeSSImage.'?rand='.rand(0, 99999999).'" alt="'.$row['channel_title'].'" width="250" height="200">';
} else {
echo '<img src="'.$defaultSSImage.'" alt="'.$row['channel_title'].'" width="250" height="200">';
}
echo '<span class="image-cover"></span>
<span class="play-icon"></span>
</a>
</div>
</div>
</div>
</li>';
}
} else {
echo '';
}
} else {
echo '';
}
In this above code is:
<a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'"target="window" onclick="openStreamPopup(); return false;" data-islive="'.$whatIsLive.'" title="'.$row['channel_title'].'">';
which sends the compiler to a JavaScript function which grabs the array and assigns it to a JavaScript variable - allowing a new window to open with window.open(). This is done with this code:
<script type="text/javascript">
var theChannel = <?php echo(json_encode($chName)); ?>; //Grab the Array $chName - call it theChannel
var windowObjectReference = null; // global variable
function openStreamPopup() {
if(windowObjectReference == null || windowObjectReference.closed)
/* if the pointer to the window object in memory does not exist
or if such pointer exists but the window was closed */
{
windowObjectReference = window.open("channels/"+theChannel,
"window", "resizable,scrollbars,status"); //Open link with theChannel (channel_title) as url
/* then create it. The new window will be created and
will be brought on top of any other window. */
}
else
{
windowObjectReference.focus();
/* else the window reference must exist and the window
is not closed; therefore, we can bring it back on top of any other
window with the focus() method. There would be no need to re-create
the window or to reload the referenced resource. */
};
console.log( "function complete" );
console.log( theChannel );
}
</script>
The problem I am having is that in this created variable contains every variable of the array. Therefore when I click on an item it adds the URL of each 'channel_title' and not just the 'channel_title' of the item I clicked on.
I have been trying for hours now to get my head around it - I am terrible with PHP and arrays.
The effect I want to achieve is like on http://onperiscope.com/ when you click on a stream and it opens the stream in a new window.
Thank you for your time, please let me know if I have not given enough information.
I'm not sure I followed exactly which value you want where, but I think something like this should get you in the right direction:
PHP:
<a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'" target="window" onclick="openStreamPopup(\'' . $row['channel_title'] . '\'); return false;" data-islive="'.$whatIsLive.'" title="'.$row['channel_title'].'">
JavaScript:
function openStreamPopup(theChannel) {
...
windowObjectReference = window.open("channels/"+theChannel, "window", "resizable,scrollbars,status");
...
}
So in the PHP you put the "current" value inside the openStreamPopup call as a string (\'' . $row['channel_title'] . '\'), and then that will be available inside your JavaScript function call as the first parameter.
This should get things working, but generally my preference would be to store the contextual value as a data- attribute on the element, bind the onclick event, and inside the handler read the attribute of the triggering element.

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/

how to get text of div in php variable while its text come from js function

Here is my modal code
<p id="getdatevalue" style="display:none;"></p> //HOW TO GET THIS DIV TEXT IN PHP
</div>
I am getting date of php in this anchor tag
<?php
for($i = 1; $i <= $this->daysInCurrentMonth + $this->firstDayOfTheWeek; $i++) {
?>SetRecipe
<?php
$day++;
}
?>
and opening modal window on click of this link
I am passing date as id in some div and getting same id when click on testclass , mean i am getting value of date suppose 27-04-2014 in id populated via lope
<script>
$(".testclass").click(function(event) {
var date_value = $(this).attr("id");
$("#getdatevalue").html(date_value);
});
</script>
using jquery post
<script>
$(".testclass").click(function(event) {
var date_value = $(this).attr("id");
$("#getdatevalue").html(date_value);
$.post('aPhpFile.php',{
dateVal: $("#getdatevalue").html()
});
// since you specifically asked how to get the value from that
// element, but $.post('aPhpFile.php',{dateVal:date_value});
// would be fine
});
</script>
and php (aPhpFile.php);
<?php
$postedVal = $_POST['dateVal'];

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