Ok, I know this has been asked before (as I have viewed it myself) and it seems to work for everyone else except for me. Im terribly new to javascript, as I try not to use it cause its a nightmare to debug. But, here is my issue. I have a script that im working on for ajax to add an image to a gallery. The image is just an id that references another table in the database, and same for the gallery. Just two id's. Anyways, when I click on a link, I want it to run this script to add it to the database. But, its not working, and of course, javascript is horrible at letting you know where it fails. Here is the code for the script.
function addToGallery(img)
{
var e = document.getElementById("galleries2");
var gal = e.options(e.selectedIndex).value;
window.alert("Gallery Id: "+gal+" Image Id: "+img);
if (img=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","addtogallery.php?img="+img+"gal="+gal,true);
xmlhttp.send();
}
Ok, so the above doesnt work. I added the alert message to try to troubleshoot as much as I could. If I put the alert box above the var's, and only ask it to reference the img variable, it works. Now, if I put it below and try to do what I did there, it just stops. No message box, no ajax, nothing. So, im betting it has something to do with the
var gal = e.options(e.selectedIndex).value;
I have also tried it with the [] instead of the () and nothing there either...
Any help would be appreciated.
UPDATE
Ok, so I have got past the problem with the select, now im trying to pass values with the xhtmlrequest.open method. I can pass 1 get value it seems, but not two. Here is the line of code in question
xmlhttp.open("GET","addtogallery.php?image="+img+"&gid="+gal,true);
Now, I know that img and gal are set because of an alert box that pops whenever this script is run to tell me that they are set. But when it gets to the php page its only putting out the img variable, and the gal variable is still not set. Anyone have this issue before?
You definitely need square brackets, but also try changing your variable "e" to something else like "el". The function responds to a click as I understand, so it might be reserved for an event.
Try:
var galleries = document.getElementById("galleries2");
var gal = galleries.options[galleries.selectedIndex].value;
I think what you want to do is:
var gal = e.options[e.selectedIndex].value;
Hope this helps.
You need square brackets instead of parens.
var gal = e.options[e.selectedIndex].value;
Your JavaScript environment should be giving you a nice TypeError saying something like "HTMLOptionsCollection is not a function"
Related
Apologies if this question is a bit vague, but I have no idea how to make it more specific. I am a beginner when it comes to javascript. I have a web page which sends a number of ajax calls to the server to call php scripts which runs some sql against a mysql database. Everything was working fine then all of a sudden I started to get an internal server error 500 on one of my ajax calls. The ajax call is placed in a function, it works most of the time. Only when I pass the function one specific sql query does it give the error. I've tested the query in my database manually and it works so its not an issue with the query that I am passing. The strange thing is, since the error has started, every now and then it does work, however most of the time it is not working, the error seems to be somewhat random. I realise that with limited information it may be impossible to give an exact answer, but has anyone experienced anything like this before? OR does anyone have any clues as to how I can get to the bottom of this. I've tried everything. I will paste the function that is causing the error (not sure if that will help at all). The error comes on the "xmlhttp.send();" line.
function phpRequest2(prov, phpsc, funct, bolL) {
<!-- document.getElementById("demo").innerHTML = qry; -->
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
document.getElementById("demo").innerHTML = prov;
xmlhttp.open("GET", phpsc + ".php?qry=" + prov, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var arrLocs = JSON.parse(xmlhttp.responseText);
funct(arrLocs, bolL);
}
}
}
You best bet at finding out the reason when you get the Error 500 is to edit your php.ini file and change the following parameters
display_errors = Off
display_startup_errors = Off
to
display_errors = On
display_startup_errors = On
Hopefully that should give you exact details on what your error is and thereby help you solve it.
So I have some code, which checks for whether a one time use discount code exists, and if so, it applies it and then marks it as used in the database. The problem is, it ends up being useable more than once if you spam click it, and then some time maybe 15-20 seconds later it stops being useable.
The relevant javascript component:
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
discountAmount += parseFloat(xmlhttp.responseText);
modifyCartOrder();
}
}
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
xmlhttp.send();
This is processed over in the php file, and when a match is found we echo that amount and then delete the entry
$mysqli->query("DELETE FROM discounts_available WHERE `index`=$index");
The php file is indeed doing what its supposed to. When you click apply code, it is immediately deleted from the database. The problem is, even with the code no longer in the db, you can still apply the code over and over for some amount of time before the js file finally realises there is no entry in the db. Why is this?
You should first check if it exists in DB then only you should proceed with request, it should be very first statement.
If it does not exists you can send response saying code already applied.
You most likely need to lock the table ASAP so no other instances can modify the table concurrently.
http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html
I did not get your problem, exactly I am assuming lost of things, so..
//this is triggered on some click, right?
//TODO:- check if button is disabled? you can have some js variable or check button attribute disbled
//TODO:-if its not disaled->{so first disable the button when it is clicked } else do nothing
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
discountAmount += parseFloat(xmlhttp.responseText);
// if succefull keep button disabled
// else renable it, so that it can be clicked again.
modifyCartOrder();
}
}
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
xmlhttp.send();
thers's no syntax problem here in your code its logical,
ajax call is asynchronous call, it does not happen in sequence
1) You clicked
2) Request Sent
3) Request Processed
4) JS is informed : your modifyCartOrder function executed
what I am trying to say here is that, there is no 3 immediately after 2, 3 will take time to start, js has no control over it, whenever php is done it will reply there's no guarantee. so you can repeat 1 again and again, and 2 will keep repeating... and so 3 will...
I hope I understood your problem, and you understood what I am trying to say :)
Problem is : You are sending asynchronous ajax calls from following code :
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
Solution : as defined , for opening an ajax call , method is :
xmlhttp.open(method,url,async)
So, You have to modify above line as:
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,false);
I'm trying to do a simple AJAX call to an ASP page, that resets session variables and posts a little message back on completion. I'm doing this purely to learn AJAX.
The example came from W3 Schools website but since applying it to my page, I can't seem to get it to work and it's not producing any errors, which is annoying, because I can't debug it.
This is my JS, which is called when a user hits a button [Clear Form]:
function resetSearchForm()
{
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("notification").innerHTML=xmlhttp.responseText;
document.getElementById('notification').style.visibility = 'visible';
}
}
xmlhttp.open("GET","clearSearchData.asp",true);
xmlhttp.send();
document.searchFrm.searchStr.value='';
document.searchFrm.vertical.checked = true;
document.searchFrm.horizontal.checked = true;
document.getElementById('dateRange').selectedIndex = 0;
document.searchFrm.searchStr.focus();
}
And this is the ASP (clearSearchData.asp) that clears my session variables and writes a message:
Response.Expires = -1
Session("search-str-boolean") = ""
Session("search-str-plain") = ""
Session("date-range") = ""
Session("date-from") = ""
Session("date-to") = ""
Session("specificDate") = ""
Session("peopleStr") = ""
Session("orientation") = ""
Response.Write "Form has been reset"
Can anybody see where I'm going wrong? I have been looking at it for a long time and I just can't see it.
The function itself works because the last part of the function gets processed, the bit that clears the form values... but... the AJAX call doesn't happen because the session variables still contain data and the message doesn't appear.
Many thanks in advance...
UPDATE - - - - - - - - - - -
It now works. The problem was I didn't include the full URL to the ASP page. Thanks for 'thedaian' (below) for pointing that out
Chances are, something is wrong with the page you're trying to get via AJAX. Check what xmlhttp.status is, if it's 404, then you're never going to get to the point where you're printing the AJAX response. Make sure that "clearSearchData.asp" is accessible from the same directory as your javascript. This is a common problem if you have your javascript code in a separate folder from the rest of your site. Or simply put in the full URL path for the "clearSearchData.asp" so it'll definitely work.
Something to point out, the function in xmlhttp.onreadystatechange is (usually) called after it's declared in the code. In this case, it gets called after your search form fields are cleared out and reset.
The ajax call does not automatically send along a session cookie. That means the session you're clearing is not the user's session, but just a session that's been created for that ajax call alone.
I am using a simple "live search" script that displays the results from a MySQL database as the user types into a text box. It works perfectly fine if the Javascript is pointing to a completely separate page but I need it to point to the same page. Unfortunately when I try and do this the page is duplicated within itself as the results are generated.
This works as expected:
Document called: "test.php" containing JavaScript below and test2.php containing the PHP code
xmlhttp.open("GET","test2.php?livesearch="+str,true);
xmlhttp.send();
This creates a page within a page:
Document called: "test.php" containing both the JavaScript and PHP code below
xmlhttp.open("GET","?livesearch="+str,true);
xmlhttp.send();
I understand that it's because it is opening itself in a loop but I'm not sure what I am supposed to change in the code to avoid this. Any help would be greatly appreciated as I haven't found much help via Google.
Here is all my code:
Javascript
function showResult(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","&livesearch="+str,true);
xmlhttp.send();
}
PHP Code
if(isset($_GET['livesearch'])) {liveSearch();}
function liveSearch() {
$q=$_GET["livesearch"];
$sqlQuery = "SELECT * FROM something WHERE something LIKE '%" . $q . "%' ;
etc etc etc
}
Why would you want the code to point to itself? Seems logical to have a web service that would return only the content that is needed. It is not like you have to duplicate the code, just make some common method that spits out the content in the full page or in the web service.
If you need to call the same page, you can always use a regular expression to rip out the content that you need instead of replacing the whole page.
I am using this HTML
<html>
<head>
<Title>EBAY Search</title>
</head>
<script language="JavaScript" src="ajaxlib.js"></script>
<body>
Click here link to show content
<div id="Result"><The result will be fetched here></div>
</body>
</html>
With this Javascript
var xmlHttp
function GetEmployee()
{
xmlHttp=GetXmlHttpObject()
if(xmlHttp==null)
{
alert("Your browser is not supported")
}
var url="get_employee.php"
url=url+"cmd=GetEmployee"
url=url+"&sid="+Math.random()
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function FetchComplete()
{
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("Result").innerHTML=xmlHttp.responseText
}
if(xmlHttp.readyState==1 || xmlHttp.readyState=="loading")
{
document.getElementById("Result").innerHTML="loading"
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
However it is not being called. get_employee.php works fine when I call it by itself, so that is not the problem. Is there anything wrong in my code that would prevent it from being called? I cannot test with any firefox extensions, I do not have access, so please don't give that as an answer.
edit: the problem is the javascript is not being called at all. I fixed the question mark problem, but even just a simple javascript with an alert is not being called.
use a javascript debugging tool like firebug, this will make your life simpler.
you had a syntax error in your code that made the error "GetEmployee is not defined"
it was a missing "catch" after the last try in "GetXmlHttpObject()". this is the same function after adding the missing "catch".
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
return xmlHttp;
}
var url="get_employee.php?"
Needs the "?".
It's better to use this markup to include your scripts:
<script type="text/javascript" src="ajaxlib.js"></script>
Change this
var url="get_employee.php"
url=url+"cmd=GetEmployee"
url=url+"&sid="+Math.random()
to this:
var url="get_employee.php?cmd=GetEmployee&sid="+Math.random();
You were missing the "?" and there's no need for all of the concatenation (but I guess that's just personal style).
Also, if you actually have the "<The result will be fetched here>" in your html, you should remove it.
I am a bit confused about putting the <script> tag into the no man's land between head and body. Does this have some special meaning?
Shouldn't there be a question mark or an ampersand between the getcommand.php and the cmd= parts?
I don't suppose its something silly like a missinq question mark in the url
var url="get_employee.php"
url=url+"cmd=GetEmployee"
url=url+"&sid="+Math.random()
I would have expected to see "?cmd=GetEmployee"
Make sure you aren't misplacing or naming a file.
You can change OnClick to all lowercase too.
var url="get_employee.php" + "?"
(answering the comment)
What error is reported? You still have to attach your FetchComplete function to xmlHttp's "onreadystatechange" property, but it shouldn't be an error not to do it.
Make sure that ajaxlib.js is really loaded, and that it is the file you mean. Put some alerts and see if they pop up.
If you can't use a proper debugger, you can add alert statements all over the place to see if anything is happening at all (yes, it's a bad solution, but anytime you don't use a good tool you have a bad solution).
Also, make sure the OnClick() returns false, to prevent the browser from reloading the page.
link
becomes
link
You can use alert(url) to check the exact url being sent.