Ajax / PHP updating DIV - php

I'm using the following to update a DIV called 'output'. This works fine with one exception, I would like echo entries to update the parent page.
<script type="text/javascript">
<!--
var divid = 'output';
var loadingmessage = '<img src="working.gif">';
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function formget(f, url) {
var poststr = getFormValues(f);
postData(url, poststr);
}
function postData(url, parameters){
var xmlHttp = AJAX();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState > 0 && xmlHttp.readyState < 4){
document.getElementById(divid).innerHTML=loadingmessage;
}
if (xmlHttp.readyState == 4) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(parameters);
}
function getFormValues(fobj)
{
var str = "";
var valueArr = null;
var val = "";
var cmd = "";
for(var i = 0;i < fobj.elements.length;i++)
{
switch(fobj.elements[i].type)
{
case "select-one":
str += fobj.elements[i].name +
"=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&amp;";
break;
}
}
str = str.substr(0,(str.length - 1));
return str;
}
//--></script>
This is called using :
<input type='button' name='Send' value='submit' onclick="javascript: formget(this.form, 'foo.php');">
The issue I have is foo.php runs a series of exec() commands, between each command is an echo statement that I would like to be displayed in the output div.
So it will do something like:
echo "archive files";
exec ("tar -cvf bar.tar bar.txt foo.txt");
echo "backing up /user";
exec ("tar -cvf /user.tar /user/*");
I would like the user to see the working.gif, but under it each echo statement from foo.php
Can that be done and how ?
Thanks

I can't say I've ever tried sending back chunks of data at separate times with a single AJAX request, so I'm not sure it's possible. What happens currently? Do you only get first echoed message, or do only get the entire response at the end?
Two things that I know will work:
Break your PHP script into multiple scripts and execute them in order with separate AJAX requests. This will only work if the separated scripts don't depend on each other or you find some other way to persist the state across the separated scripts.
Create an iframe and load the PHP script into it instead of using an AJAX request. Flushing the output of the PHP script should then work. (If you have ever used Wordpress, I believe they use this technique to show the progress of plugin updates.)

Related

Loading html and php page in div

How can I load html in a div when I click a button?
I have function but it does not work:
function ajaxFunction(id, url){
document.getElementById("sh").style.visibility = 'hidden';
var xmlHttp;
try {// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4) {
//Get the response from the server and extract the section that comes in the body section of the second html page avoid inserting the header part of the second page in your first page's element
var respText = xmlHttp.responseText.split('<body>');
elem.innerHTML = respText[1].split('</body>')[0];
}
}
var elem = document.getElementById(id);
if (!elem) {
alert('The element with the passed ID doesn\'t exists in your page');
return;
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
And I have button to click it.
<button type="button" name="new metere" value="" class="button" onclick="ajaxFunction('test','newmetere.html');">new metere</button>
when I put newmetere.php Function does not work and get garbage value.
Try jQuery's load () : it's a fast and simple way to load content from another page asynchronously in a web page using Ajax!

Open PHP file using AJAX

i am trying to execute a PHP file using AJAX, which is supposed to update a txt file
here is my javascript
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
var host = window.location.hostname;
var dir1=window.location.pathname.split("/")[1];
var dir2=window.location.pathname.split("/")[2];
var p = document.getElementById(\'CTI_IP\').value;
var url=\'http://\'+host+\'/\'+dir1+\'/modules/company/include/file.php?var=\'+p;
xmlHttp.open("POST",url,true);
if (xmlHttp.readyState==4)
{
xmlHttp.send();
}
}
the url is fine, i alerted it, copy pasted the link, the php file is working perfect and updating the txt file but it won't work in ajax? why
thanks !!
You have a syntax error:
var p = document.getElementById(\'CTI_IP\').value;
^HERE
(And similar ones scattered throughout).
This should have shown up in your browser's JavaScript error console.
When you build the URL, you are building it wrong. You are escaping quotes that don't need escaping. It should be built as follows:
var url = "http://" + host + "/" + dir1 + "/modules/company/include/file.php?var=" + p;
You are also escaping the quotes on your getElementById call for some unknown reason. It should be called as follows:
var p = document.getElementById("CTI_IP").value;
The only time you want to escape quotes is when you want them included in your string. In these instances, you shouldn't have escaped them because they denote a string - they aren't meant to be included.
I recommend that you research a little bit about how strings work in Javascript.
Once you've fixed those errors, remove the if block around your xmlHttp.send().
You have:
if (xmlHttp.readyState==4)
{
xmlHttp.send();
}
But should only have
xmlHttp.send();
Finally, since you don't include it in your example above, I'm assuming you aren't actually making a call to your MakeRequest() function anywhere. You have to call that function somewhere in your code to get it to actually execute the function.
Simply invoke the function as follows:
MakeRequest();

AJAX and php POST problems

I am trying to pass to a PHP file cellnumber. My AJAX isn't even working, when I try
alert("test"); in the ajax.onreadystatefunction() it won't print.
My javascript getrow(t) function gets called every time someone clicks on a cell in a table
and the result is the cell turning into green. I want to ultimately enter this data into a postgres table using php.
Thanks for all the help!
Vlad
<script type="text/javascript">
//gets the row and column number
function getRow(t)
{
var col=t.cellIndex;
var row=t.parentNode.rowIndex;
var testTable = document.getElementById("testTable");
t.style.backgroundColor = "#33CC66";
var cellnumber = (row*15 + col);
var ajax = new XMLHttpRequest();
//use ajax to enter into visitedCells
ajax.onreadystatechange = function()
{
// Call a function when the state changes.
if(ajax.readyState == 4 && ajax.status == 200)
{
ajax.open("POST", insertCoordinates.php, true);
ajax.send(cellnumber);
}
else
{
alert("Error:" + ajax.status + "and " + ajax.statusText);
}
}
}
</script>
</body>
</html>
ajax.open("POST", insertCoordinates.php, true);
ajax.send(cellnumber);
should be outside ajax.onreadystatechange
just befor }//getRow
you actually don't have the request executed
should be like that:
var ajax = new XMLHttpRequest();
//use ajax to enter into visitedCells
ajax.onreadystatechange = function() {//Call a function when the state changes.
if(ajax.readyState == 4 && ajax.status == 200) {
alert('success');
} else {
alert("Error:" + ajax.status + "and " + ajax.statusText);
}
}//onreadyState
ajax.open("POST", insertCoordinates.php, true);
ajax.send(cellnumber);
probably won't work in IE
should use a construction like that:
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
but the best way is to use jQuery ...easy and safe

while retreving the data using ajax getting an error message

I posting my value through ajax and using the response the details will be displayed.I am getting the problem while retreiving the data.But i dono where i have mistaked,then this is the error getiing displayed frequently
"There was a problem while using XMLHTTP:\n";
in all browsers mainly in the chrome,could any one help me...
this is my code,
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer 6+
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// Internet Eplorer 5
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX. Download a newer browser to view this page.");
return false;
}
}
}
// insert server response into HTML element
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
MM_check_session(xmlHttp.responseText);
var b_gc = document.getElementById(insert).value;
document.getElementById(insert).value = xmlHttp.responseText;
var shippingid = getCheckedValue('checkout_form', 'shippingid');
closeMessage();
MM_calc_shipping(shippingid);
if (b_gc == xmlHttp.responseText) {
MM_register();
} else {
error = 1;
document.getElementById('payment_error').innerHTML = xmlHttp.responseText;
document.getElementById(insert).value = '';
}
} else {
closeMessage();
alert("We can't process your request.Please refresh(reload) the page to proceed further:\n"
+ xmlHttp.statusText);
}
}
}
displayStaticMessage(
'<img src=' + config_MM_loader_image_path + ' alt=\'loading...Please wait\'>',
false);
xmlHttp.open("POST", serverScript, true);
xmlHttp.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xmlHttp.setRequestHeader('Content-length', parameters.length);
xmlHttp.setRequestHeader('Connection', 'close');
xmlHttp.send(parameters);
any help
You seem to be incorrectly tagged as php. Also have you considered jQuery for the ease of ajax whilst using it.
as for your question could you post the code on the page where the ajax request is going to as the code here looks fine..
Edit:
Where is serverScript set?
change serverScript for the ajax page you are calling?
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849%28v=vs.85%29.aspx

changing values of array elements in javascript functions

These are my three functions that I am using in javascript :
function postRequest()
{
var xmlHttp;
if(window.XMLHttpRequest)
{ // For Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{ // For Internet Explorer
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('GET', 'effort.php', true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
get_string(xmlHttp.responseText);
dij();
}
}
xmlHttp.send(null);
}
function get_string(str)
{
get_integer = str.split(" ");
for(var i=0;i<214;i++)
{
vertex_i[j] = get_integer[i]*1;
j++;
}
j=0;
for(var i=214;i<427;i++)
{
vertex_f[j] = get_integer[i]*1;
j++;
}
j=0;;
for(var i=427;i<517;i++)
{
x[j] = get_integer[i]*1;
j++;
}
j=0;
for(var i=517;i<607;i++)
{
y[j] = get_integer[i]*1;
j++;
}
for(var m=0;m<90;m++)
{
for(var n=0;n<90;n++)
{
L[m][n] = -1;
}
}
for(var m=0;m<212;m++)
{
x1 = x[vertex_i[m]];
x2 = x[vertex_f[m]];
y1 = y[vertex_i[m]];
y2 = y[vertex_f[m]];
L[vertex_i[m]][vertex_f[m]] = parseInt(find_dist(x1,x2,y1,y2));
}
}
function point_it(event)
{
postRequest();
}
namely :
point_it(event),then postRequest(); and finally dij();
In these functions I use the data in three globally defined arrays,the elements of whose are derived from the data sent by the server(get_string function).
if I call dij() function from within the postRequest() function(after the get_string function I am able to access the correct data within the arrays.
However if I call it immediately after the postRequest() function the value of elements in the array become equal to null.
I am unable to understand the proper reason for this and have tried several ways to get through but with no progress.
CAn sm1 please help me out !
postRequest fires an asynchronous request to the server. Calling a function directly after it doesnt mean that the request has finished and youve doen anything with the response data. It works inside postRequest because that where you actually handle processing the request and response.
if you want to do this all from within point it i would recommend doing the following:
function postRequest(callback)
{
var callbackFunc = callback||null;
var xmlHttp;
if(window.XMLHttpRequest)
{ // For Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{ // For Internet Explorer
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('GET', 'effort.php', true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
get_string(xmlHttp.responseText);
if(callbackFunc){
callbackFunc();
}
}
}
xmlHttp.send(null);
}
function point_it(event)
{
postRequest(dij);
}
this allows you to vary the callback that uses the array thats been populated by the post request and in a away that it always fires after that request cycle is complete.
XMLHttpRequest is asynchronous.
That means, it will return as soon as the request was send. If you now call dij() the request will still be pending and get_string wasn't called yet.
As soon as the requests completes, the callback will be called, and then execute get_string.
You need to leave dij() inside the callback too.
Visually:
postRequest is made, sets the callback, but does not execute it, postRequest then returns
the code after the call to postRequest executes
some time passes...
the XMLHttpRequest finally completes and the callback executes, which now calls get_string
Global variables are not a good practice. It is better to combine your get_string and dij functions into one with your arrays as local variables inside the single function.

Categories