about using ajax - php

I'm displaying the cotntent of a text file on web page(say between <div id='text'></text>)
this file's content is edited by any user who view the page, I already use ajax to write to the file and display to the current user, but if there are any users browsing the page at the same moment they have to refreh the page to see the new edited content.
I want to know how to use ajax to make the part that contain the file content remain updated continmuosly without refreshing the page
<script type='text/javascript'>
function change(){
if (window.XMLHttpRequest) xhr=new XMLHttpRequest();
else xhr=new ActiveXObject("Microsoft.XMLHTTP"); //IE5
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
if(xhr.responseText=="empty") return;
document.getElementById("space").innerHTML=xhr.responseText;
}
}
var str=document.getElementById('msg').value;
document.getElementById("msg").value="";
xhr.open("GET","response.php?q="+str,true);
xhr.send();
}
</script>
<center>
<div id='space'>nothing</div>
<input type='text' name='msg' id='msg'>
<input type='button' onClick='change()' value='Click'>
</center>

The simplest way to accomplish the "server push" effect is through polling.
In your case, you can add this functionality by adding a simple Javascript statement:
window.onload = function()
{
setInterval("change();", 5000);
};
This code will call change(); every 5000 ms.

You could use setInterval() to perform a periodic AJAX query to check for updates. Then, if needed,update the content on the page.

Related

how to reload a div on a button click using Jquery or Javascript

I'am using Yii framework, I want to reload this div:
<div class="likes" id="likes">
<?php
echo $model->likes." ".CHtml::imageButton($src.'like.png', array('value'=>'like', 'width'=>'25px', 'height'=>'20px'));
?>
</div>
by using this ajax function that is written in a js file in the extensions folder:
$(document).ready(function(){
$("#like").click(function(){
$("#likes").html("result reloaded successfully");
});
});
but their is nothing happened when I clicked the button, can you help me?
this may help someone
$("#reload").click(function(){
$("#like").load(location.href + " #like>*", "");
});
without page refreshing refresh particular div or any tag
Create a new file called reload_likes.php with the following code:
<?php
echo $model->likes." ".CHtml::imageButton($src.'like.png', array('value'=>'like', 'width'=>'25px', 'height'=>'20px'));
?>
then on your javascript file put:
function FreloadDiv(){
var request = new XMLHttpRequest();
request.open('GET', 'http://yourdomain.com/reload_likes.php', false);
request.send(null);
if (request.status === 200) {
document.getElementById('likes').innerHTML = request.responseText;
}
}
Finally add onClick='FreloadDiv();' to your button
because you call by the wrong way I think. your id is likes and you are writing like instead of likes. Check it first after that I will check next coming error..

PHP load data in modal

I need to load data from a database table using an ID that is sent to a modal window.
Basically, when the grid loads, there are multiple columns. Two in particular are called CONTAINER_ID and WORKFLOW.
Whatever is returned for WORKFLOW will be a link that opens up a MODAL popup called #mySVCModal. Here is the sample code:
while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE)
{
echo "<tr";
echo "<td style=\"width: 50px;\">{$Row[CONTAINER_ID]}</td>";
echo "<td style=\"width: 50px;\"><a class=\"open-container\"
data-toggle=\"modal\" href="#mySVCModal\"
data-cont=\"{$Row[CONTAINER_ID]}\">{$Row[WORKFLOW]}</a></td>";
echo "</tr>";
}
When the user clicks on {$Row[WORKFLOW]}, a modal window opens up with the CONTAINER_ID from the same row.
Here is the javascript that makes that happen:
echo "<script type=\"text/javascript\">
$(document).on(\"click\", \".open-Container\", function() {
var myContainer = $(this).data('cont');
$(\".modal-body #containerID\").val( myContainer );
});
</script>";
At this point, the modal window is open, and I can display the CONTAINER_ID. Here is the code that displays the CONTAINER_ID:
<div id="mySVCModal">
<form action="" method="POST">
<input type="text" name="containerID" id="containerID" class="containerID" />
*** more code here ***
</form>
</div>
So no problem. The CONTAINER_ID is displayed in an INPUT field called "containerID".
What I need to make happen now is when the modal window opens, "containerID" is sent to a PHP variable that will retrieve the WORKFLOW information from a database table called WORKFLOW_TABLE.
When I try to convert containerID into a PHP variable and echo it out, nothing is displayed:
<?php
$containerID = $_POST['containerID'];
echo "this is containerID " . $containerID; // only displays the text, not the $containerID
?>
I know that once I can get the code directly above to display the containerID in an ECHO, I can run a query off of it.
So basically, what I need to do is when the modal window opens, PHP will take containerID and run a " SELECT * FROM WORKFLOW_TABLE where CONTAINER_ID = 'containerID' ";
The contents from WORKFLOW_TABLE should automatically be displayed in various INPUT fields. I'm just using INPUT fields for now. That's beside the point.
So all in all, I need the modal to open up with the contents from WORKFLOW_TABLE displayed using the containerID.
I hope I worded this clearly.
Please help.
Sounds like you need an AJAX query.
<script>
function loadData()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "db_query.php?containerID = " + document.getElementById('containerID').getAttribute('value'), true);
xmlhttp.send();
}
window.onload = loadData;
</script>
<div id="myDiv"></div>
Sorry in advance for any possible flaws, I didn't actually run this.
It looks like you're not actually submitting your form to the server when you're loading the modal.
Since you probably don't want to reload the entire page to display the modal, you should request the modal content on demand using an asynchronous request. Since your sample code uses jQuery, I've used the same here. (see the jQuery.load() documentation for more info)
echo "<script type=\"text/javascript\">
$(document).on(\"click\", \".open-Container\", function() {
var myContainer = $(this).data('cont');
$(\".modal-body #containerID\").val( myContainer );
$('.modal-body').load(
'yourPHPscript.php',
{ containerID: $('#containerID').val()}
);
});
</script>";
Then your PHP script should resemble this (notice the change from POST to GET):
<?php
$containerID = $_GET['containerID'];
echo "this is containerID " . $containerID;
?>

Getting trouble in saving data to a mysql using AJAX

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;

Change value of PHP variable with AJAX

The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it

How to send javascript variable to php using ajax?

The scenario is , below is the html file through which i want to display the content of a text file at div id="myDiv".
The file will be read by php . The php content is given below.
I am unable to get the content from the text file . Please tell me what should be added in the ajax part to correct the program.
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+tb,true);
xmlhttp.send();
}</script>
</head>
<body>
<div >
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest(myfile.txt)">Change Content</button>
</div>
</body>
</html>
Below is the PHP file
<?php
$tbName = $_GET['tb'];
$file = "/home/$tbName";
$f = fopen("$file", "r");
echo "<ul>";
while(!feof($f)) {
$a= fgets($f);
echo "<li>$a</li><hr/>";
}
echo "</ul>";
?>
Fix quotes
onclick="ajaxRequest('myfile.txt')"
make sure you use encodeURIComponent() on tb
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+encodeURIComponent(tb),true);
Test your php page in the browser: does http://localhost/TBR/getdata.php?tb=myfile.txt provide the data you want?
If so test the function gets called. (Place an alert or debug the code and place a breakpoint within the function, or use console.debug if your browser supports it)
If the function gets called then your event handler is working correctly, if not try to rewrite it or attach it differently like onclick="ajaxRequest('myfile.txt');" though I suspect the missing semicolon isn't the problem.
If that is called you can try to see if the ajax call is carried out my inspecting the network traffic. Any decent browser will let you do that (hit f12 and look for the network tab). You should be able to see the request and response if the ajax request is being issued and responded to.
Supposing that is all working fine, ensure that your event ajax event handler is getting called. I suspect there is an issue here because you are not setting the event handler to a function...
xmlhttp.onreadystatechange = function statechange()
{
if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
And failing all of that your data insert code isn't working.
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
Remember to quote the string in the onclick.
Here's a fixed version:
<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
if (window.XMLHttpRequest){
var xmlhttp= new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }
}
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+ encodeURIComponent(tb),true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="myDiv">Text from file should come here.</div>
<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
</body>
</html>
What was wrong:
the presence of XMLHttpRequest was tested, but the function was not wrapped in an if, making that useless.
The variable names were a little mismatched - double check that
EncodeURI Component, as mentioned below
The proper syntax for a callback function is window.onload = function(){ alert('func!'); } not window.onload = alert(){ alert('load!'); }
That should be it, unless there's a problem with the PHP Script, try testing that out by visiting the URL directly.

Categories