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();
Related
Ok im tring to get PHP variable to javascript variable via ajax.
i have some piece of php code to make this variable it look like this: (i wont put entire code because its working so only relevant code for this topic. i have new_m variable which is ARRAY and i want to pass it)
shuffle($new_m);
echo json_encode($new_m);
then i have js file which should catch that echo and it look like this:
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();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
var myvar = new Array();
var myvar=JSON.parse(xmlHttp.responseText);
return myvar;
}
}
xmlHttp.open("GET", "showimage.php", true);
xmlHttp.send(null);
}
When this code is not on separate page like here and when is myvar is used inside function it works (because i have used this code on another page successfully). So i think my problem is not returning correct variable or not returning it on correct way.
and final piece of code is part where this myvar should be used it looks like:
<script type="text/javascript" src="js/shuffle.js"></script>
<title>undf</title>
</head>
<body onload="MakeRequest()">
<script type="text/javascript">
alert(myvar);
var pos = 0;
var imgs = myvar;
</script>
and nothing happens. im still new at this ajax and javascript. thanks for you help in advance.
Your problem is that when alert( myvar); is executed, the request to the server hasn't happened yet, and the variable is undefined (not to mention that I believe the variable is out of scope, so you can't access it).
You should set up the JS so that when the window loads, you execute the request to retrieve the data and then read it:
<script type="text/javascript">
window.onload = function() {
var myvar = MakeRequest();
alert( myvar);
}
</script>
You can then get rid of the onload within the <body> tag.
Note that I'm not entirely sure that you're returning the value from the MakeRequest() function correctly, since the return is within the xmlhttp callback and not in the function. You should investigate this and verify.
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 + "&";
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.)
I have two divisions, <div id=statuslist></div><div id=customerlist></div>
The function sendReq() creates a xmlhttprequest and fetches the data into the division.
sendReq('statuslist','./include/util.php?do=getstatuslist','NULL');
sendReq('customerlist','emphome.php?do=getcustomerlist','NULL');
I have a problem,
The data fetched into the 'customerlist' gets copied onto 'statuslist'
If i change the order of function calls,
sendReq('customerlist','emphome.php?do=getcustomerlist','NULL');
sendReq('statuslist','./include/util.php?do=getstatuslist','NULL');
Now the data of 'statuslist' gets into 'customerlist'..
Whats the problem with the code?
That's also my problem right now. After a thorough research, I've found out that:
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task
- W3Schools.com
Also, thanks to Two xmlHttpRequests in a single page which redirects me to this question Using two xmlhttprequest calls on a page, I was able to solve the problem. By the way, it is a modification of Addsy's answer.
First, create a ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task. Example:
function sendReq(url, callbackFunction)
{
var xmlhttp
if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status=='200')
{
if (callbackFunction) callbackFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
Second, call the function and pass the necessary parameters. For example:
sendReq("orders_code_get.php?currentquery="+sql, function processResponse( response )
{
document.getElementById("orders_content").innerHTML="";
document.getElementById("orders_content").innerHTML=response;
});
I have proven and tested this code and it works.
I have had this before.
Basically you have a scope problem - you have something like this in your sendReq() function?
if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
And so when you make a second request, the xmlhttp object is over-ridden
You need to create a closure where your xmlhttp objects don't clash
eg
function sendReq(url, callbackFunction)
{
var xmlhttp
if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
... probably some other stuff here, setting url etc ...
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4&&xmlhttp.status='200')
{
if (callbackFunction) callbackFunction(xmlhttp.responseText);
}
}
.. probably more stuff here ( including xmlhttp.send() ) !! ...
}
you can then pass the callback function as a parameter and when the data is successfully loaded, it will be passed to the callback function. Note that you will need to pass the actual function, not just its name (so no quotes around the function name)
Alternatively, you could do what i do which is just use jQuery - works for most of my js problems ;)
Hope this helps
In fact it is possible to run multiple async xhr call but you have to give them an unique id as parameter to be able to store and load them locally in your DOM.
For example, you'd like to loop on an array and make a ajax call for each object. It's a little bit tricky but this code works for me.
var xhrarray={};
for (var j=0; j<itemsvals.length; j++){
var labelval=itemsvals[j];
// call ajax list if present.
if(typeof labelval.mkdajaxlink != 'undefined'){
var divlabelvalue = '<div id="' + labelval.mkdid + '_' + item.mkdcck + '" class="mkditemvalue col-xs-12 ' + labelval.mkdclass + '"><div class="mkdlabel">' + labelval.mkdlabel + ' :</div><div id="'+ j +'_link_'+ labelval.mkdid +'" class="mkdvalue">'+labelval.mkdvalue+'</div></div>';
mkdwrapper.find('#' + item.mkdcck + ' .mkdinstadivbody').append(divlabelvalue);
xhrarray['xhr_'+item.mkdcck] = new XMLHttpRequest();
xhrarray['xhr_'+item.mkdcck].uniqueid=''+ j +'_link_'+ labelval.mkdid +'';
console.log(xhrarray['xhr_'+item.mkdcck].uniqueid);
xhrarray['xhr_'+item.mkdcck].open('POST', labelval.mkdajaxlink);
xhrarray['xhr_'+item.mkdcck].send();
console.log('data sent');
xhrarray['xhr_'+item.mkdcck].onreadystatechange=function() {
if (this.readyState == 4) {
console.log(''+this.uniqueid);
document.getElementById(''+this.uniqueid).innerHTML = this.responseText;
}
};
}
}
You have to set each xhr object in a global variable object and define a value xhrarray['xhr_'+item.mkdcck].uniqueid
to get its unique id and load its result where you want.
Hope that will help you in the future.
Lets say I have an array of javascript objects, and I am trying to pass those objects to a php page to save them into a database. I have no problems passing a variable to the php and using $_POST["entries"] on that variable but I can't figure out how to pass an entire array of objects, so I can access my objects.entryId and .mediaType values on the php page.
Oh and before anyone asks, yes the reason I need to do it this way is because I have a flash uploader, that you guessed it.. uploads into a CDN server (remote) and the remote server only replies back with such js objects.
Thanks for any help anyone can provide.
Here is my JS functions:
function test() {
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
var parameterString;
for(var i = 0; i < entries.length; i++) {
parameterString += (i > 0 ? "&" : "")
+ "test" + "="
+ encodeURI(entries[i].entryId);
}
xmlhttp.open("POST","ajax_entries.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameterString.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = handleServerResponseTest;
xmlhttp.send(parameterString);
}
function handleServerResponseTest() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
maybe you need to take a look at json and jQuery ajax methods:
.- http://blog.reindel.com/2007/10/02/parse-json-with-jquery-and-javascript/
.- http://us.php.net/json_decode
The turorial is maybe a little outdated because jQuery last version is 1.3.x but you will get an idea on that and about the PHP json functions... if your server does not have the json extension enabled you can use some php classes:
.- http://google.com.co/search?rlz=1C1GPEA_enVE314VE314&sourceid=chrome&ie=UTF-8&q=php+json+class
good luck!
I too had the same trouble. But googling dint help.
I tried myself to tweak and test. And I got it. I am using POST method though. Please try the idea with GET method. Here is the idea:
Append the array index value within square brackets to the Post/Get variable name for array. Do this for each array element.
The part var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2; of the following script would give you a hint.
This is the test JS, I used (Again this uses POST method not GET):
var xmlAJAXObject;
function test() {
xmlAJAXObject=GetxmlAJAXObject();
if (xmlAJAXObject==null) {
alert ("Oops!! Browser does not support HTTP Request.");
return false;
}
var namevalue1=encodeURIComponent("Element 1");
var namevalue2=encodeURIComponent("Element 1");
var parameters="&Name[0]="+namevalue1+"&Name[1]="+namevalue2;
xmlAJAXObject.open("POST", "test.php", true);
xmlAJAXObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlAJAXObject.setRequestHeader("Content-length", parameters.length);
xmlAJAXObject.onreadystatechange=stateChanged;
xmlAJAXObject.send(parameters);
}
function stateChanged() {
if (xmlAJAXObject.readyState ==4) {
if (xmlAJAXObject.status == 200) {
alert('Good Request is back');
document.getElementById("show").innerHTML=xmlAJAXObject.responseText;
}
}
}
function GetxmlAJAXObject() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject) {
// code for IE6, IE5
return new ActiveXObject("Microsoft.Microsoft.XMLHTTP");
}
return null;
}
This worked for me. Sorry for the formatting and incomplete code. I meant to give a direction. Google reault websites couldn't give a solution. Hope you find this useful.
I have the following code, which is the core part of my small AJAX application. I am not getting any errors, it is just that nothing happens. I am guessing there is a more efficient way to do what I am trying to do.
Here is the code:
var xmlHttp
var layername
function update(layer, part, pk, query)
{
if (part=="1")
{
$url "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random()
}
else if (part=="2")
{
var url "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random()
}
xmlHttp=GetXmlHttpObject()
if(xmlHttp==null)
{
alert("Your browser is not supported?")
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading"
}
};
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return xmlHttp;
}
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write(json_encode(<?php echo $row2["ARTICLE_DESC"]; ?>));
child1.document.close();
}
and an example of how I am calling the function from php
onclick="update(\'Layer3\',\'2\','.$pk.'\',\'0\',)">'
pk or query will never be passed at the same time, only one of them will ever be passed.
edit: I am also wondering if it would make more sense for the makewindows function to take a parameter, or stay as it is. Are there advantages and disadvantages for each approach?
Looks like you may have some javascript errors:
if (part=="1")
{
$url "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random()
}
else if (part=="2")
{
var url "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random()
}
Use Firefox and Open the javascript console to get the javascript errors, then try to fix the lines it complains about.
Javascript will stop running as soon as it encounters an error.
Also, checkout firebug if you haven't already. Great tool!
I'd check the HTML the PHP is generating. Assuming $pk is a string it looks like you're missing an opening quote. Try this:
onclick="update(\'Layer3\',\'2\',\''.$pk.'\',\'0\',)">
json_encode is a PHP function, and thus you need to modify that particular line like so:
child1.document.write(<?php echo json_encode($row2["ARTICLE_DESC"]); ?>);