Next and previous button using jquery - javascript

I am using a PHP Simple HTML DOM Parser to save a website as a htm file. I then use jQuery to extract a div from the file and put it into a div. I want to create a
Previous and Next button but the problem I have is that to do this I have to change the URL so the parser can get the page. I would really appreciate if you can help. Below is the code I am using.
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=1');
$html->save('site/rtnews.htm')
?>
<script type="text/javascript" src="site/jquery.js"></script>
<script type="text/javascript">
$('document').ready(function() {
$('#wrap').click(function (event){
event.preventDefault();
});
$("#wrap").load('site/rtnews.htm #postsArea');
});
</script>
</head>
<body>
<div id="wrap">
</div>
</body>

You will have to create a new php file for this and make an AJAX request to that file. I assume you have already realised that you cannot make a cross-domain request due to CORS.
Here is your new php file, let's call it proxy.php. It will proxy the request, responding with the page that is passed to it via GET :
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=' . $_GET["page"]);
echo $html;
?>
Your new JavaScript;
$('document').ready(function() {
var $wrap = $('#wrap'),
page = 1;
$('#next').on('click', function () {
getPage(++page);
});
$('#prev').on('click', function () {
getPage(--page);
});
var getPage = function (page) {
$wrap.load('proxy.php?page=' + page + ' #postsArea');
};
getPage(page);
});

Related

Update page content from live PHP and Python output using Ajax

Long-time user, first-time asker. I've learned so much from the community and I love this site.
So here is what I'm shooting for. I want to have a web interface that runs ping commands on the backend. I ideally want a website that has a text input that allows you to enter an IP address or domain, a button that runs the command and a python script that runs from PHP to actually run the ping command. The tricky part for was to get the output to print to the website live as it is outputted on the command line. I want to do it this way as a way to future-proof the concept and eventually use different iperf parameters.
I built a little PHP page that "technically" gets the job done but I can't figure out how to only call the PHP script when the button is clicked. Since it's a PHP page, it runs whenever the page is loaded. So after some research, I figure ajax jquery is what I'm looking for. I've spent about 2 days trying different things that get me really close but it seems that I'm dancing around my solution.
From what I've learned about ajax, I essentially need a button that runs an ajax function that is linked to my working php script. I can get it to run the script but I can't get it to update the page content in a live/continuous manner. Only when the command is finished running.
Here is my php page that does what it needs to do but does it everytime the page is loaded/reloaded. Not ideal. I want the script to only run when the button is pressed.
liveping.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="liveping.php" id="ping" method="post" name="ping">
Domain/IP Address: <input name="domain" type="text"> <input name="ping" type="submit" value="Ping">
</form><?php
if (isset($_POST['ping'])) {
function liveExecuteCommand($cmd)
{
while (# ob_end_flush()); // end all output buffers if any
$proc = popen("$cmd 2>&1", 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
$live_output = fread($proc, 4096);
$complete_output = $complete_output . $live_output;
echo "<pre>$live_output</pre>";
# flush();
}
pclose($proc);
}
}
$domain = $_POST['domain'];
$pingCmd = "python /var/www/html/ping.py ".$domain;
if (isset($_POST['ping'])) {
liveExecuteCommand($pingCmd);
}
?>
</body>
</html>
ping.py:
#!/usr/bin/python
import cgi
import os
import sys
ping = "ping -c 5 -W 2 "+sys.argv[1]
os.system(ping)
Some things I've tried:
<html>
<head>
<script>
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = setInterval(function() {
if (ajax.readyState == 4) {
document.getElementById('content').innerHTML = ajax.responseText;
}
},100);
function updateText() {
ajax.open('GET', 'ajax.php');
ajax.send();
}
</script>
</head>
<body>
<button onclick="updateText()">Click Me</button>
<div id="content">Nothing here yet.</div>
</body>
</html>
OR
<!DOCTYPE html>
<html>
<body>
<head>
<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('ajax.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds
</script>
</head>
<div id="load_tweets"> </div>
</body>
</html>
WITH ajax.php
<?php
while (# ob_end_flush()); // end all output buffers if any
$proc = popen("ping -c 5 -W 2 google.com", 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
$live_output = fread($proc, 4096);
$complete_output = $complete_output . $live_output;
echo "<pre>$live_output</pre>";
# flush();
}
pclose($proc);
?>
Thanks for any help!
You do not need python for showing ping results. Just two PHP files will be enough.
index.php will have the AJAX functionalities along with the form.
ajax.php will have the code to ping specified domain address.
I afraid that using jQuery you might not able to catch the live feed. Because it doesn't have any onreadystatechange. So, you might need to use vanilla JavaScript in this case. Here is a working demonstration:
index.php:
<!DOCTYPE html>
<html>
<head>
<title>Ping AJAX</title>
</head>
<body>
<div>
Domain/IP Address: <input id="domain" type="text">
<input id="ping" type="button" value="Ping">
</div>
<div id="result"></div>
<script>
function updateText(domain) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState == 3) {
var old_value = document.getElementById("result").innerHTML;
document.getElementById("result").innerHTML = this.responseText;
}
};
var url = 'ajax.php?domain='+domain;
ajax.open('GET', url,true);
ajax.send();
}
document.getElementById("ping").onclick = function(){
domain = document.getElementById("domain").value;
updateText(domain);
}
</script>
</body>
</html>
ajax.php:
<?php
if (isset($_GET['domain'])) {
function liveExecuteCommand($cmd)
{
while (# ob_end_flush()); // end all output buffers if any
$proc = popen($cmd, 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
$live_output = fread($proc, 4096);
$complete_output = $complete_output . $live_output;
echo "<pre>$live_output</pre>";
# flush();
}
pclose($proc);
}
$domain = $_GET['domain'];
$pingCmd = "ping ".$domain;
liveExecuteCommand($pingCmd);
}
else{
echo "No post request";
}
?>
Output:
Declaimer:
The ping command is changed as I am currently using Windows operating system. Update it according to your operating system.
As a first time questioner, you have described the problem neatly and also showed your efforts to solve the problem. I really appreciate it.
ajax.readyState == 4
essentially means, script on the other side has finished ... 3 is partial.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
You just have to take all ajax script into the function
example:
function updateText() {
$.ajax({
type: 'GET', // can be POST, too
url: "ajax.php",
crossDomain: true,
data: {
firstvar: firstvar,
secondvar: secondvar
},
cache: false,
success: function(data) {
if($.trim(data) == "false") {
alert("Fail to recived data");
}
else {
// Success getting data
// Do some jobs
}
}
});
}
If you want to cancel submit to not refesh, U can use
return false; // At the end of the function above
Hope it helps.

Form data not visible in new page - PHP + Javascript

I have a page containing a set of hyperlinks. Clicking on any of the hyperlinks should take the user to a new page with the url sent as POST data.
What I am able to do:
1. Open the new page.
What issues I am facing:
1. In the new page, I am trying to access the url that was sent across as data. The url is not visible. Where am I going wrong?
The code I have so far:
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function takeMeHome(obj) {
var URL = obj.getAttribute("href");
//alert("Url = " + URL + " with id = " + obj.id);
console.log("URL = " + URL);
$.ajax({
type: 'POST',
url: './bbCloud.php',
data: {'tgt_url': URL},
success:function(data) {
console.log("Function invoked. It seems posting data was a success");
window.location = URL;
//alert('This was sent back: ' + data);
}
});
return false;
}
</script>
</head>
<body>
<p>
Choose one of the links below to access content:</p>
<p>1. Email Etiquette</p>
</body>
</html>
bbCloud.php:
<?php
//the function below displays data from bbMainPage javascript.
function getDataFromLibrary() {
$tgt_url = $_POST["tgt_url"];
echo "Data received = " . $tgt_url . "<br/>";
return $tgt_url;
}
?>
<html>
<head>
<style>
.hlight{background-color:#ffcc00;}
textarea {
width:100%;
height:100%;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://myDomain/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
//mention all global variables here.
console.log("this is the start of javascript");
//get all data from the previous script.
var tgtURL = "<?php getDataFromLibrary(); ?>";
console.log("URl obtained = " + tgtURL);
</script>
<body>
<div>
<audio id="playText" src="" controls></audio>
</div>
</body>
</html>
try dynamically creating and submiting a form instead of trying to ajax it:
<script type="text/javascript">
function takeMeHome(obj) {
var URL = obj.getAttribute("href");
$('<form>', {
"html": '<input type="text" name="tgt_url" value="' + URL + '" />',
"action": URL
}).appendTo(document.body).submit();
}
</script>
Hmm, if I recall correctly, what is happening is that your $.ajax does indeed send the POST data to your php file. The problem is, that it sends the post data, the php file is executed, and a response is sent back, but its sent back to the $.ajax call itself. You THEN redirect to the php file (and thus run it again), but without the post data coming along. Also, something along the lines of $.('a').click(function(event) { event.preventDefault(); } might be a good idea. I'll try and make a better answer for you when I get home (currently on my phone, shouldn't be long).

How do you move the contents of an iframe's body to the body of the page?

UPDATE:
I was mislead, by some mistake I had made, into thinking that I could not both have a running script updating the screen AND an outstanding submit that would reload the page upon completion.
You can do this, and I have. The way that I did it was to place my updater on a startTimeout and let the submit continue.
$('#JQF').on('submit', function(){
start();
return true;
});
...
start:
function (xhr, s) {
$(".appMainMsg").hide();
bar = document.getElementById("ProgressBar");
if (bar)
{
eta = document.getElementById("ProgressBarEta");
startTime = new Date();
infoUpdated = 0;
infoRequested = 0;
$(bar).empty().progressbar();
setTimeout(requestInfo, 2);
}
},
...
ORIGINAL Question:
I have a page that posts a form with file uploads and targets the response to an hidden iframe. When the iframe finishes loading, it calls a function in the (main) page. If all looks good, I want to move the contents of the body that loaded into the iframe to the main page's body, else I will just leave things alone. I do have jquery loaded so I'd like to use that.
<body>
<iframe name='ifr' id='ifr' style='display: none;'></iframe>
<form target='ifr' method='post' action='mypage.php'>
</form>
<script>
function finished()
{ if (iLikeIt)
{
//replace body contents with ifr.body.contents
// keeping all event handlers attached
// something like...
WHAT DO I PUT HERE?
}
}
</script>
</body>
The page loaded into the iframe, ends with:
<script>
setTimeout(parent.finished, 1000); // some time for navel gazing
</script>
You do not need iframe to do this. I recommend to submit your form by ajax.
Since you have jquery loaded, the easiest option for you is to use jquery-form plugin.
Here is a working example of what you are looking for:
index.html:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(function(){
// instead of redirecting to upload.php, your form "#form"
// will now be submitted by ajax and you'll get response
// content in html parameter of success callback
$('#form').ajaxForm({
// you can handle "json" or "xml" content types too
// #see http://jquery.malsup.com/form/#json
dataType: 'text',
success: function(html) {
// in case you want to replace your document
// content with the response content
$(document.body).html(html);
}
});
// This is how you "keep all event handlers attached", with
// live method instead of bind.
// So if you have #btn2 element in ajax response, and you replace
// document content with this ajax response, jquery will auto-bind
// 'click' event on new #btn2 element
// Note that you can also use bind, but you'll have to "re-bind"
// the event manualy (inside "success" callback in this case).
$("#btn2").live("click", function(){alert("button 2 clicked")});
});
</script>
</head>
<body>
<h1>ajax form:</h1>
<form id="form" action="upload.php" method="post">
<input type="file" name="file" />
<input type="submit" value="Submit File" />
</form>
<h1>keeping all event handlers attached exemple:</h1>
<button id="btn2">click me</button>
</body>
</html>
upload.php:
<?php
// here you handle your $_FILES, $_POST, $_GET ...
// html response example:
header('Content-Type: text/html; charset=utf-8');
echo '<h1>This is your ajax html response:</h1>';
echo '<button id="btn1">click me</button>';
var_dump($_FILES);
echo '<h1>keeping all event handlers attached exemple:</h1>';
echo '<button id="btn2">click me</button>';
echo '<script>
$(function(){
// js event handler attached to #btn1
$("#btn1").bind("click", function(){alert("button 1 clicked")});
});
</script>';

jquery noob problem with variables (scope?)

I'm trying to retrieve data from a php file named return that just contains
<?php
echo 'here is a string';
?>
I'm doing this through an html file containing
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var x;
$.get("return.php", function(data){
x = data;
})
function showAlert() {alert(x);}
$(document).ready(function(){
alert(x);
});
</script>
</head>
<body>
<input type = "button" value = "Click here" onClick="showAlert();">
</body>
</html>
When the button is clicked it retrieves and displays the code fine, but on the $(document).ready thing, it displays "undefined" instead of the data in return.php. Any solutions?
Thanks.
the document.ready is running before the $.get has returned the msg probably
var x;
function showAlert() {alert(x);}
$(document).ready(function(){
$.get("return.php", function(data){
x = data;
showAlert();
})
});
that should work fine
The ajax probably has not loaded yet.
var x;
function showAlert() {alert(x);}
$(document).ready(function(){
$.get("return.php", function(data){
x = data;
alert(x);
});
});
It isn't a question of scope, it's a question of order of events. $.get is an asynchronous call, so it may not finish yet by the time your page loads in the browser (it's a fairly small page so I imagine it loads quite quickly).

How do you automatically refresh part of a page automatically using AJAX?

$messages = $db->query("SELECT * FROM chatmessages ORDER BY datetime DESC, displayorderid DESC LIMIT 0,10");
while($message = $db->fetch_array($messages)) {
$oldmessages[] = $message['message'];
}
$oldmessages = array_reverse($oldmessages);
?>
<div id="chat">
<?php
for ($count = 0; $count < 9; $count++) {
echo $oldmessages[$count];
}
?>
<script language="javascript" type="text/javascript">
<!--
setInterval( "document.getElementById('chat').innerHTML='<NEW CONTENT OF #CHAT>'", 1000 );
-->
</script>
</div>
I'm trying to create a PHP chatroom script but I'm having a lot of trouble getting it to AutoRefresh
The content should automatically update to , how do you make it do that? I've been searching for almost an hour
I would take that PHP functionality you have and putting it in a sperate page that returns JSON. From there you can call that method using jQuery and the AJAX tools built in. Really simple. Start here for jQuery: http://api.jquery.com/category/ajax/
you'll need to set up a server side script that renders only the contents of the chat div and use ajax to grab that. it can be done with jquery quite easily:
In your html document:
<head>
...
<script src="/path/to/jquery.js" type="text/javascript"></script>
<script>
var chatUpdateInterval = null;
function initChat() {
chatUpdateInterval = window.setInterval(updateChat, 5000); /* every 5 seconds */
}
function updateChat() {
$.ajax({
url: '/url/path/to/your/script.php'
,dataType: 'HTML'
,success: function(data, status, xhr){
$('#chat').append($(data).html());
}
});
}
$(document).ready(function(){
initChat();
});
</script>
...
</head>
<body>
<div id="chat">
please stand by while we're firing up the coal!
</div>
</body>
Note that this won't be really good, it's just a sample to get you started. you should look into jquery's $.ajax

Categories

Resources