HTML button to load data and refresh UI - javascript

Here the situation:
In my html page I have a link, which onclick runs a PHP script.
<iframe style="display:none;" name="target"></iframe>
Load new tasks
I use an invisible iframe to execute the script but I stay on the same page.
This link executes script.php which updates mysql database, but in order to see new content the page must be reloaded.
Of course I can always create a separate button/link that reloads current page.
But I wonder if there is a way to execute the PHP script and reload current page with one html button.

Better use it this way:
1: Use a common Javascript Framework, for example JQuery
2: Create your Link and a Div for your Content:
Update my Data and reload my new Content
<div id="result"></div>
3: Use Jquery to add the click event to your link:
$('#reload').click(function(e) {
// Prevent from going to the link provided in href
e.preventDefault();
// make POST Request to script
$.post( "myScriptHandler.php", { value1: "1", value2: "2" })
.done(function( data ) {
// if done, refresh my Div with html content from your PHP Script
$('#result').html('')
$('#result').load('mydata.php');
});
}

You don't need AJAx - just return a script into the iframe which updates the toplevel page...
<?php
....
$new=run_updates();
print "<div id='newcontent'>$new</div>\n";
?>
<script>
var dest=parent.document.getElementById('oldcontent');
var src=document.getElementById('newcontent');
dest.innerHTML=src.innerHTML;
</script>
(not tested, YMMV)

I show you how to use Ajax in this case:
here is your html and js code:
<script type="text/javascript">
$(".link").on("click", function() {
$.ajax({
url: "your_php_script.php",
dataType: "json",
cache: false,
success: function(data) {
location.reload(true);
}
});
});
</script>
<html>
<body>
<a class="link" target="target">Load new tasks</a>
</body>
</html>
When you click the 'a' tag, the jQuery Ajax script call your php script, and when it return with success, then your page will be refresh.

Related

I want to show data which got from a php file to all tab pages by using ‘storage event’

I want that when I click on logout, ck() function will be fired and there is an ajax method. By ajax method I have send some data to object.php file. After success all process I will get I got It string. Now I want that when this data I will get, 'storage' event will execute and I got It will show all index.php tab pages at a times without any refresh or click again logout. I am very very sorry for my poor English. It is my first question.
index.php:
<script>
function ck(){
var ok="thx";
$.ajax({
type:"GET",
data:{mt:ok},
url:"object.php",
success:function(html){
if(html!=""){
localStorage.setItem('store-it', html);
window.addEventListener('storage', function (event){
if(event.key=='store-it'){
$(".show").text(event.newValue);
}
})
}
},
});
}
</script>
<p onclick="ck()">logout</p>
<p class="show"></p>
object.php
<?php
if(isset($_GET['mt']) && $_GET['mt']=="thx"){
echo "I got It";
}
?>

Anchor tag update div without page reload

I have this div which includes an anchor tag that loads a php script that essentially adds information to a database and returns back to this page. I want to use this achor tag to run that php script update the database and refresh this div without reloading the page. The php script need those two variables title and vote which used with the php $_GET[] function. Can this be done, and if so how? I have searched everywhere and no script seems to work. Will provide more information if needed. Thanks so much will give credit to everyone who helps.
<div class='like_box'>
<a href='#' class='counter' ><img src='img/like.png' class='vote'></a><p class='vote_text'>$like_num</p>
<p style='color: #fff;'>$like_username</p>
</div>
I've tried something like this
<script>
$('a.counter').click( function(e) {
e.preventDefault();
vote.php?vote=like&title=$title
});
</script>
Use this:
<div class='like_box'>
<a href='#' class='counter' ><img src='img/like.png' class='vote'></a><p class='vote_text'>$like_num</p>
<p class="vote_text1" style='color: #fff;'>$like_username</p>
</div>
In the javascript side (jquery)
$(".like_box a").click(function(event){
event.preventDefault();
$.ajax({
url: 'vote.php?vote=like&title=$title',
success: function(result){
// update $like_num and $like_username here
// if you do not have them binded use this
$('.like_box p.vote_text').text('<value from result>');
$('.like_box p.vote_text1').text('<value from result>');
}});
});

Ajax data disappeared when I come back

I make a html page and there is ajax call for get some data.
after success ajax call, I render to html element with the json data which is from the ajax call.
But, If I go to other page by click some link, and when I come back there is no data at all.
how can I preserve the data element when I come back from other page.
<!DOCTYPE HTML>
...
...
<body>
<div id='data'>
</div>
<a href='/next'> NEXT </a>
<script type='text/javascript'>
$.ajax({
type : 'GET',
url : '/data/user',
...
...
success: function(json) {
$('#data').append(json.username);
}
...
</script>
</html>
When I click 'NEXT' and history back. the username is go away.
When page is reloaded all data came from ajax will be lost definitely. you can faster your ajax call if you already make ajax call earlier by using cache property
$.ajax({
url: "test.html",
cache: true
})
.done(function( html ) {
$( "#results" ).append( html );
});

How to load PHP page with variables passed from javascript

I'm new to PHP and am trying to figure something out that I'm sure is very basic. What I am wanting to do is generate variables in javascript and pass these to a PHP page which then loads and displays. The problem is, I seem to be able to both POST variables to the PHP page and load the PHP page but am unable to load the PHP page with the variables that I POSTed.
Here is an example of my code:
index.php
...
<script language="javascript">
function passToPHP(){
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
data: {
varToPass: "foo"
},
success: function(){
window.location.href="/TraceExperiment/TraceExperiment.php";
}
})
}
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
TraceExperiment.php
<?php
$tempVar = $_POST["varToPass"];
echo("hello" . $tempVar);
print_r($_POST);
?>
What is happening when I click displayPHP is that the ajax POST succeeds and
TraceExperiment.php loads fine (it actually has a whole heap of other html, php etc. code that loads and displays fine but for simplicity I've excluded that) but the $_POST array seems to be empty.
i.e. what ends up being displayed when I try to echo and print the POST array and variables is:
Notice: Undefined index: varToPass in C:\xampp\htdocs\TraceExperiment\TraceExperiment.php on line 3
helloArray ( )
Any help resolving this would be much appreciated. Ultimately, I'm simply after a way to display a PHP page that uses variables passed from a javascript file.
You can dynamically create a form in JavaScript and submit it rather than calling ajax and refreshing the page:
<script language="javascript">
function passToPHP(){
$('<form action="/TraceExperiment/TraceExperiment.php" method="POST"><input type="hidden" name="varToPass" value="foo" /></form>').appendTo('body').submit();
}
</script>
<input type="button" value="displayPHP" onclick="passToPHP()"></input>
You can do a get request like this
<script language="javascript">
function passToPHP(){
var varToPass= "foo"
window.location = "/TraceExperiment/TraceExperiment.php?varToPass="+varToPass;
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
<?php
$tempVar = $_GET["varToPass"];
echo("hello" . $tempVar);
?>
or a post request by creating a simple form
$('#frm').submit(function(e){
var varToPass= "foo"
e.preventDefault();
$(this).find('#varToPass').val(varToPass);
$(this).submit();
});
<form id ="frm" method="POST" action="/TraceExperiment/TraceExperiment.php">
<input type="hidden" id="varToPass"/>
<input type="submit"/>
</form>
dont redirect to the same page on success. you are getting the undefined var on second go to that page
function passToPHP() {
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
dataType:text,
data: {
varToPass: "foo"
},
success: function(data) {
console.log(data);
}
})
}
try doing like this
if you want to show the message in the html
try
success: function(data) {
$('body').append(data);
}
There is 2 solution for This
by the different approach
Generate your variable value by JavaScript and than use
Write in TraceExperiment.php
function genratenumber(){
return "number"
}
window.location.href= "/TraceExperiment
/TraceExperiment.php?yourvar="+genratenumber()
</script>
<?php }else{
// get the value of $_GET['yourvar']
} ?>
Than get it by using $_GET['yourvar'] on same page
By using your approch
you need to put that variable in session (in ajax file) than only you can get that variable

Link to a page and trigger ajax via the same button

I'm trying to make a div button which triggers ajax and links to a page which the ajax is posting data to. I have the ajax working on click, but can't seem to get the link to work at all with it, all the ways I've tried to get the link working do nothing.
I have a div button:
<div class="cman shadow1" id="search_button" value="carSearch"/>
Start Search
</div>
Which triggers:
function carSearch()
{
$.ajax({
type: "POST",
url: 'searchpost.php',
data:
{
mpg : $('.mpg').val()
},
success: function(data)
{
alert("success! "+$('.mpg').val());
}
});
}
Edit:
Feel I should mention that the page I wish to link to is atm:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('cdb', $conn);
if(isset($_POST['mpg']))
{
$mpg = (int)($_POST["mpg"]);
header("Location: home.php");
exit;
}
?>
I wish to use this to gather all of the search fields the user enters to then load the search results page. The above code for it is just for testing right now.
I mention this as user #Doge suggested doing document.location.href = "searchpost.php" in the success handler of the ajax, this did cause the page to change but the page didn't run the isset and the redirect, so the js variable wasn't posted, or it was but this instance of the page didn't get it.
The isset and redirect do work as using the XHR Network tab on my page the page it is to redirect to appears.
If you must do this via js then create a hidden form, populate it and submit it:
html:
<form method="post" id="hiddenform" action="searchpost.php">
<input type="hidden" name="mpg" id="mpg"/>
</form>
js:
function carSearch()
{
$('#mpg').val(yourjsvariable);
$('#hiddenform').submit();
}

Categories