I want button to do simply task, execute php code - php

I want my button to do simple task, when i click on it it should send
$sql = "UPDATE `user` SET `free`=2 WHERE username='$username'";
$result = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($result);
but without refreshing. I know how to do it, but everytime i click on button it refresh page ( tried with a href that set up to other page etc). Is any way to set it so?
I meant not send, but execute this one.

I would recommend you using AJAX to send your data to a PHP page that will do the task you want.
With Javascript:
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send(); } </script>
With jQuery:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
} });

your looking for ajax
http://en.wikipedia.org/wiki/Ajax_(programming)
Most (maybe all) javascript frameworks have wrappers for AJAX to make it easier
http://api.jquery.com/jquery.get/
and
http://api.jquery.com/jquery.post/
for example

Related

Live update php variable and simultaneously, show the value in a textbox

This is my table row click function in the file, 'BAConsult.php'. On click, showconsultationdata function will run.
$(document).ready(function(){ //table row click
}).on('click','.consultclick tr',function(e){
if(e.target.tagName === "TD"){
$(".consultclick tr").removeClass("highlight");
$(e.target).parent().addClass("highlight");
}
var dateconsulted = $(this).attr('value');
alert(dateconsulted);
showconsultationdata(dateconsulted);
});
This is my ajax script
function showconsultationdata(str) {
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint2").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Here is another php file called 'BAConsultRecordsAJAX.php' where i placed the ajax of the showconsultationdata.
session_start();
require('Config/Setup.php');
$q = $_GET['q'];
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareremarks=$row['skincareremarks'];
$skinconditionremarks=$row['skinconditionremarks'];
}
On table row click, $skincareremarks and $skinconditionremarks should be updated. And these values will show up in the textboxes in the 'BAConsult.php' page. How can i do this?
So, i followed #Jeff's method by using JSON. However, I realised that the xmlhttp.responseText wasn't only showing my JSON encoded code, but also my javascript which was why the JSON.parse method was unable run properly. I then did the following:
In my BAConsultRecordsAJAX.php file, i did this.
echo "<div id='test1'>";
echo json_encode(array('first'=>$skincareremarks,'second'=>$skinconditionremarks));
echo "</div>";
I gave this output a div called 'test1'.
Then, in my main file's AJAX script, i did this.
var a = JSON.parse($(xmlhttp.responseText).filter('#test1').html());
document.getElementById("test").value=a.first;
So basically, it filters out the rest of the xhtmlhttp.responseText outputs, and selects only the contents in the div where id='test1'.
Hope this helps those who have this problem too..

Ajax loading content of same page

I just copy paste the code form w3school
In load_second.php I simply load gethint.php and rest of the code is same as in w3school.
function loadDoc() {
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "gethint.php", true);
xhttp.send();
}
gethint.php has this code<?php echo "ghjghjghj";?>
but when I run it on my local host it is not working properly.
I am using xampp. I run load_second.php on local host and following thing happens when I click on Change Content it display another Change Content button
Try using jQuery's Ajax.
Its in my opinion way simpler.
$.get( "gethint.php", function( data ) {
$( "#demo" ).html( data );
console.log( "Load was performed." );
});

Is there any way for adding non-form elements to GET URL?

I need to pass some data over GET URL which is not in form, is there any way to include non-form data into GET method?
http://localhost/land1/index.php?visitorName=&visitorPhone=&submit=Submit
which is ok for form elements like visitorName and visitorPhone, but i need to pass some other info also with this, like some fixed non-form data.
And i have to use only html, in form submitting page, no php.., target is php.
You can use input type=hidden for this purpose.
For e.g.
<input type="hidden" name="fixedData" value="some data" />
Use Ajax in this case-
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", "/myUrl?<[parameters]>", true);
xmlhttp.send();
}
</script>
You can add form as well as non-form parameters here -
xmlhttp.open("GET", "/myUrl?<[parameters]>", true);

xmlhttp.open(url) and Calling php function using AJAX not working?

Just beginner in php, I want to call php method using AJAX. I tried every thing but don't know what error is. Not getting any response from object xmlhttp.
Heres my java script code :
function loadData(){
var mID=ddItems;
var method=2;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
if (xmlhttp.readyState == 4 || xmlhttp.readyState == 0) {
xmlhttp.open("GET", "../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method, true); **// is this statement correct**
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) **//conditin is false,**
{
document.getElementById("ddItems").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send();
}
}
My js file is on "projectname/javascript/script.js" and my php file is in "projectname/code/GetItemsInDD.class.php" dir.
Why don't you use jQuery for making AJAX requests? Its as simple as this, include jQuery in your page
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
and JS code,
$.ajax({
type: 'GET',
url: '../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method',
success: function (data) {
document.getElementById("ddItems").innerHTML = data;
}
});
This way, you don't need to check for the readyState and status thing
jQuery follows object oriented approach for declaring XMLHttpRequest objects, so you won't have to worry about creating multiple objects for making more than one AJAX requests.
function loadData(){
var xmlhttp;
var mID=ddItems;
var method=2;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ddItems").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method, true);
xmlhttp.send();
}
I have made 2 desired changes to your code, try running it now. Make sure the URL is correct.
function loadData()
{
var mID=ddItems;
var method=2;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else //For some versions of IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) **//conditin is false,**
{
document.getElementById("ddItems").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../code/GetItemsInDD.class.php?id=" + mID + "&method=" + method, true); **// is this statement correct**
xmlhttp.send();
}
}
Change 1 : You may be running the code in an older version of IE, where ActiveXObject is used.
Change 2 : The open() method should not be called if the readyState changes ( as you have written it within the IF block), readyState changes only after the ajax call is initialized by the open() method and then send by the send() method.

Display Multiple Records From SQL Query Using AJAX with Timer

I'm trying to find a good example on how to retrieve records using PHP from a table and refresh it say every 2 minutes using Ajax.
Anyone can point me to that tutorial?
I don't think you'll find a tutorial that specific, but you just need to learn AJAX and then make the AJAX call every two minutes using JavaScript's setInterval method.
EDIT
Meh, I'm bored enough to write this example. This isn't tested, but I don't think it has errors.
<html>
<head>
<script type="text/JavaScript">
window.onload = function()
{
// call your AJAX function every 2 minutes (120000 milliseconds)
setInterval("getRecords()", 120000);
};
function getRecords()
{
// create the AJAX variable
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// set up the response function
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
/*
Your code goes here. 'xmlhttp.responseText' has the output from getRecords.php
*/
document.getElementById("txaRecords").innerHTML = xmlhttp.responseText;
}
}
// make the AJAX call
xmlhttp.open("GET", "getRecords.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<textarea id="txaRecords"></textArea>
</body>
</html>
This is a bit of code that I wrote for this exact purpose. Adapt as appropriate.
AJAX code:
function timer()
{
var t=setTimeout("check()",2000);
// At an appropriate interval
}
function check(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText!=""){
var output = xmlhttp.responseText;
// Do what you need to do with this variable
}
}
}
xmlhttp.open("GET","backend.php",true);
// Set file name as appropriate.
xmlhttp.send();
timer();
}
PHP code:
<?php
// This assumes you have already done mysql_connect() somewhere.
// Replace as appropriate
$query = "SELECT * FROM table_name";
// Perform the query
$result = mysql_query($query);
// Get the results in an array
while($row = mysql_fetch_array( $result )) {
// Echo the message in an appropriate format.
echo "<br />" . $row['column_name'];
}
?>
Remember to initiate one of the JS functions as you load the page:
<body onload="timer()">

Categories