JavaScript function not responsive - php

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

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.

Check for username while typing in field?

I am fluent with HTML, and mostly PHP.
I can do the scanning part with PHP.. I'm just not sure how to call a function in PHP with JavaScript, because I don't know JavaScript.
My PHP code will connect to my MySQL database and see if the text currently in the textbox (Not clicked enter yet, still typing) is in the database..
Do you know how to do this, or at least know a link that tells you how to do it?
This sounds like a problem for jQuery. I'd give you a long-winded example, but there are many people that would give you a much better one: like this guy.
Consider using jQuery in conjunction with jQuery UI, specifically something called autocomplete. I'm fairly certain it does what you're wanting, and it's completely themable for your site.
I see everybody likes jQuery so much, wow!
I'd tell you just need some very basic Ajax script to call your PHP script and receive the response.
Here's the simple Javascript function (actually two):
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(scriptAddressWithParams, callback) {
if (xmlhttp) {
xmlhttp.open("POST", scriptAddressWithParams, 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 here's an example of usage:
<input type="text" onchange="doRequest('myphpscript.php?checkvalue='+this.value, function (returnedText) { alert(returnedText);});"/>

Adding ajax loading gif to script

Thanks for looking, I have the below script that updates a series of drop down boxes, populated depending on the users previous answer. Data comes from SQL tables. I was wondering how I could add an Ajax loading gif to each drop down while the data is loading. I hope this makes sense, if not please ask.
<script language="javascript">
var xmlhttp
function selectmanu()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support XMLHTTP!");
return;
}
document.form1.mtype.style.background = "#FFFFFF"
var id=document.form1.mtype.value;
var url="selectmanu.php";
url=url+"?id="+id;
/*url=url+"&sid="+Math.random();*/
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("abc").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function selectmodel()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support XMLHTTP!");
return;
}
document.form1.manu.style.background = "#FFFFFF"
var id=document.form1.manu.value;
var url="selectmodel.php";
url=url+"?id="+id;
xmlhttp.onreadystatechange=stateChanged1;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged1()
{
if (xmlhttp.readyState==4)
{
document.getElementById("modspan").innerHTML=xmlhttp.responseText;
}
}
function validate()
{
if(document.form1.mtype.value=='0')
{
document.form1.mtype.style.background = "#FF0000"
return false;
}
else if(document.form1.manu.value=='0')
{
document.form1.manu.style.background = "#FF0000"
return false;
}
else if(document.form1.model.value=='0')
{
document.form1.model.style.background = "#FF0000"
return false;
}
return true;
}
function mset()
{
if(document.form1.model.value!='0')
{
document.form1.model.style.background = "#FFFFFF"
}
}
</script>
Cheers,
B.
Instead of images, you could disable the "select" and put a single "option" with a loading message. You do that before the XHR call.
<select disabled="">
<option>Loading...</option>
</select>
Once you get your data, replace this "option" by the real ones, and remove the attribute "disabled".
Visually it is ok, and users do not have anything to guess.
I think you can have images in select options, but I'm too sure. Don't quote me on that.
Nevertheless, it should just be a case of having an onChange JavaScript function that replaces the next select element with a loading image whilst querying the database for your options. When the options have been retrieved by AJAX, replace the loading image with a select field, and loop through your AJAX response and add an option tag for each option you retrieved from the database.
As mentioned above, libraries like jQuery make writing functions like this easier, but for that you do need a good knowledge of writing JavaScript from scratch.

ajax php variables in javascript

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.

Categories