Ajax page load with <a> tag - javascript

I have an a-tag which when clicked, page gets reloaded and certain php code is executed. On successful execution of php code the page is then redirected to same page.
Now, the problem is that the page is jumping to the top which I guess is normal unless you don't use ajax. So, if I can get some assistance with the lines of codes below.
html:
Unfollow
on clicking the above link this php code is executed
php:
if(isset($_GET['key']) && isset($_GET['val'])){
//some task....
header('location:home.php');
}
NOTE: all codes are is same page home.php
if I can do this without reloading the entire page that would really be helpful.
[Edit] I am really sorry to not have added this in my question. I am using php to show bunch of datas on my page from mysql database. hence all datas have same id and class

try to do this via ajax
Unfollow
<script>
$(function(){
$('.ajax_reload').on('click',function(){
$.ajax({
url : home.php,
type:'POST',
data : {key: $(this).data('key'), val:$(this).data('someval')},
dataType:'json',
success:function(data)
{
if(data.success==1)
location.reload();
}
});
});
});
</script>
in home .php
if(isset($_POST['key']) && isset($_POST['val'])){
//some task....
echo json_encode(array('success'=>1));exit();
}
It may contain some syntax errors it is basic idea how to use it via ajax

To have your redirected page scroll down to the initial location, include a fragment (#) at the end of the location header:
if(isset($_GET['key']) && isset($_GET['val'])){
//some task....
header('location:home.php#ajax_reload"');
}

A more simple solution to this would be to build the link with a tag, and add the tag in the HTML, for example:
Unfollow
<div name="LinkThisPartOfThePage">...</div>
Now your link will point to that particular div

If you want to perform an action in PHP without reloading the page, a solution is by using ajax.
Example :
Html :
Click !
Javascript :
$("#ajaxButton").on('click', function() {
var btn = $(this);
$.ajax({
url : 'phpscript.php?key=somevalue&val=1',
type : 'GET',
dataType : 'json',
success : function(dataObject, statut){
// some tasks ...
console.log(dataObject);
},
error : function(result, statut, error){
console.log(erreur);
}
});
});
PHP :
<?php
if(isset($_GET['key']) && isset($_GET['val'])){
//some task....
return json_encode($result);
}
?>
This way the return of the PHP is use with javascript withount any reloading

Related

Using AJAX to pass Javascript var to PHP on same page

I have a page that started with an empty PHP var. Then, when the user clicks on a link I want to pass the value of the name attribute to a JS var, and then pass that JS var to the same page and then update the PHP var with the JS var value. Here is a simple example of what I am trying to do:
// PHP
<?php
// Starts empty, then when posted should update
$jsVar = $_POST['jsVar'];
echo $jsVar;
?>
<!-- HTML-->
<!-- Link to click with name vlue to pull-->
Click Me
<!-- JAVASCRIPT -->
<!-- Import jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
// On link click
$('a').click(function(e){
// Prevent link default behavior
e.preventDefault();
// Store name vale as jsVar
jsVar = $(this).attr("name");
$.ajax({
type: "POST",
// url: "" <--------------- From what I read, if you want to post to the same page you just don't inclue the URL?
data: {jsVar : jsVar}, // <--------- This was also something I found online that supposedly helps pass JS vars to PHP?
success: function(data)
{
alert("success!");
}
});
});
</script>
A lot of people say that I don't need AJAX for this. The example I provided is a much similar version of what I am trying to do, which is dynamically change an include file based on the user clicking a sidebar item. I don't want to use a form for this, do I?
Ah! As I continued to look, I found that jQuery has the .load() function which is EXACTLY what I wanted. Dang! I was able to build this and make it work:
// Store clicked page
var currentPage = $(this).attr("name");
// Build filepath
var currentPagePath = "pages/" + currentPage + ".php";
// Find the div I want to change the include for and update it
$("#pageContent").load(currentPagePath);
So easy. Dang. Thanks all.

How do I dynamically read from a file using PHP as new information is written into it

I have a code set up where I use JS and PHP to write to a file and display the output to a html element (in this case a textarea). I have a huge problem about how to go about this. I know that PHP is executed before anything else happens. I use php to echo the file content using my own javascript function
output(string) // this outputs whatever into the html element text area
PHP:
<?php echo "output('".$someText."');"; ?>
Now my problem comes around when I update and add contents to that file, but the php has already been executed and trying to read from the file again, will only display results from the last time it executed the php. The only way around this is to refresh the page, thus 'rebuilding' the html content of the file.
This whole code of mine mimics the look and feel of a command line ( you have an output screen with an input box) How can i dynamically display the contents of a file as new content is being added to the file without having to refresh the window. Refreshing the window will work, but not at all what i need for this to work. Any help with this?
For more information about how my code is structured, below you will find a snippet of how the code executes:
// main.php
<?php
// displays the file into the output box
function displayFile($fileName){
$file_handler = fopen($fileName, "r");
while (!feof($file_handler)){
$line = fgets($file_handler);
$line = formatFileLine($line);
echo "output('".$line."');";
}
fclose($file_handler);
}
?>
switch(splitCmd[1]){
case 'permitted':
output('\nWells that have been permitted:\n');
<?php displayFile('permitted.txt'); ?> //calls the php function to display content.
break;
case 'drilled':
output('\nWells that have been drilled:\n');
<?php displayFile('drilled.txt'); ?>
break;
default:
output('Wrong syntax: show <permitted, drilled>');
}
You can do this with an AJAX request, there are multiple ways to do this, but the easiest is with jQuery (opinion based ofcourse!), here is a link to the documentation. jQuery AJAX
Example:
function ajaxCall(){
$.ajax({ url: 'PHPFILE.php',
success: function(e){
//e is what you get returned from the php file
$('#div').html(e);
}
});
}
Oh, and you should ofcourse have the jquery library linked. which you do this way:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
You need to make an AJAX call to your PHP file. Take the output from the PHP script, and embed this into, say, a given div on your page.
Let's pretend you have a div set aside for display. Let's give you a button to refresh it whenever.
<div id="resultdiv"></div>
<input type = "button" id="rbutton" value="Click to Refresh">
Style it any way that you please.
Now, let's set up an AJAX call to load the results from the PHP.
<script type="text/javascript">
$(function() { //document ready psuedonym
function refreshdata(){
$.ajax({
type: "POST",
url: "my_data_script.php",
dataType: 'html',
data: {myparam1: 'abc', myparam2: '123'}, //these are optional parameters in case your PHP script needs them
success: function(data){
$('#resultdiv').html(data);
},
error: function(){
},
complete: function(){
}
}); //end ajax
} //end function
$("#rbutton").click(function() { //clicking the button refreshes the data on demand
refreshdata();
});
refreshdata(); //this will run the function when the page loads
});//end document ready pseudonym
</script>

Reloading a page include every 30 seconds or when user submits form

I have a PHP page with a lot of includes which make up various parts of the page for a video website.
I have a comments section which submits information into a database (Which works fine). But I need to make it so when this is done only the included page/div refreshes.
This is the PHP:
<form id="song-comment-form">
<input type="hidden" value="<?=$rSong->id?>" class="song-id">
<textarea class="editor" id="song-comment-textarea"></textarea><br>
<input type="submit" value="Submit"><input type="button" value="Cancel" id="hide-song-comment-form">
<hr>
</form>
<div id="player-song-comments">
<?php $showComments?>
</div>
Here is my attempt at doing it with Javascript:
<script>
var $comments = $("#player-song-comments");
setInterval(function () {
$comments.load("/template/sections/player_comments.php #player-song-comments");
}, 30000);
</script>
This should reload just the comments section but instead, everything from this point onwards goes blank.
How it looks now when I press submit:
When I reload that page manually:
I don't want the whole page to refresh because it contains a video.
How can I make just that Refresh after submit is pressed OR every 30 seconds?
UPDATE:
I have tried using JQuery to execute this. I'm getting an error:
Fatal error: Call to a member function query() on a non-object in /home/content/58/12052758/html/template/sections/header.php on line 42
<script>
/*wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#song-comment-form').ajaxForm(function() {
alert("Thank you for your comment!");
});
}); */ //THIS IS LINE 42
$(document).ready(function() {
var options = {
url: 'template/sections/player_comments',
target: '#player-song-comments', // target element(s) to be updated with server response
type: 'post' // 'get' or 'post', override for form's 'method' attribute
};
// bind form using 'ajaxForm'
$('#song-comment-form').ajaxForm(options);
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#song-comment-form').ajaxForm(function() {
$("#player-song-comments").load('template/sections/player_comments.php');
alert("Thank you for your comment! The site is currently in maintenance and the comment won't show until you revisit this video");
});
});
});
</script>
For those interested. Here is the whole page: http://pastebin.com/c0kQ3tGp
You seems to load comments in PHP and as far as I know, PHP is only parsed once.
The simplest workaround I know is to use an iframe that you would refresh, but I'm not sure this is a good practice tho.
So there are two parts to your question:
How can I make just that Refresh after submit is pressed
You can use jquery-form for that. In your case, you can initialize your form to something like this:
$(document).ready(function() {
var options = {
url: 'your_form_action',
target: '#player-song-comments', // target element(s) to be updated with server response
type: 'post' // 'get' or 'post', override for form's 'method' attribute
};
// bind form using 'ajaxForm'
$('#song-comment-form').ajaxForm(options);
});
There are many other options you can play with.
OR every 30 seconds?
Try change your
$comments.load("/template/sections/player_comments.php #player-song-comments");
to
$comments.load("/template/sections/player_comments.php"); // remove the selector
According to the docs, the selector is used to insert fragments of the remote document. In other words, when load was executed, jQuery parses the returned document to find the element #player-song-comments. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.... I assume #player-song-comments is not part of your response?

Why is my div populated with my whole page?

I'm trying to load a div from another page using ajax but maintain the URL integrity using the History API. The ajax and history part is working (ie. the div is loading and the url is changing) but for some reason my div contains my entire page not just what is meant to be in the div!
This is the case for both the original page and the page div being loaded.
Stripped back HTML
<!DOCTYPE html>
<html>
<body>
<div id="slider">
... all the page content
<a rel='tab' href="p/password.jsf">Forgot password?</a>
</div>
</body>
</html>
JS
<script>
$(function(){
$("a[rel='tab']").click(function(e){
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
$.ajax({
url:pageurl + '?rel=tab',
success: function(data){
$('#slider').html(data);
}});
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({
url:location.pathname+'?rel=tab',
success: function(data){
$('#slider').html(data);
}});
});
</script>
If you want to fetch an part of an page with ajax, then you can use the load method with the id of the element to fetch the content from.
$('#slider').load(pageurl + '?rel=tab #container_with_content_to_fetch', function() {
alert('callback after success.');
});
More info about load(): info
You may need to stop the default click action. It appears as though your link is acting as a... link.
$("a[rel='tab']").click(function(e){
e.preventDefault();
...
you if you want to select a specific part of the page that you recive with the ajax response
then do the following
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({
url:location.pathname+'?rel=tab',
success: function(data){
var mydiv = $('#my_div_id' , data ) // this will get the div with an id of #my_div_id
$('#slider').html(mydiv );
}});
});
$.ajax loads the whole page. You can use .load()
Instead of
$.ajax({
url:pageurl + '?rel=tab',
success: function(data){
$('#slider').html(data);
}});
you can use
$('#slider').load(pageurl + ' [rel=tab]');
The docs are here.

AJAX script not working after page content changed with another ajax script

I am trying to run two scripts: one for loading page content using ajax and the other uses ajax to submit a contact form.
Load page content:
<script>
$('#top_links a').click(function (e) {
e.preventDefault();
var link = $(this).attr('href');
$('#content').empty();
$.get(link, { },
function(data) {
$('#content').replaceWith($(data).find("#content"));
}
)
});
</script>
Submit Form:
<script type="text/javascript">
$('#submit').click(function(event){
event.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
$.post("<?php echo bloginfo( 'template_directory' ) . '/inc/mailit.php';?>",
{
name: name,
email: email,
message: message
},
function(data) {
var n = data.indexOf('<span class="success_message">');
if (n !== 0) {
$('#message_box_1').empty().append(data);
} else {
$('#contact_form').empty().append(data);
}
}
);
});
</script>
Both Scripts are in the footer and are not included in the dynamically loaded content. When I access the contact page directly without using ajax to load it's content, the form code works perfectly. But when I load the form using ajax, the submit script stops working.
This is actually a follow up question to one I posted earlier. After some thought, Im not 100% sure that the answer I received earlier was accurate. The answer relied on the assumption that the form submit code was part of the loaded content but thats not true since I put all the code in the footer which is unaffected by the content changes. Since I can't uncheck the answer, I needed to repost.
You need to run the Submit form script after the form is loaded.
Try wrapping your submit form script in a function, like applySubmitFormEvents() {...} or something similar.
Then in your callback function you need to call applySubmitFormEvents().
If submit button is in dynamically loaded content, you have to use $.live() function.
$("#submit").live("click", function(e){})

Categories