ajax php variables in javascript - php

I have the below code, which was previously working fine:
var xmlHttp
var layername
var url
function update(layer, url) {
var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere
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";
}
//etc
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function updateByPk(layer, pk) {
url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random();
update(layer, url);
}
function updateByQuery(layer, query) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
update(layer, url);
}
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");
var phpstring = <?php $out = htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); echo("'$out'"); ?>;
child1.document.write(phpstring);
//child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
child1.document.close();
}
The part that is commeneted out was working fine in a previus version, in that javascript was replacing row2['ARTICLE_DESC'], a php variable with the contents of the variable. This javascript file is included from a script tag in a php file, and always worked fine. I have changed something recently however, I am not sure what the specific thing was, butnow I get these errors, from firebug:
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write("<br />
<b>Notice</b>: Undefined variable: row2 in <b>C:\Programme\EasyPHP 2.0b1\www\records4\fetchlayers.js</b> on line <b>57</b><br />
null");
child1.document.close();
}
unterminated string literal on line 57 and the updateByQuery is not defined.
I have no idea why I get either of those errors, and why updateByPk does not throw an error. I am even more confused as to what article_Desc is being expanded to and how. This happens on the index.php, which has a link to call updateByQuery, which would load a section via ajax which would have a link to updateByPk, which would display the final section, which would have a link to makewindows(), where article_Desc would relate to the relevant $pk
This was all working fine, and I can not find out why it no longer is.
would it help if I were to paste the php files somewhere?
edit.
i do not understand why this is happening, but have tried to modified the function so it takes a paramter.
function makewindows(html){
child1 = window.open ("about:blank");
child1.document.write(html);
child1.document.close();
}
in conjunction with thse two snippets of php
$html = json_encode(htmlspecialchars($row2['ARTICLE_DESC']));
and
<a href='#' onclick='makewindows(/"".$html."/"); return false;'>Click for full description </a></p>

Everything indicates the problem is in your PHP file. The notice you are getting is from PHP and not from JavaScript as you may be assuming.
<b>Notice</b>: Undefined variable: row2 in <b>C:\Programme\EasyPHP 2.0b1\www\records4\fetchlayers.js</b> on line <b>57</b><br />
null");
So the problem is in here:
<?php $out = htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); echo("'$out'"); ?>;
The $row2 array is not defined, so $row2['ARTICLE_DESC'] doesn't exist. You should verify from where it should come from because I couldn't find it in the code you provided.

Related

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();

php variable to javascript via ajax

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.

ajax with JavaScript exception: unexpected end of input

I have an input field for a concept and when the user fills it out, he has to then check if the concept exists. So I made a check button, which checks a database using ajax and JavaScript to see if the concept exists. My problem is when using ajax and JavaScript I get this exception:
unexpected end of input
JS :
var concept = document.getElementById('acConceptName').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var isexisted = JSON.parse(xmlhttp.responseText);
if(isexisted[0]==true){
var errorMessage = document.getElementById('acSuggesConcepts');
var p = document.createElement('p');
p.innerHTML="this concept is already existed";
errorMessage.appendChild(p);
errorMessage.style.display="block";
}
}
}
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/isExistedConcept/"+concept+"/TRUE",true);
xmlhttp.send();
What is the exception and how can I solve it ?
PHP : function to check database and I always return true in it
public function isExistedConcept($concpetName,$Ajax){
if($Ajax==true){
$results=true
$d=array($results);
return json_encode($d);
}
}
Demo: http://jsfiddle.net/Wiliam_Kinaan/s7Srx/2/
After looking at the code for a while, one thing that might be a suspect is your PHP.
Your function in php ends with a return command. What the AJAX call is actually waiting for is some data to be sent back. The return command simply passes that value back to the entity that originally called the function.
Try alter your function to echo the result as opposed to returning it. Save your return value for when you need the result to go into another PHP function, not when you are returning data to the client.
I only put this return command here for readability.
public function isExistedConcept($concpetName,$Ajax){
if($Ajax==true){
$results=true
$d=array($results);
echo json_encode($d);
}
return;
}
Try this:
public function isExistedConcept($concpetName,$Ajax) {
if( $Ajax) return "1";
}
// This is a simplified version of what you're doing, but it returns "1" instead of "[true]"
// Now for the JS:
if( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var isexisted = xmlhttp.responseText == "1";
if( isexisted) {...}
If that doesn't work, try adding alert(xmlhttp.responseText) and see if you're getting anything other than what should be there.
try this :
var concept = document.getElementById('acConceptName').value;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/isExistedConcept/"+concept+"/TRUE",true);
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
var isexisted = JSON.parse(xmlhttp.responseText);
if(isexisted[0]==true){
var errorMessage = document.getElementById('acSuggesConcepts');
var p = document.createElement('p');
p.innerHTML="this concept is already existed";
errorMessage.appendChild(p);
errorMessage.style.display="block";
}
else{
console.log('error');
}
}
}
}
xmlhttp.send(null);

AJAX post method: Variables are not passed to target php

I am trying to send two pieces of info to a php.
1-) tent = zuzu
2-) zart = gagi
target php simply echoes what I send so that I can check if it's working. This is the javascript:
function boka ()
{
var mesparam = "tent=zuzu&zart=gagi";
if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}
else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) {document.getElementById("response").innerHTML=xmlhttp.responseText;} }
xmlhttp.open("POST","/mysite/oxifa/oxifat.php?tent=zuzu&zart=gagi",true);
//xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-length", mesparam.length);
//xmlHttp.setRequestHeader("Connection", "close");
xmlhttp.send(mesparam);
}
This is oxifat.php that recieves the request:
<?php
echo " sign1 <br>";
echo next($_POST);
echo next($_POST);
echo next($_POST);
echo next($_POST);
echo next($_POST);
echo $_POST['tent'];
echo $_POST['zart'];
echo $_REQUEST['tent'];
echo $_REQUEST['zart'];
echo "<br> sign2";
?>
As you can see I've included all sorts of things to echo out whatever is in $_POST but apparently there is nothing there and this is the response I get:
sign1
Notice: Undefined index: tent in C:\wamp\www\mysite\oxifa/oxifat.php on line 16
Notice: Undefined index: zart in C:\wamp\www\mysite\oxifa/oxifat.php on line 17
Notice: Undefined index: tent in C:\wamp\www\mysite\oxifa/oxifat.php on line 18
Notice: Undefined index: zart in C:\wamp\www\mysite\oxifa/oxifat.php on line 19
sign2
three lines about the "setRequestHeader" are in comment status. If I include them, I don't even get sign1. No response. What I figure out from this is everything is OK but I don't seem to understand how to use the post method to pass data to php. How do I do this? I have read everything on the net. I only do not know what "setRequestHeader" is for. One more thing: If I put ?tent=zuzu&zart=gagi at the end of target URL, $_REQUEST thing works. But that's GET and not what I'm trying to do. What is the $_POST's deal?
Could you please try to invoke following code
function getXMLObject() {
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
return xmlHttp;// Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject();//xmlhttp holds the ajax object
//use this method for asynchronous communication
function doRequest(params, callback) {
if (xmlhttp) {
xmlhttp.open("POST", "your_script.php?" + params, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
else {
alert("Error retrieving information (status = " + xmlhttp.status + ")\n" + response);
}
}
};
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
and in your PHP script first thing off write
print_r($_POST);
You are passing in the parameters with the URL which is for GET, not the right way for POST.
See: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Try taking the parameters off in the request here:
xmlhttp.open("POST","/mysite/oxifa/oxifat.php?tent=zuzu&zart=gagi",true);
And then uncommenting these:
//xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-length", mesparam.length);
//xmlHttp.setRequestHeader("Connection", "close");
You need to uncomment those 2 lines, otherwise you the php $_POST is not going to pick it up. also, as stonemonkey77 answered, you are also passing the parameters in the get url.
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", mesparam.length);

JavaScript function not responsive

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"]); ?>);

Categories