Basically I want to have a button on my HTML/PHP page which will once clicked send a call to another php page which will update a value in mysql table.
<html>
<head>
<script>
src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
function toggleText(button_id){
if(document.getElementById(button_id).innerHTML == "Uninstall All"){
document.getElementById(button_id).innerHTML = "Cancel Uninstall";
//ajax////////////////////
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "valueChange.php?uninstalled=1&type=all", true);
xmlhttp.send();
////////////////////////
}
}
</script>
</head>
I'm curious why this isn't working.
I had tested my toggleText function without the ajax and it changed the HTML properly.
But once I add in the ajax to visit this valueChange.php page and update an sql value it doesn't work.
I've tested the php page by itself and it properly updated the value in sql.
I've never used ajax so I'm curious if I'm doing it wrong? I thought my src = "google/ajax/jquery" was the way to install it. Or is there a library I need to install on the VPS hosting my site?
The only mistake I see in above code is just a typo. See line 3 you closed the script tag before the second attribute it should have been <script src="*link to jQuery*" ></script>
And another thing you don't need to use the jQuery library to use XMLHttpRequest() method.
The modified code:
<html>
<head>
<script>
function toggleText(button_id)
{
if(document.getElementById(button_id).innerHTML == "Uninstall All")
{
document.getElementById(button_id).innerHTML = "Cancel Uninstall";
//ajax////////////////////
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "valueChange.php?uninstalled=1&type=all", true);
xmlhttp.send();
////////////////////////
}
}
</script>
</head>
Related
I have code in /user.php:
<?php
$thisuser = $_GET['user'];
echo $thisuser;
?>
And i write in browser: /user.php?user=Maria
And the website do not echo anything. What is wrong about it?
I actually have a ajax script that should send there a variable by get but it do not work at all.
EDIT here is the whole thing:
echo '<div class="thisphotobox"><div class="photouser">' . 'Dodał: '.$numphotos["user"].'</div>';
<script>
function prof(profuser){
var xmlhttp=new window.XMLHttpRequest();
xmlhttp.open("GET", "user.php?user=" + profuser, true);
xmlhttp.send();
}
</script>
This seems to be related to the <a> tag's default behavior preventing your function to execute on click.
Since you are setting the URL inside the prof() function, you don't need he href value inside the <a> tag, so you could do something like this:
echo '<div class="thisphotobox"><div class="photouser">' . 'Dodał: '.$numphotos["user"].'</div>';
Note that I just set the href value to javascript:void(0);. So now onClick should take effect and the prof() function should be invoked.
** Visually verify if it's working: **
Use this javascript code:
<script>
function prof(profuser)
{
var xmlhttp=new window.XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if ( (xmlhttp.readyState == 4) && (xmlhttp.status==200) )
{
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "user.php?user=" + profuser, true);
xmlhttp.send();
}
</script>
Then you will also have to add, in the same file where the javascript code is, the following:
<div id="result"></div>
Finally, please make sure you are properly closing the PHP tags <?php ?> and make sure that only PHP code is inside that block. HTML and Javascript must be outside that block.
The AJAX script will send the data by POST not by GET.
GET is to 'get' the value, POST is to pass the value.
You also only use the send() value for POST, so change the GET to POST in the AJAX.
Also, you need to declare your script BEFORE you call it in the HTML.
What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
What I have tried.
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents()
I have javascript function plotting data from one of the simpleXML_Load_file()...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
If I need to elaborate more just ask!
Thanks,
JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body
The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
Example:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
File 1: file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php
I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>
I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
JQuery
JQuery learning center
A small example:
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
adding the following php file
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.
It is kind of nasty solution to your problem...
But this can work:
You work with those -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif...
Then you do all the processing and calculating you want...
At the end of the processing, just echo a small script that does a hide to your gif...
Depends on the exact need, maybe ajax can be more elegant solution.
In response to your conversation with David Constantine below, did you try using ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();
I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?" In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.
I know this is an old question, but the answer provided in this page by rpnew is extremely clear and easy to adjust to your project's requirements.
It is a combination of AJAX and PHP.
The HTML page PHPAjax.html which calls the PHP script:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".
I am using the very basic technique of AJAX to save the form into a database using AJAX.
However I am having some trouble.
All I searched, I was getting jQuery code, but I want to do this with simple AJAX only.
HTML FORM:
<form id="submitcourse" name="submitcourse" method="get">
<p>Course Name: <input type="text" name="cvalue" id="cvalue" /></p>
Successfull
</form>
<span id="result">.</span>
AJAX CODE:
<script type="text/javascript">
function GetXmlHttpObject()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if(window.ActiveXobject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function submitformwithajax()
{
var myAjaxPostrequest=new GetXmlHttpObject();
var coursename=document.submitcourse.cvalue.value;
var parameter="cvalue="+coursename;
myAjaxPostrequest.open("GET", "do.php", true)
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameter)
myAjaxPostrequest.onreadystatechange=function{
if(myAjaxPostrequest.readyState==4){
if(myAjaxPostrequest.status==200){
document.getElementById("result").innerHTML=myAjaxPostrequest.responseText;
document.getElementById("submitcourse").style.display="none";
}
else
document.getElementById("submitcourse").innerHTML="An error has occured making the request";
}
}
}
</script>
The purpose of the above AJAX code is to send the form details to do.php File, where I can work on the data received.
do.php File :
<?php
$course=$_REQUEST['cvalue'];
echo "dddd".$course;
?>
Right now I am not able to get the value in the do.php file, Please help me out,
NOTE: I have the code to do this using jQuery, but I want to do it in this method only. Since it is for teaching students about Basic AJAX.
Right off the bat I'm noticing that you don't have () after your function definition...
myAjaxPostrequest.onreadystatechange=function{
Should be
myAjaxPostrequest.onreadystatechange=function(){
Let me know if this helps!
The problem is: you put your parameter inside send(), which is not correct, because you sending GET request, change your code to:
myAjaxPostrequest.open("GET", "do.php?"+parameter, true)
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send()
Using Ajax GET, the parameter should be mixed with the URL, however, your code is correct for POST method.
or if you want to use POST
myAjaxPostrequest.open("POST", "do.php", true)
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameter)
See if you can't get away with using getElementsByName instead
var coursename=document.getElementsByName('cvalue')[0].value;
I'm learning AJAX and created this simple code. I type in something in the text box and it should return with the word something pop up on screen. This was able to work when I clicked on a button but now that I changed it to a text box it no longer works. Here is the first file that contains the XML HTTP Request data and HTML code.
<html>
<head>
<script type="text/javascript">
function load() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('results').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'test_ajax_return.php', true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="search" name="search">Type a name:
<br>
<input type="text" name="search_text" onkeydown="load();">
</form>
<div id="results"></div>
</body>
</html>
And here is the second file that I want to open when the user types in something in the text box.
<?php
echo 'something';
?>
[SOLVED] : Thanks to Matt for Javascript Console. Found out some comments that I edited out effected the code after all. I didn't think HTML comments could do that. Lesson learned.
Open up your javascript console (F12 in Chrome) and see if there are any errors (indicated by a red X on the bottom of the popup).
You most likely have javascript errors that you're not catching.
I just copied the code to my machine, it works perfectly.
As an idea though, maybe your browser's being funny about onkeydown. Try onKeyDown instead.
Is it possible to trigger a PHP function by just clicking a link? Or should I stick with the form submit method? If clicking the link will work, where should the link refer to?
Here is a sample code:
<?php
session_start();
function listMe($username){
$username = mysql_real_escape_string($username);
$query = mysql_query("INSERT INTO List (Usernames) VALUES ('$username')") or die(mysql_error());
}
?>
<html>
<head>
<title>SAMPLE</title>
</head>
<body>
Add my username to the list
<?php
listMe($_SESSION['Username']);
?>
</body>
</html>
Maybe someone can point me in the right direction. Thanks!
You can do this by means of loading the entire page over again by the use of form submission, or by loading specific page contents directly into the page without needing to go from page to page. The second method is called "AJAX" (Asynchoronous Javascript and XML). Here are two examples, one of each specified.
Form submission approach
form.php
<?php
function get_users(){
}
if(isset($_GET['get_users']))
{
get_users();
}
?>
...
<form method="get">
<input type="hidden" name="get_users">
<input type="submit">
</form>
AJAX approach
ajax_file.php
<?php
function call_me(){
// your php code
}
call_me();
?>
form.html
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
// do something if the page loaded successfully
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
click to call function
</body>
</html>
HTML
list me
PHP
<?php
if (isset($_GET['list_me'])) listMe();
(EDIT although this works, it's a bad idea as it is. One should never read from $_GET without sanitising it first)
You can pass it as a query parameter of the link.
http://example.com/?command=listMe&username=tom
However that way everybody will be able to run the function by loading that URL
List me
and in the PHP
<?php
if( isset($_GET['list_me']) && isset($_SESSION['Username'] ) ){
listMe( $_SESSION['Username'] );
}
?>
To trigger a function on link click with php the only way I know would be to append a param in the url of the link and then listen for that
Add my username to the list
Then check for link
if (isset($_GET['function'])){
runFunction();
}
This is because php is a server side technology if you want to fire something without refreshing the page you would need to look at something like javascript
I found this code in a plugin, they have user a foreach look to trigger the action:
$actions = unset($meta[$key]);
foreach ( $actions as $action => $value ) {
echo '<li>' . '<i class="fa fa-times"></i></li>';
}