Want to Click on a Website Button Programatically - javascript

I want to Click on a Website button that are already going on.
For example:
like url: www.google.com..
I want to Click Google Search button programmatically by using any method in PHP, Javascript, Jquery and Ajax.
if Anyone know Solution. Please tell my and provide the source code.
Note: We dn't need to create own button we want to click on a website button by using class and id.
I want to try this..look like this but not success..I want to click Learn HTML button that are show on iframe...in w3school website..
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<iframe src="http://www.w3schools.com" width="800" height="400"></iframe>
<script>
//setInterval(function () {$("#hand_1151079882").click();}, 3000);
function clime(){
setInterval(function () {document.getElementById("#w3-btn").click();}, 3000);
alert();
}
//using javascript
$(document).ready(function () {
$(".cli").on('click', function(event){
$("#w3-btn").trigger('click');
});
});
</script>
<input type="button" class="cli" name="clime" value="submit" onclick="clime()">

you need set id for iframe
var iframe = document.getElementById('w3schools-home');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
innerDoc.getElementsByClassName('w3-btn')[0].click();
[0] is for button Learn HTML, there 19 element have class w3-btn
Tested and Work on w3schools Try it Yourself ยป
IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.
as Requested, here example PHP for get Element and Recreated to your own sites.
<?php
$url='http://www.w3schools.com/css/default.asp'; // or use $_GET['url']
$scheme=parse_url($url)['scheme'];
$host=parse_url($url)['host'];
$domain=$scheme.'://'.$host;
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
curl_setopt($ch,CURLOPT_POST, 0);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML(substr(curl_exec($ch), curl_getinfo($ch, CURLINFO_HEADER_SIZE)));
$xpath = new DOMXpath($dom);
$aElement = $xpath->query('//a');
$length = $aElement->length;
$links=array();
for ($i = 0; $i < $length; $i++) {
$element = $aElement->item($i);
if ($element->tagName=='a' && trim($element->textContent)<>'') {
foreach ($element->attributes as $attr) {
$attrName = $attr->nodeName;
$attrVal = $attr->nodeValue;
if($attrName=='href' && str_replace(';','',$attrVal)<>'javascript:void(0)'){
if(substr($attrVal, 0, 1)=='/'){
$links[trim($element->textContent)]=$domain.$attrVal;
}else if(substr($attrVal, 0, 4)=='http'){
$links[trim($element->textContent)]=$attrVal;
}
}
}
}
}
foreach ($links as $key=>$value) {
echo ''.$key.' | ';
}
You can create a javascript function to get URL from iframe and than request AJAX to PHP that have script ABOVE, you can use echo(but need foreach as example from my script) or json_encode to array $links, then reCREATED button from other url/website to your sites.
or just echo to your sites.
My script still need improvement to handle value of attribut href that use '../' or 'foldername/'
just reminder, for get access ELEMENTS on iframe that pointing to different domain is impossible.

You seem to be missing the element with the id w3-btn which gets clicked programmatically.
Also, it seems both of these are doing the same thing ...
function clime(){
setInterval(function () {document.getElementById("#w3-btn").click();}, 3000);
alert();
}
and
$(document).ready(function () {
$(".cli").on('click', function(event){
$("#w3-btn").trigger('click');
});
});
both are trying to click an element with id w3-btn, just in different ways. You only need one of them.

This might help:
<script>
jQuery(function(){
jQuery('#modal').click();
});
</script>
I got this answer from here.

Related

Refresh part of my php page with setInterval()

I have a value on my PHP page and I want to refresh it per second with setInterval().
So I actually know how to refresh values with html etc. But now I want to do the same with php values. Here is my code:
<script>
setInterval(function()
{
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
?>
},1000);
</script>
Ofc this isn't working since JS and php arent really great together.
and in my table I just simply have:
<table>
<tr>
<td>Activity:</td>
<td><p id='MachineActivity'></p><?php echo $TimeMachineActive; ?></td>
</tr>
</table>
So the problem now is, it's only refreshing when I press f5. But now I want the autorefresh. I know setInterval() worked for html. Is it possible to get this done for php code?
This should work for you:
JS Code:
<script>
setInterval(function()
{
$.ajax({
url: 'value-generation.php',
type: 'get',
success: function(response){
$("#MachineActivity").html(response)
},
});
},1000);
</script>
value-generation.php code:
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
echo $TimeMachineActive;
?>
This is how you convert php value to javascript value
<script>
setInterval(function(){
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
?>
var n_val = "<?php echo $TimeMachineActive; ?>";
console.log(n_val);
},1000);
</script>
Change console and give it to your desire.
But does this make the loading time more ? Every second you are calling a remote page and checking ?
When you refresh, PHP returns the whole page again, and it cannot refresh parts of the page. So if you want just part of the page refreshed, you'll need to use iframes.
<body>
<h1>This is my main PHP page</h1>
<iframe src="[url-to-another-php-page-with-only-the-timer]"></iframe>
</body>
And then you'll have to do a separate php page with just the timer value, and serve the html with a meta tag - this meta tag will do the refresh. Meta tag is detailed in this ticket: PHP - auto refreshing page
You need to define setInterval function.
function setInterval($f, $milliseconds)
{
$seconds=(int)$milliseconds/1000;
while(true)
{
$f();
sleep($seconds);
}
}
Now call your set interval function and it should work fine.
As you know, a PHP file will make the server generate a page when you call its URI.
The way you are using your script won't make the server "regenerate" the page and update the values.
Assuming this, you can:
Externalize the php code which is in your setInterval function (ex: update_time_machine.php)
Recall the externalized PHP resource(using IFrame or a request)
Update your page through Jquery/JAVASCRIPT using the PHP script output.
Edit: Mihali's answer sounds the cleanest one.
I'm sure this will work for you
<script>
setTimeout(function(){
location.reload();
},1000); // 1000 milliseconds means 1 seconds.
</script>

Convert PHP objects array to javascript array

I retrieve image paths with the function get_all();. This get_all function retrieves images as an object. This object has the attributes name, source_path and date. I want my javascript to add images to a div. I have the following:
The instantiate.php includes files like Jquery and another JS file.
<?php
require_once("../../include/instantiate.php");
$photos = Photos::get_all();
$JSPhotos;
foreach($photos as $photo) { $JSPhotos + $photo->source_path; }
?>
<script type="text/javascript">
$(document).ready(function() {
var photos = <?php echo json_encode($JSPhotos); ?>;
for(var i = 0; i <= 10; i++)
{
create_image("../"+photos[i]);
}
});
This does not work. Anyone got a solution?
Solution in Jeroen's Post!
New Problem;
In the create_image function I set the class and src of the image element. When you click such an image I want an alert box to show up. I have checked if the class is set correctly, and I concluded that all images did have the classname "imgid". So, any idea why this dont work?
Script in the javascript part:
$(".imgid").click(function() {
alert("hey");
});
You are not assigning anything to your variable.
You probably want:
$JSPhotos = array();
foreach($photos as $photo) {
$JSPhotos[] = $photo->source_path;
}
Or something similar.

Whats wrong with my jquery select

login_view.php
I am just trying to use some jQuery to select the a drop down I have created via code igniter's form helper. I have tried different javascript statements on the browser console but keep getting "undefined" for this form element. :(
<?php
//build html for company drop down
$form_options['--'] = "--";f
foreach ($client_list as $client) {
$form_options[$client['co_id']] = $client['co_name'];
}
$js = 'id="companies"';
echo form_dropdown('', $form_options,'', $js);
?>
<input id="login" type="submit" value="Login">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">
$('#login').click(function() {
var co_id = $(this).find('#companies').val();
console.log(co_id);
});
</script>
In this case there is not need to use find() because the element companies doesn't have #login as its parent. So you need to change it too
var co_id = $('#companies').val();
Just use
var co_id = $('#companies').val();
$(this).find('#companies').val(); you are trying to find element with id companies inside element with id login which doesn't exists .
Id's are unique so can call them directly using id-selector

How can I create a custom function in PHP for HTML tags?

Last time I asked for help in PHP and I got great response. Thanks to all of you for that. Now I am learning and creating website using MVC PHP. I want to ask you that can I create a custom function to use html tags? I am trying to remember that where I saw an example of it. Actually I've seen it before in and open source project.
It was like something this:
htmltag(script(src=address, type=javascript))
Its output was in html like:
<script src="address" type="javascript"></script>
So can I create something like this? I am trying to do this way:
public function script($var1, $var2){
$var1 = array(
'type'=>'',
'charset' => '',
'src' => ''
);
$var2 = false;
print("<script $var1>$var2</script>");
}
So can anyone guide me with this? Do I need to create class first? I will be waiting for your reply friends.
Javascript works with DOM, see the reference
function htmltag(name,atts) {
var tag = document.createElement(name);
for(var i in atts) tag.setAttribute(i, atts[i]);
return tag;
}
var img = htmltag("img", {
src: "https://kevcom.com/images/linux/linux.logo.2gp.jpg",
alt: "linux logo"
});
document.body.appendChild(img);
Note that img here is object (XML Node), not just plain text, so you can attach events on it etc. If you want to extract just the plain html code from it, use img.outerHTML. Test it on the fiddle.
Note: print is the equivalent of Ctrl+P in the browser :-) it is not the print equivalent in PHP.
In PHP you can use DOM::createElement and other methods from DOM which are quite similar to those from javascript. Personaly I prefer something more simple:
function tag($name,$atts="",$content="") {
$str_atts = "";
if(is_array($atts)) {
foreach($atts as $key=>$val) if(!($val===null || $val===false)) $str_atts.= " $key=\"$val\"";
} else $str_atts = " ".preg_replace("/=(?!\")(\S+)/m","=\"\\1\"",$atts);
if($name=="img" && !strpos($str_atts,"alt=")) $str_atts.= " alt=\"\"";
if(in_array($name,array("input","img","col","br","hr","meta"))) $name.= "/";
if(substr($name,-1)=="/") { $name = substr($name,0,-1); return "<{$name}{$str_atts}/>"; }
else return "<{$name}{$str_atts}>$content</$name>";
}
Examples
echo tag("p","class=foo id=bar1","hello");
echo tag("p",'class="foo" id="bar2"',"hey");
echo tag("p",array("class"=>"foo","id"=>"bar3"),"heya");
echo tag("img","src=https://kevcom.com/images/linux/linux.logo.2gp.jpg");

jQuery $.post() using output data as selector

I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr

Categories