need to make sure my ajax script is set up right - ajax

ajax code:
try {
xmlhttp = new XMLHttpRequest();
}
catch(ee) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E) {
xmlhttp = false;
}
}
}
div_base = "";
valor = 0;
function abre(arquivo,metodo,div) {
div_base = div;
valor++;
xmlhttp.open(metodo,arquivo+"?valor="+valor);
xmlhttp.onreadystatechange=response
xmlhttp.send(null)
}
function response() {
nova_div = div_base;
document.getElementById(nova_div).innerHTML="<div>Loading...</div>"
if (xmlhttp.readyState==4) {
document.getElementById(nova_div).innerHTML=xmlhttp.responseText
}
}
html code:
<form>
<select name="menu" style="width:400px; height:25px;">
<option>Change Theme:</option>
<option></option>
<option onclick="javascript: abre('Chat_Themes/Default.html','GET','response2');">Default - Shadow Hunters</option>
<option onclick="javascript: abre('Chat_themes/Custom.html','GET','response2');">Custom - Shadow Hunters</option>
</select>
</form>
<br />
<div id="response2"></div>
i changed the "div = responce" to "div = responce2" without changing the ajax code at the top, im not sure if i have to change the ajax code or not or i can leave it and it works fine the way it is, but it does not work on google chrome idk if its just google chrome being retarded, but it works in ff and ie just fine, any thoughts?

Try indenting your code: you'll find that your try-catch statements don't have matching braces. You can also try a Javascript-validating service like jshint, but indenting should come first.
You might want to consider using a third-party library which already has cross-browser AJAX capability, like jQuery.

Related

Chosen with Ajax in Classic Asp

I'm new to Ajax and Chosen so please bear with me. I'm trying to reload a second select box based on the selection of the first one. All of my select boxes are using the Chosen plugin.
First, this is my JQuery function for chosen.
$(function(){
$('.TeacherName').chosen({ max_selected_options: 1, placeholder_text_multiple: "Select A Teacher"});
$('.Schools') .chosen({ max_selected_options: 1, placeholder_text_multiple: "Select A School" });
});
</script>
Next I load the two boxes from a record-set.
<select class="Schools" name="Schools" id="schoolDrop" style="max-width:210px;" multiple="multiple" onchange="getLocation(this.value);">
<% while not SchoolList.eof%>
<option value="<%=SchoolList("SCHOOL_NUMBER")%>"><%=SchoolList("NAME")%> </option>
<%SchoolList.MoveNext
wend%>
</select>
<select class="TeacherName" name="TeacherName" id="TeacherName" multiple="multiple"style="max-width:150px;">
<option value="0"></option>
<%while not TeacherList.eof%>
<option value="<%=TeacherList("DCID")%>"</option>
<%TeacherList.MoveNext
wend%>
</select>
As you can see I call the Ajax function in an onchange event in the Schools select box.
Next is my Ajax Function.
function getLocation(schoolId)
{
var strURL="SetTeacherAjax.asp?school="+schoolId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('TeacherName').innerHTML=req.responseText;
} else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}//End of Function getLocation
The ajax works if I remove the class selector from the TeacherName drop down.
I've figure this out, so I'll post it as it may help someone else. I needed to add an update statement for Chosen plugin.
enter code here if (req.status == 200)
{
document.getElementById('TeacherName').innerHTML=req.responseText;
$('#TeacherName').trigger('chosen:updated');
} else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
Once I added the
$('#TeacherName').trigger('chosen:updated');
it worked.

jQuery returning null - selected option not being posted correctly?

This jQuery script is returning null. I've tried using other syntax for selected options but here's what I've got below:
The script works and runs correctly, allowing me to download the Excel file. However the ID is not being set correctly (via the option selected) and thus is parsing as "0".
<script>
//When Page Loads....
$(document).ready(function(){
$('#dropdown').change(function(){
// Call the function to handle the AJAX.
// Pass the value of the text box to the function.
sendValue($(this).val());
});
});
// Function to handle ajax.
function sendValue(str){
// post(file, data, callback, type); (only "file" is required)
$.post(
"scripts/export_to_excel/index.php", //Ajax file
{ sendValue: str }, // create an object will all values
//function that is called when server returns a value.
function(data){
$('#linkDiv').html(data.returnValue);
},
//How you want the data formatted when it is returned from the server.
"json"
);
}
</script>
Select HTML
<p>Select event for export to Excel:</p>
<p>
<select name="eventIDExport" id="dropdown">
<option value=0>
<?=$options?>
</select>
</p>
<?php var_dump($_POST['eventIDExport']); ?>
<div id="linkDiv"></div>
Rendered mark-up
<p>Select event for export to Excel:</p>
<p>
<select name="eventIDExport" id="dropdown">
<option value=0>
<option value="1">BIG event</option>
<option value="54">2013 Network Conference</option>
</select>
</p>
NULL
<div id="linkDiv"></div>
Some of the code in index.php to process Ajax request - I think this is triggering the null value?
if (isset($_POST['eventIDExport']))
{
$eventIDExport = $_POST['eventIDExport'];
}else{
$eventIDExport = "";
}
Why you POST sendValue and check if eventIDExport is set?
$.post("scripts/export_to_excel/index.php", {
sendValue: str
^^^^^^^^^
and
if (isset($_POST['eventIDExport']))
^^^^^^^^^^^^^
Your code should be:
if(isset($_POST['sendValue']))
{
$eventIDExport = $_POST['sendValue'];
} else {
$eventIDExport = "";
}
or
$.post("scripts/export_to_excel/index.php", {
eventIDExport: str

Ajax Parent Form Submit not working for Calendar

I have a popup calendar that is being called from the parent form. What I am wanting to happen is when the user clicks on the date after it updates parent form field it automatically submits the parent form (where certain date checks will happen upon refresh). Ive tried using Ajax and for some reason the calendar popup window closes after the selection is made but the parent form wont submit. Is there anything Im missing here?
Here is the ajax code in the actual calendar popup window.
<script type=”text/javascript”>
// function create GetXmlHttpObject
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 submitFormWithAjax(){
var myAjaxPostrequest=new GetXmlHttpObject();
var t2lrequestend=document.docreq.request_end.value;
var t2lrsubmit="Submit Request";
var parameters=”request_end=”+t2lrequestend+"rsubmit="+t2lrsubmit;
myAjaxPostrequest.open(“POST”, “rm_new_arp_request_NEW_TIME_RESTRICTION.php”, true);
myAjaxPostrequest.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
myAjaxPostrequest.send(parameters);
myAjaxPostrequest.onreadystatechange=function(){
if(myAjaxPostrequest.readyState==4){
if(myAjaxPostrequest.status==200){
document.getElementById(“result”).innerHTML=myAjaxPostrequest.responseText;
document.getElementById(“docreq”).style.display = “none”;
}
else {
document.getElementById(“docreq”).innerHTML=”An error has occured making the request”;
}
}
}
}
</script>
And here is where it is supposed to submit the form and close the child window.
function set_datetime(n_datetime, b_close) {
if (!obj_caller) return;
var dt_datetime = obj_caller.prs_time(
(document.cal ? document.cal.time.value : ''),
new Date(n_datetime)
);
if (!dt_datetime) return;
if (b_close) {
obj_caller.target.value = (document.cal
? obj_caller.gen_tsmp(dt_datetime)
: obj_caller.gen_date(dt_datetime)
);
submitFormWithAjax();
window.close();
}
else obj_caller.popup(dt_datetime.valueOf());
}
if (obj_caller && obj_caller.time_comp)
document.write('<form onsubmit="javascript:set_datetime('+dt_current.valueOf()+', true)"><tr><td colspan="7" bgcolor="#87CEFA"><font color="White" face="tahoma, verdana" size="2">Time: <input type="text" name="request_end" value="'+obj_caller.gen_time(this.dt_current)+'" size="8" maxlength="8"><INPUT TYPE="hidden" NAME="rsubmit" VALUE="Submit Request" ></font></td></tr></form>');
</script>
</table></tr></td>
</table>
</body>
</html>
Any ideas on how I can get this to submit the parent form with the date still being used?

Ajax response text correct but not displaying

i tried finding this problem using google but no luck so far , so im asking for some help.
im working with a webpage on JSP and im having a little problem with ajax responseText, im testing the page on firefox and using firebug.
the problem its that the operation its completed correctly and the response text show ok on the firebug console, but it doesnt display on the <div> i assigned.
when i put an alert() inside the function handling the onreadystatechange it displays correctly as if the response was just too late, so im a bit lost.
can anyone give me an idea?
my JS handling the submit is
function validate( form ) {
var expresion = /[\b\W\d]+/;
var error=0;
var nombre = document.getElementById("Addname");
var descripcion = document.getElementById("Adddescripcion");
if(nombre.value == "" ){
nombre.focus();
nombre.style.backgroundColor="red";
alert("Los Campos no deben estar vacios");
error = error+1;
}else{
if(!(expresion.test(nombre.value))){
var temp = nombre.value.toUpperCase();
nombre.value = temp;
}else{
nombre.focus();
nombre.style.backgroundColor="red";
alert("La entrada no es valida");
error = error+1;
}
}
if( descripcion.value == "" ){
descripcion.focus();
descripcion.style.backgroundColor="red";
alert("Los Campos no deben estar vacios");
error = error+1;
}
if(error == 0){
var url = "addCarrera";
var params = "name="+ nombre.value +"&descripcion="+descripcion.value;
ajaxPost(url,params,"addres");
document.getElementById("addres").setAttribute("class","visible");
clearing();
}
}
function clearing(){
var nombre = document.getElementById("Addname");
var descripcion = document.getElementById("Adddescripcion");
nombre.value="";
descripcion.value="";
nombre.style.backgroundColor="white";
descripcion.style.backgroundColor="white";
var timer = setTimeout("ocultar()", 1500);
}
an my code handling the Ajax request its
var ajaxCall;
function ajax_request() {
if(window.XMLHttpRequest){
//codigo para IE7+,Firefox,Chrome, Opera,Safari
ajaxCall=new XMLHttpRequest();
}else{
//codigo para IE6 y 5
ajaxCall=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function ajaxPost(url ,params, respuesta){
ajax_request();
ajaxCall.onreadystatechange = statechangeHandle(respuesta);
ajaxCall.open("POST",url,true);
ajaxCall.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxCall.setRequestHeader("Content-length", params.length);
ajaxCall.setRequestHeader("Connection", "close");
ajaxCall.send(params);
//alert("respuesta? "+respuesta);
}
function statechangeHandle(text){
//alert("text?"+text);
//alert("ready?"+ajaxCall.readyState);
if(ajaxCall.readyState == 4 && ajaxCall.status === 200){
//alert("prueba");
document.getElementById(text).innerHTML=ajaxCall.responseText;
//alert(ajaxCall.responseText);
}
}
the html part
<h3>Agregar Carrera</h3>
<table>
<tr>
<td>Nombre:</td>
<td><input type="text" id="Addname" size="20" /></td>
</tr>
<tr>
<td>Descripcion:</td>
<td><textarea rows="2" cols="20" id="Adddescripcion" > </textarea></td>
</tr>
<tr>
<td><input type="button" value="Agregar" onclick="validate()"></td>
</tr>
</table>
<div class="ocultar" id="addres"></div>
thanks in advance.
by the way ,the ajax at ajaxPost doesnt show a thing but for example at statechangeHandle if active te alert before the asign the responseText the html its modified correctly but if not then the div stays the same, im not quite sure what that means, its like it has to wait i dont know if im just doing something really wrong

Ajax Request Results in form being submitted aswell

As the title states my Ajax call is actually causing the form to be submitted to its default action, why? I've never come across this before, all my other ajax calls have never done this.
function newAjax(t,u){ //t = type(post/get), u = url
var resource = null;
if (window.ActiveXObject) {
resource = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
resource = new XMLHttpRequest();
resource.overrideMimeType('text/html');
}
resource.open(t,u,false);
resource.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
return resource;
}
function send_newsletter(){
formObj = document.getElementById("news_form");
var inputs = formObj.getElementsByTagName("INPUT");
var parameters = "";
for(i = 0; i < inputs.length; i++){
parameters += inputs[i].name+"="+encodeURI(inputs[i].value);
if(i != inputs.length-1){
parameters += "&";
}
}
var url = "whereitshouldbegoing.com";
var ajax = newAjax("POST",url);
ajax.onreadystatechange = ajaxResult;
ajax.setRequestHeader("Content-length", parameters.length);
ajax.setRequestHeader("Connection", "close");
ajax.send(parameters);
}
It all works fine upto the .send line, which is the bugger which is causing the form to submit aswell(I also have no idea if the ajax request actually gets off).
The send_newsletter function is called from an input type="image" element with onclick="send_newsletter()"
Please don't tell me to use jQuery or another library, as much as I would love to, we can't use any external librarys, corporate guidelines and whatnot.
An input of type "image" will behave the same as a submit button. Use an anchor or button type input to trigger your method.
<input type="button" onclick="send_newsletter()" value="Send" />
<button onlclick="send_newsletter()">... </button>
<img src="... />
Are you using a submit button to call send_newsletter?
onreadystatechange callback function 'ajaxResult' is not called because you're doing a synchronous call to the server:
resource.open(t,u,false);
if you want ajaxResult to be called change it to :
resource.open(t,u,true);
for now that's what I see. You have to provide more info like how do you call send_newsletter?
EDIT:(following author comment)
an INPUT of type image is a graphical submit button.

Resources