The ajax jquery I am using in my form takes almost 4 seconds to complete and create the fields I want in my form. Because of that, some users submit the form before those fields are created. I want the form not submitted until those fields are created.
Here is my code.
echo"<form action='http://teachers.teicm.gr/dvarsam/index.php/exelixi_aitisis/' method='post' onsubmit='return recaptcha();'>
<label class='formLabel'>Όνομα*</label><br />
<input name='FirstName' required='' type='text'/><br />
...
...
echo"<select name='ThesisID' id='link_block' onchange='showCourses(this.value)'>
<option disabled='disabled' selected='selected' value=''></option>";
while ($row = mysqli_fetch_array($result))
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";
//displays the courses when thesis is selected
echo"<p id='courses'></p> ";
//placeholder which you’ll need to add to your form markup wherever you want the reCAPTCHA to appear
echo"<div class='g-recaptcha' data-sitekey='6LcIzA4TAAAAABo7Ean4z9EbNJddkkh04x9v6pLs'></div>
<input type='submit' name='action' value='Αποστολή' />
</form>";
On submit function. It checks if receptcha "I am not a robot" is clicked
function recaptcha ()
{
if(grecaptcha.getResponse() == ""){
alert('Παρακαλώ επιβεβαιώστε ότι δεν είστε ρομπότ κάνοντας κλικ στο κουτάκι.');
return false;
}
else
{
return true;
}
}
OnChange javascript. It shows textboxes on < p id='courses'>
//Browser Support Code
function showCourses(str){
var ajaxRequest; // The variable that makes Ajax possible!
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("Problem with your browser!");
return false;
}
}
}
// Create a function that will receive data sent from the server
// and will update div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('courses'); // the div section where it should be displayed
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to server script.
var queryString = "?thesis_id=" + str ;
ajaxRequest.open("GET", "http://teachers.teicm.gr/dvarsam/index.php/get_courses" + queryString, true);
ajaxRequest.send(null);
}
I think that I need to add something in my on submit function that will return true only when the ajax jquery is completed. Am I thinking correctly? Can someone help me with that?
First, give an ID to your submit button and disable it by default:
<input type='submit' ID="SUBMITBUTTON" name='action' value='Αποστολή' disabled />
Then you can do something like this in your On Success return from Ajax to enable the submit button:
$('#SUBMITBUTTON').removeAttr('disabled');
OR
$('#SUBMITBUTTON').prop('disabled', false);
Related
STRANGE BEHAVIORS
No matter how I organize the code:
Submit button makes the loader and then the confirmation message appears even if you dont fill the email input form
Sometimes refresh the page , sometimes dont
What I want is simple:
a) If the email input form is unfilled then dont do nothing just expect the html5 input validation message.
b) If all is ok and the email input is correctly filled then have the loader appears and then the confirmation message.
I have 3 days in a row, experimenting. I'm STUCK.
Thanks in advance
AJAX / JS
function ajaxFunction() {
var form = document.getElementById("contactForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('email_suscribe', handleForm);
var ajaxRequest;
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");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("loading").innerHTML = ''; // Hide the image after the response from the server
document.getElementById("ajaxDiv").innerHTML = xmlhttp.responseText;
}
}
document.getElementById("loading").innerHTML = '<img src="images/loading.gif" />'; // Set here the image before sending request
xmlhttp.open("GET", "includes/suscripcion.asp?email_suscribe=<%=request.form("email_suscribe")%>", true);
xmlhttp.send();
}
FORM
<form id="contactForm" name="contactForm">
HTML
Email Input Form
<input name="email_suscribe" type="email" autocomplete="on" required="required" class="footer_suscribir" placeholder="Correo Electronico" maxlength="60">
Submit Button
<button name="submit" onclick="ajaxFunction();" class="footer_suscribete"><strong>Suscribete</strong></button>
Loader
<span id="loading"></span>
Real Time Confirmation Message
<div id="ajaxDiv"></div>
You can check this.
HTML
<input name="email_suscribe" type="email" autocomplete="on" required="required" class="footer_suscribir" placeholder="Correo Electronico" maxlength="60">
<input type="button" onclick="subscribe()">
<span id="loading"></span>
<span id="ajaxDiv"></span>
JS
<script>
function subscribe() {
var email=$(".footer_suscribir").val()
if (isEmail(email)===true) {
$("#loading").fadeIn("fast")
$.ajax({
type: 'POST',
crossDomain: true,
url: "postdata.asp",
data: {
"email": email
},
success: function (resp) { //resp: return from postdata.asp
$("#ajaxDiv").html(resp)
$("#loading").fadeOut("fast")
},
error: function (e) {
$("#ajaxDiv").html("AN ERROR OCCURRED")
$("#loading").fadeOut("fast")
}
});
}
else {
$("#ajaxDiv").html("EMAIL FORMAT ERROR")
}
}
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
</script>
POSTDATA.ASP
<%
'...
'DB CONNECTION
'...
' SAMPLE DB EXECUTION
email=request.form("email")
Set rsa=Server.CreateObject("Adodb.Recordset")
Sorgu="Select TOP 1 email from subscribers WHERE email='"&email&"'"
rsa.Open Sorgu, bag, 1, 3
if rsa.bof then
rsa.addnew
rsa("email")=email
rsa.update
response.write "SUCCESS"
else
response.write "ALREADY EXISTS"
end if
rsa.close
set rsa=nothing
%>
In my HTML I have an article containing clickable lists. I also have a form that adds data to my database. Once it's done adding the data I want my PHP to send a new list based off the data given in the form to the article in my HTML with my other lists.
How can I do this? I know how to display data from PHP in HTML but I don't know how to display that data in existing articles in HTML.
My function that updates and refreshes my page after every click on a link is called MyFnc and this is the JavaScript for it:
function myFnc(x) {
if (x == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else { //if a link is clicked
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() {
//readyState = 4: request finished and response is ready
//status = 200: "OK"
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "get_data.php?q=" + x, true);
xmlhttp.send();
}
}
And get_data.php is where I display the data from the database to the webpage. I know that displaying the link must be done in get_data since that is where I display everything to the page. But for now I just want to know how to send the data retrieved from add_records and make a list out of it.
This is my article in my HTML:
<article>
<ul class="lists" style="list-style-type:none">
<li>Tiger</li>
<li>Hammerhead</li>
<li>Bull</li>
<li>Great White</li>
<li>Mako</li>
<li>Greenland</li>
<li>Whale</li>
<li>Thresher</li>
<li>Oceanic WhiteTip</li>
<li>Goblin</li>
</ul>
</article>
Here is my form in my HTML:
<form method="post" action="add_to_records.php">
<input type="hidden" name="addshark" value="true" />
<fieldset>
<label>Name:<input type="text" name="Name" /></label>
<label>SpeciesID:<input type="text" name="speciesID" /></label>
<label>Genus:<input type="text" name="genss" /></label>
<label>Family:<input type="text" name="famly" /></label>
<label>Order:<input type="text" name="ordr" /></label>
<label>Class:<input type="text" name="clss" /></label>
<label>Create New Shark</label>
<input type="submit" value="add shark" />
</fieldset>
<br />
</form>
Here is my add_to_records.php:
<?php
include 'connect.php';
if (isset($_POST['addshark']))
{
include 'connect.php';
$Namee = mysqli_real_escape_string($connect,trim($_POST['Name']));
$specID = mysqli_real_escape_string($connect,trim($_POST['speciesID']));
$gens = mysqli_real_escape_string($connect,trim($_POST['genss']));
$fam = mysqli_real_escape_string($connect,trim($_POST['famly']));
$ord = mysqli_real_escape_string($connect,trim($_POST['ordr']));
$cls = mysqli_real_escape_string($connect,trim($_POST['clss']));
if (!mysqli_query($connect, "INSERT INTO Species
(SpeciesID,Genus,Family,Order_,Class)
VALUES ('$specID','$gens','$fam','$ord','$cls')"))
{
die('error inserting new record');
}
//I would like the list it returns to look like this if the Name entered was Hello
//and the speciesID entered was Something
//<li>Hello</li>
//echo "shark was added";
header('Location: ProjectMainAdmin.html'); exit;
}
mysqli_close($connect);
?>
Just use jQuery's AJAX, it's a lot simpler and easier to implement. Data will be passed to server, then once completed you need to append the data into your list.
something like this:
$("form").submit( function(){
$.ajax({
url: "add_to_records.php",
success: function(result){
$(".lists").append("<li><a href=''>" + result.name + "</li>");
}
});
return false;
});
I've searched everywhere but can't find an answer to this problem.
I'm writing a little ajax script but can't get the correct value of the POST request.
This is the code so far:
<textarea id="message" name="message" style="width:100%;"></textarea>
<input value="SEND" style="border-radius: 5px 5px 5px 5px;" type = 'button' onclick = 'ajaxFunction()'/>
<script type="text/javascript"> <!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
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;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('chbox');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var message = document.getElementById('message').value;
var queryString = message ;
ajaxRequest.open("POST", 'chatdata.php', true);
//ajaxRequest.send(null);
ajaxRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajaxRequest.send('queryString');
}
</script>
<?php
$message1 = $_REQUEST['message'];
echo $message;
?>
when i use print_r($message); to see the content of the POST value
this is what i get Array ( [queryString] => ). It has no values.
What could be wrong with my code?
(I would have used jQuery but i'm not well grounded in it yet.)
I fixed some bugs and code start works:
1.
<p id="chbox"></p> <!-- ajaxDisplay need this -->
2.
ajaxRequest.send("message="+queryString); //queryString is variable so without quotes
3.
var_dump($message1); //there was message without 1
Here's how you would do it in jQuery - much simpler:
$('#mybutt').click(function(){
var txt = $('#message').val();
$.ajax({
type: 'post',
url: 'my_ajax_processor_file.php',
data: 'ta=' + txt,
success: function(d){
if (d.length) alert(d);
}
});
}); //END mybutt.click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="message" name="message" style="width:100%;"></textarea>
<input id="mybutt" value="SEND" style="border-radius: 5px 5px 5px 5px;" type='button' />
my_ajax_processor_file.php
<?php
$txt = $_POST['ta'];
$out = 'You sent: ' .$txt;
echo $out;
Here are a bunch of free 5-min video tuts for jQuery
The trouble is with query string. You should put ajaxRequest.send(queryString) instead of ajaxRequest.send('queryString');. Don't use query string just use the name of the variable. It should work!
I've a JSP page which includes a checkbox, so when i try to submit the form using the conventional javascript way of document.forms[0].submit(); the form gets refreshed and the checkbox values are not getting retained.
Can anybody help me on how to send the form value using only AJAX. I don't need the way to send using JQuery.
This is the code I had used for sending using form submit:
function relatedAER(){
......
document.forms[0].literatureSelected.value = litNO + "&";
document.forms[0].opCode.value = "relatedAER";
document.forms[0].target='_self';
document.forms[0].action="<%=request.getContextPath()%>/litaer.do?selected="+selected;
document.forms[0].submit();
}
I hope next time, you'll put some effort, into creating even a simple code, and showing us instead of asking for a script.
Now, that bieng said: This will submit a username to a php file, called fetch.php
HTML
<input type='text' name='user' id='user' /><br/>
<input type='submit' name='submit' onclick='check()' />
<div id='output'></div>
Ajax:
function check(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('output').innerHTML = xmlhttp.responseText;
}
}
get_user = document.getElementById('user').value;
param = "name="+get_user;
xmlhttp.open('POST','fetch.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
</script>
I am try to have a forum submits more then once when a user clicks the submit button. Why? I am try to add more then one idem to a shopping cart, The shopping cart software I am using doesn't support adding more then one product at a time and I don't want to edit there core code. The hidden forum would have the product ids like '1,2,3' I'd then need the JavaScript to separate the values and post each one using AJAX to the cart. I am not great a JavaScript but I coded what I think should work but its just giving me a alert: 'There was a problem with the request.' twice. I can't see whats wrong with it, any and all help and suggestions are welcomed! Here the code:
JS
<script type="text/javascript">
function testResults (form) {
var product_id = form.product_id.value;
var quantity = form.quantity.value;
var brokenstring=product_id.split(",");
for ( var i in brokenstring )
{
var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}
var poststr = "product_id=" + encodeURI( brokenstring[i] ) +
"&quantity=" + encodeURI( quantity );
makePOSTRequest('post.php', poststr);
}
}
</script>
HTML
<form action="javascript:testResults(document.getElementById('myform'));" name="myform" id="myform">
<input type="text" name="product_id" id="product_id" />
<input type="hidden" name="quantity" id="quantity" value="1" />
<br />
<input type="submit" name="button" value="Submit" />
</form>
<span name="myspan" id="myspan"></span>
post.php
<?php
print_r($_POST);
?>
If you want to add two items to the cart shouldnt you be doing two posts with the same item? I can just see one post per item there. You are not taking the quantity into account. But this is not the problem. In this case this is only a logic error.
For the javascript side I would recommend you to use jQuery to treat the ajax stuff because it will make your life WAY easier than regular javascript that might event not work with all browsers.
This is the link related to the POST method of jQuery: http://docs.jquery.com/Post
Hope it helps
It is against all the programming logics to post a form several times instead of having a more complex form. From what I can see or understand from your code you are trying to loop through your splitted (brokenstring) string. Your loop is not constructed where and how it should be. Anyway, if I were you, I would consider migraton to another free cart o the possibility to write one myself. From what I see you will be able to do so with a little bit of help from here.