ajax XMLHttpRequest readystate - php

I have an html page with this form
<form id="quick-search" autocomplete="off" class="form-wrapper cf" >
<div style="text-align: center;">
<input id="qsearch" name="qsearch" onkeyup="liveSearch()" placeholder="Search here..." required="" type="text">
<button onclick='ajaxFunction()' id="submitButton">Search</button>
</div>`
and this div where I put the results of ajaxFunction
<div id='ajaxDiv'>Your result will display here</div>
when I click the button the ajaxFunction executed. Just opens a php file where I make a sql query as user writes it in qsearch input form. Here is the JavaScript code:
function createRequestObject(){
var request_o;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_o = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_o = new XMLHttpRequest();
}
return request_o;
}
var http = createRequestObject()
function ajaxFunction(){
// Create a function that will receive data sent from the server
http .onreadystatechange = function(){
try{
if(http .readyState == 4){
if(http .status==200){
try{
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML= http .responseText;
}catch(err){
// display error message
alert("Error reading the response: " + err.toString());
return false;
}
}
}
else{
alert(http .readyState+" "+http .status);
}
}catch(e){
alert('Caught Expection: '+e.description+' '+http .status);
return false;
}
}
var par = document.getElementById('qsearch').value;
var queryString = "?par=" + par;
http.open("GET", "results3.php" + queryString, true);
http.send(null);
}
The code works well but the problem is that I need to click the button two times(with the same text in input field of course) to make result text stay in div. At first click the same results come out but the page automatic refresh and results(also the text in input form) disappear.At second click the page don't refresh show no problem.With the alert in code I can see the readyState and status. The states,status produced are 1,0->2,200->3,200->1,0. between state 3 and 1 results shown on page(clearly state 4 comes without problem) but why I have state 1 after 4? All this in Firefox 17.0.1
Thanks in advance for any help!

I work on this at least one day and I found the solution 10 min after I post my problem! The answer is here [Stop refreshing with ajax , javascript , php][1] [1]: Stop refreshing with ajax , javascript , php… I only had to add return false here: onclick='ajaxFunction();return false' and now it works perfect! Thanks!

Related

PHP load data in modal

I need to load data from a database table using an ID that is sent to a modal window.
Basically, when the grid loads, there are multiple columns. Two in particular are called CONTAINER_ID and WORKFLOW.
Whatever is returned for WORKFLOW will be a link that opens up a MODAL popup called #mySVCModal. Here is the sample code:
while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE)
{
echo "<tr";
echo "<td style=\"width: 50px;\">{$Row[CONTAINER_ID]}</td>";
echo "<td style=\"width: 50px;\"><a class=\"open-container\"
data-toggle=\"modal\" href="#mySVCModal\"
data-cont=\"{$Row[CONTAINER_ID]}\">{$Row[WORKFLOW]}</a></td>";
echo "</tr>";
}
When the user clicks on {$Row[WORKFLOW]}, a modal window opens up with the CONTAINER_ID from the same row.
Here is the javascript that makes that happen:
echo "<script type=\"text/javascript\">
$(document).on(\"click\", \".open-Container\", function() {
var myContainer = $(this).data('cont');
$(\".modal-body #containerID\").val( myContainer );
});
</script>";
At this point, the modal window is open, and I can display the CONTAINER_ID. Here is the code that displays the CONTAINER_ID:
<div id="mySVCModal">
<form action="" method="POST">
<input type="text" name="containerID" id="containerID" class="containerID" />
*** more code here ***
</form>
</div>
So no problem. The CONTAINER_ID is displayed in an INPUT field called "containerID".
What I need to make happen now is when the modal window opens, "containerID" is sent to a PHP variable that will retrieve the WORKFLOW information from a database table called WORKFLOW_TABLE.
When I try to convert containerID into a PHP variable and echo it out, nothing is displayed:
<?php
$containerID = $_POST['containerID'];
echo "this is containerID " . $containerID; // only displays the text, not the $containerID
?>
I know that once I can get the code directly above to display the containerID in an ECHO, I can run a query off of it.
So basically, what I need to do is when the modal window opens, PHP will take containerID and run a " SELECT * FROM WORKFLOW_TABLE where CONTAINER_ID = 'containerID' ";
The contents from WORKFLOW_TABLE should automatically be displayed in various INPUT fields. I'm just using INPUT fields for now. That's beside the point.
So all in all, I need the modal to open up with the contents from WORKFLOW_TABLE displayed using the containerID.
I hope I worded this clearly.
Please help.
Sounds like you need an AJAX query.
<script>
function loadData()
{
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("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "db_query.php?containerID = " + document.getElementById('containerID').getAttribute('value'), true);
xmlhttp.send();
}
window.onload = loadData;
</script>
<div id="myDiv"></div>
Sorry in advance for any possible flaws, I didn't actually run this.
It looks like you're not actually submitting your form to the server when you're loading the modal.
Since you probably don't want to reload the entire page to display the modal, you should request the modal content on demand using an asynchronous request. Since your sample code uses jQuery, I've used the same here. (see the jQuery.load() documentation for more info)
echo "<script type=\"text/javascript\">
$(document).on(\"click\", \".open-Container\", function() {
var myContainer = $(this).data('cont');
$(\".modal-body #containerID\").val( myContainer );
$('.modal-body').load(
'yourPHPscript.php',
{ containerID: $('#containerID').val()}
);
});
</script>";
Then your PHP script should resemble this (notice the change from POST to GET):
<?php
$containerID = $_GET['containerID'];
echo "this is containerID " . $containerID;
?>

Form will not submit via ajax in ie8 - cross domain response failing

I am a beginner with jQuery, AJAX and php. Here is what I am trying to achieve:
- If a user enters the website through a page that does not already have an email form, show a modal pop-up asking them to opt-in with email address.
- Once user clicks submit, change the content in the modal to show a thank you message and then automatically close the modal, allowing the user to interact with the page they originally came to.
- Send submitted info to a database
-I do not want to redirect them to a confirmation page upon submit, but it would be OK if the modal did not automatically close and instead just displayed a confirm message.
I have to host the php on a different server than the website is hosted on, so I think am having a cross-domain response issue. I am able to successfully submit the form (submission goes into database) in Firefox, Chrome, Safari and IE10, and I don't see any error messages in the console when I submit the form. However, data will not transmit from IE8.
I've done some research online and read about using JSON, JSONP, and XDR but a) I'm not clear as to how to implement (over my head right now) and b) seems using these methods seems to increase the risk of someone getting access to these email address submissions.
What can I do to make this work in IE8? Any guidance will be appreciated. An iFrame was the closest alternative I could find so far, but the scrollbars do not disappear and they are unacceptable.
Here are my scripts (web server automatically uses jquery 1.3.2 and I have to use a newer version for the modal, hence the use of noConflict. Not an option to remove reference to 1.3.2):
<script type="text/javascript">
var jQuery_1_7_2 = jQuery.noConflict(true);
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
jQuery_1_7_2(document).ready(function(){
var emailFormExists = jQuery_1_7_2('#e2ma_signup_form');
if (document.cookie.indexOf('visited=true') == -1 && !(emailFormExists.length)){
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
jQuery_1_7_2.fancybox({width:"100%", inline:true, href:"#inline"});
}
else
{
jQuery_1_7_2('#e2ma_signup_form').length
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
}
jQuery_1_7_2("#contact").submit(function() { return false; });
jQuery_1_7_2("#send").on("click", function(){
var emailval = jQuery_1_7_2("#email").val();
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
jQuery_1_7_2("#email").addClass("error");
}
else if(mailvalid == true){
jQuery_1_7_2("#email").removeClass("error");
}
if(mailvalid == true) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
jQuery_1_7_2("#contact").fadeOut("fast", function(){
jQuery_1_7_2(this).before("<p><strong>Thanks for opting in!</strong></p>");
setTimeout("jQuery_1_7_2.fancybox.close()", 1000);
});
jQuery_1_7_2.ajax({
type: 'POST',
url: 'http://domain.com/scripts/email-opt-in.php',
data: jQuery_1_7_2("#contact").serialize(),
success: function(data) {
if(data == "true") {
jQuery_1_7_2("#contact").fadeOut("fast", function(){
jQuery_1_7_2(this).before("<p><strong>Thanks for opting in!</strong></p>");
setTimeout("jQuery_1_7_2.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
Here is the php:
<?php require_once('../Connections/Liz.php'); ?>
<?php
$insertSQL = "INSERT INTO optin (id, email) VALUES ('','".$_POST['email']."')";
mysql_select_db($database_Liz, $Liz);
$Result1 = mysql_query($insertSQL, $Liz) or die(mysql_error());
?>
and here is my html:
<div id="inline">
<h2>Join the mailing list!</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<button id="send">Submit</button>
</form>
</div>
First of all, I have to say that using jQuery_1_7_2() definitely looks bad for code rewrite! May I suggest var $j = jQuery.noConflict(true); -- then you can use your usual $j(window).method()'s
Anyways, you may face more trouble than its worth with cross-site posting via AJAX calls. This link may be related: CORS with jQuery and XDomainRequest in IE8/9
Using an IFRAME to post sounds like a good idea - but I don't understand why you can't hide the scrollbars. You can use CSS to move the iframe to -999em (vertical) off of the browsers viewport or wrap it in a hidden div.

ajax POST respond

I use niceEdit as a html editor and a mysql for back end. The process I will send the data into a php using AJAX.
Heres my html code:
<div class='atabcontent'>
<form id='apostform' method='POST'>
<input name='request' type='hidden' value='atabaddnew' />
<textarea id='aposttextarea' name='area1' style='width:780px; height: 400px; margin: 10px auto 0 auto;'cols='40'></textarea>
<div style='height: 5px;'></div>
<button id='apostsubmit'>Save</button>
</form>
</div>
and heres the ajax code.
$("#apostform").submit( function () {
//add a loading bar first
$('div.atabcontent').append("<img class='loading' src='media/loading.gif' />");
//send data to processor.php
$.post(
'processor.php',
$(this).serialize(),
//here, where we're going to manage the respond from the processor.php
function(data){
//remove the loading bar
$('.atabcontent img.loading').remove();
//output the respond
$('div.atabcontent').html(data).show();
});
return false;
});
and heres the php file (processor.php).
<? //this a processor e.g. post, delete, edit etc..
//check if a post "request" is present..
if (isset($_POST['request']))
{
//check if what type of request, if request type is equal to atabmenu then..
if ($_POST['request'] === "atabmenu")
{
echo $_POST['data'];
}
elseif ($_POST['request'] === "atabaddnew")
{
echo htmlspecialchars($_POST['area1']);
}
//end
//else if no request then go to fail.php along with the error code of "unable to process the data"
}
else
{
header("location: fail.php?error=unable to process the data");
}
?>
as you can see on the above code, it should work fine, but the respond from the php file that has been fetch by the ajax respond handler is empty and seems like there is no data that has been sent or neither has been received also i tried this
$("#apostform").submit( function () {
var data = $('#apostform textarea').val();
alert (data);
return false;
});
but there the alertbox content is empty and as you can see in the code, it should alert a box with the value of the "#apostform". I tried a normal form, i mean no ajax and its work fine because i can see the data has been receive because it display the data receive from the form.
hope someone could help me on pointing out on what seems the problem on this. anyway i use niceEdit textbox http://nicedit.com/
PS: im open in any suggestion, recommendation and idea. Thanks in advance.
Your submit function seems to have a few syntax errors in it
$("#apostform").submit( function () {
var data = $('#apostform textarea').val(); // missing equals sign and closing apostrophe
alert (data);
return false;
});

PHP/AJAX - advice on replacing iFrame with DIV (combined with AJAX)

I currently have a webpage where an iframe contains data that is stored into an invisible form, and I want to replace that iFrame, with a div, where the content is being changed/updated via AJAX.
If you dont feel like reading all this, you can skip to the end and read my main question.
Now, the complicated part is that the form contains all the important and used data in an invisible form, which needs to be send via POST. But, the page also includes a form that can send data via GET. And: I've setup the forms like this, that the php file recieves the form data as an array.
At the moment it works like this:
The iFrame shows the data, and stores it in an invisible form. When you want the page to refresh automatically, every 30 seconds, you click a button, and you get redirected to another page, which recieves the data from the previous page, using POST.
When you're on the auto-refreshing page, I use Javascript to automatically submit the form containing all the important data, to refresh the page.
Resubmitting the page is nessecary because I use PHP to do some important calculations with the data I'm using. Moving all this functionality to Javascript is not an option.
Just to be clear, here is a very brief description of my case:
Main page: 2 forms, 1 POST setup so variables are in 1 array, 1 GET with 6 variables.
The GET form could be modified to an AJAX function, as it only includes 6 variables
Auto update page: 2 forms, same as before. Though this POST form is auto-submitted via Javascript every 30 seconds (to update the PHP
functions output).
So, my main question is:
Can I, and if so how, recieve an array from a POST form in AJAX, and then send it as an array to a php page?
EDIT:
Here is some of the code for submitting the form:
<script type="text/javascript">
function paginarefresh() {
document.forms["updateform"].submit();
}
var paginatimer = setInterval(paginarefresh, 60000);
</script>
and the form is build up like this:
echo '<form action="data-reis-refresh.php" id="updateform" name="update" method="POST" style="width: 100px;">';
echo '<input type="submit" class="submit replaced" value="Volg deze trein" name="submit-search"/>';
if (round($afgelegdpercentage*100,1)==100) {
echo ' <span style="text-align: center;">Deze trein is al aangekomen</span>';
} else {
echo ' <span style="text-align: center;">Ververs gegevens (automatisch elke minuut)</span>';
}
echo '<input type="hidden" name="provincie" value="'.$provincie.'">
<input type="hidden" name="reisdata[Overstap]" value="'.$reisdata["Overstap"].'">
<input type="hidden" name="reisdata[Van]" value="'.$reisdata["Van"].'">
but then longer (a lot longer, and with changing length);
I'm using this for all my AJAX requests: [though I change it for different uses]
// Algemene functie om een xmlHttp object te maken. Via dit object kunnen we later Ajax calls plaatsen
function GetXmlHttpObjectReisData() {
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 CallAjaxReisDataFunction(serverScript,arguments)
{
var xmlHttp = new GetXmlHttpObjectReisData(); // Functie welke wordt uitgevoerd als de call naar de server klaar is State 4)
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
handleReisDataResult(xmlHttp.responseText);
}
}
// Ajax call (Request naar de server met eventuele parameters (arguments))
xmlHttp.open("POST", serverScript, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", arguments.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(arguments);
}
function callReisDataServer(serverScript,van,naar)
{
CallAjaxReisDataFunction(serverScript,"?&reisdata=" + reisdata);
}
function handleReisDataResult(responseText)
{
document.getElementById('reis').innerHTML = responseText;
}
JS code:
var postdata = {"provincie":"123","reisdata":{"Overstap":"234","Van":"345"}};
var post = "";
var url = "data-reis-refresh.php";
var key, subkey;
for (key in postdata) {
if (typeof(postdata[key]) == object) {
for (subkey in postdata[key]) {
if (post != "") post += "&";
post += key + "%5B" + subkey + "%5D=" + postdata[key][subkey];
}
}
else post += key + "=" + postdata[key];
}
req.open("POST", url, true);
req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-length", post.length);
req.setRequestHeader("Connection", "close");
req.send(post);
And to transfer associative array back from PHP to JS:
In PHP script, called from AJAX request:
echo "(".json_encode($hash).")";
In JS code, parsing the result:
var hash = eval(response);
In the end, I ended up using jQuery .post() and .get().
Those are extremely easy to use and a lot faster and more flexible.

Jquery form only working the first time you submit it, and not the second

I have a form that you can add data to a database. It is all done with jquery and ajax so when you press submit it validates the code and then if everything is correct it submits the post data with out refreshing the page. The problem is the form works the first time, but then when you go to submit another entry with the form it doesn't work. I thought it had something to do with the
$(document).ready(function(){
But I really have no idea. I've pasted some of the code below. It is pretty long, but this should give enough info to know what it's doing.
The entire js file is at http://www.myfirealert.com/callresponse/js/AddUser.js
$(document).ready(function(){
$('#AddCaller').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var Firstname = $('#Firstname').val();
...OTHER FORM FIELDS HERE
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut. */
if(Firstname.length == 0){
var error = true;
$('#Firstname_error').fadeIn(500);
}else{
$('#Firstname_error').fadeOut(500);
}
if(Lastname.length == 0){
var error = true;
$('#Lastname_error').fadeIn(500);
}else{
$('#Lastname_error').fadeOut(500);
}
...MORE CONDITIONAL STATEMENTS HERE
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'added'){
//$('#cf_submit_p').remove();
//and show the success div with fadeIn
$('#Add_success').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
document.getElementById('Firstname').value = "";
document.getElementById('Lastname').value = "";
document.getElementById('PhoneNumber').value = "";
document.getElementById('DefaultETA').value = "";
document.getElementById('Apparatus').value = "";
document.getElementById('DefaultLocation').value = "";
setTimeout(" $('#Add_success').fadeOut(500);",5000);
}else if(result == 'alreadythere'){
//checks database to see if the user is already there
$('#Alreadythere').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
}
else{
//show the failed div
$('#Add_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
Right now, the first time you use the form it works great. and the button is reenabled, but then when you try to make another entry and click the button nothing happens.
Thanks for the help!
EDIT: After the form submits the first time the button is still enabled and you can click on it, but when you click on it nothing happens... even if you don't fill in the form. It's like the click event of the form isn't firing the first time.
EDIT2 As requested, I'm going to post the HTML, it's behind a password protected site, so I can't send you the page link.
<form action='addcallers.php' method='post' id='AddCaller_form'>
<h2>Add Callers</h2>
<p>
First Name:
<div id='Firstname_error' class='error'> Please Enter a First Name</div>
<div><input type='text' name='Firstname' id='Firstname'></div>
</p>
<p>
Last Name:
<div id='Lastname_error' class='error'> Please Enter a Last Name</div>
<div><input type='text' name='Lastname' id='Lastname'></div>
</p>
...MORE FORM FIELDS HERE
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly >
</div>
</p>
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
<p id='cf_submit_p'>
<input type='submit' id='AddCaller' value='Send The Message'>
</p>
</form>
</div>
EDIT3 There is other ajax on the page too, but it's written in straight javascript. I'm not sure if that would affect the functionality in any way. But if needed I can post that ajax as well.
EDIT4 I got the original tutorial from http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ and modified it
EDIT After putting in some different alerts, I found out that it does not do the conditional statement if(error==false)... Any Idea why?
most likely, it's the #DefaultLocation field, since it's a read only and you are resetting it after the first post:
document.getElementById('DefaultLocation').value = "";
And never changing it's value back to something (or are you?)
so you have to do one of the following:
don't reset it
set it's value with something after posing the form
don't validate it at all since it's a read only and you are using it as a hidden input (which is wrong by the way)!
also, it can be the other "ajax" code you are talking about so please post that too here, also maybe you have other fields (elements) somewhere else on the page with same IDs like the ones in the form..
anyway, here are sometips for you:
1- close the input tags correctly (add / to the end of it):
<input type='text' name='Firstname' id='Firstname' />
2- make sure all DIVs and Ps are closed...as it seems that you have an open P here:
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
</p> <---- missing this one
<p id='cf_submit_p'>
3- you are redeclaring the error variable all the time, you don't need to do that:
if(Firstname.length == 0){
var error = true;
....
just use error = true; without var this applies on all places you are changing its value only use var on initialization:
var error = false;
4- instead of this:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
use:
$('#AddCaller').attr({'disabled' : 'disabled', 'value' : 'Adding...' });
5- if you are using DefaultLocation as a hidden field then instead of this:
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly />
</div>
use:
<input type="hidden" name="DefaultLocation" id="DefaultLocation" value="Something" />
Try to change from using the click event handler to the form's submit event handler
Change this : $('#AddCaller').click
To this : $('#AddCaller_form').submit
Do not remove the attribute of disabled, set it to false.
This line
$('#AddCaller').removeAttr('disabled').attr(...
should be
$('#AddCaller').attr('disabled', false).attr(...
I assume that by removing and adding attributes, the element is removed and replaced by the new one, but the handler is not re-attached. Try using $('#AddCaller').live('click', function(){ //code }) instead of .click()
This function send queries to php and can return results from the php file using ajax.
I have left comments for guide. the first part with try & catch statements does not need modifications. go to #1 and #2
function ajaxFunction(){
var ajaxRequest;
//Browser compatible. keep it as it is
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//Browser compatible end
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//#2 opional: create functions to return data from your php file
$('#resultArea').html(ajaxRequest.responseText);
}
}
//#1 Set the form method, filename & query here here
ajaxRequest.open("GET", "serverTime.php?query=something", true);
ajaxRequest.send(null);
}
example:
<input type='submit' value='ajax-submit' onclick='ajaxFunction()' />
quick jquery plugin for that since you might use this in almost every ajax form on your site:
it will disable all fields that could trigger a submit event and also add a class on the form tag so that you can apply some styling, or showing a load message when the form is submitted:
jQuery.extend(jQuery.fn, {
formToggle: function (enable){
return this.each(function(){
jQuery(this)[(enable ? 'remove' : 'add') + 'Class']('disabled')
.find(':input').attr('disabled', !enable);
},
enable: function(){ return this.formToggle(true); },
disable: function(){ return this.formToggle(false); }
}
then on your jq ajax code:
[...]
var $form = $(your_form).submit(function(){
$.ajax({
type: 'post',
url: "/whatever/",
data: $form.serialize(),
success: function (){ alert ('yay');},
complete: function(){ $form.enable();},
error: function(){ alert('insert coin')}
}
$form.disable();
return false;
});
It should be enough to properly block the submits while the forms is sending/receiving data.
If you are really paranoid you can add a check so that it cannot be sent twice between the moment the user triggers the submit and the fields get disabled with : if ($form.is('.disabled')) return false; as first line of the submit handler, but it shouldn t be necessary really
Set some breakpoints in Firebug and watch if it goes somewhere.
Button can lose its click handler after submit and applying effects. You probably need to assign click handler again after submit and stuff.
Not 100% on this but try setting the code as a separate function then rebinding the click event at the end.
Example:
function addCaller(e) {
// your unchanged code
$('#AddCaller').click(addCaller(e));
}
$(document).ready(function(){
// added an unbind just in case
$('#AddCaller').unbind('click').click(addCaller(e));
});
Try to change this:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
into that:
$('#AddCaller').attr({'value' : 'Adding...' });
This should make it work.

Categories