I have a PHP script, which connects to the DB, does a simple select and returns a single number back. The script works fine, I can test it by adding
action="search_ODtime.php" method="POST"
to my form. But the whole thing does not work. The whole page is getting refreshed and I am getting nothing back. I killed the whole day trying to figure out what is wrong here. Does anyone have any idea?
My html file:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#time_search').bind('submit', function() {
var origin = $('#origin').val();
var destination = $('#destination').val();
alert(origin);
$.ajax({
type: "POST",
url: "search_ODtime.php",
data: 'origin=' + origin + '&destination=' + destination,
success: function(data) {
$('#search_results').html(data);
}
});
});
});
</script>
</head>
<fieldset style="font-size:11pt; opacity: 1; color: white;">
<form id="time_search">
Orinig:
<input name="origin" id="origin" type="number" value="1" min="1" max="97">
<br>
Destination:
<input name="destination" id="destination" type="number" value="1" min="1" max="97">
<br>
<input type="submit" value="Get travel time" name="submit" id="submit" style="border-radius: 5px; display: block; margin: 10px auto 10px 0;">
</form>
Travel time:
<div id="search_results">
</div>
</fieldset>
</body>
</html>
What's happening is your form is getting submitted. You can either: a) remove the form entirely and change the submit button to a regular button, then bind your event to the button instead of the form, or b) prevent the form from submitting.
jQuery passes the event object to every event handler. The event object has a method called preventDefault() which prevents, well, the default action, whether it's submitting a form or linking to a page or whatever.
You need to pass the event into the function by adding a variable for it, and then call it's preventDefault() method to prevent the form from submitting and your page being refreshed.
$('#time_search').bind('submit',function(event) {
event.preventDefault();
var origin = $('#origin').val();
var destination = $('#destination').val();
alert (origin);
$.ajax({
type:"POST",
url:"search_ODtime.php",
data: 'origin='+origin+'&destination='+destination,
success: function(data){ $('#search_results').html(data); }
});
});
Some things to mention:
First:
When submitting a form via AJAX you need to prevent the browser from its default submitting behaviour and thus from refreshing the page.
('#time_search').bind('submit',function(e) {
e.preventDefault();
Second:
Try sending your data in the JSON format eg. {"origin": origin, "destination": destination}
Related
I am new here. I want my code to submit form without submit button. My code run like this:
Every time when user input data in input text and press enter, the result will be display on the same page just below input text. This code will work perfectly is I use submit button to submit data. Can anyone help me with this ? Thanks in advance.
This is my result.html
$(document).ready(function(){
$("#code").change(function(){
var st = '';
$('#Myform input[type=text]').each(function(){
st = st+ '<td>'+$(this).val()+'</td>';
$(this).val('');
});
$('#result').append('<tr>'+st+'</tr>');
});
});
html
<form id="Myform">
<table>
<tr>
<td>
<p>Code:</p>
</td>
<td><input id="code" type="text" name="code" size="40" autofocus/></td>
</tr>
</table>
</form>
<table id="result"></table>
This is my code.php
<?php if( $_REQUEST["code"] ) {$code = $_REQUEST['code'];}?>
A cursory Google search would have brought up that jQuery provides a means of doing this.
You can trigger form submission via either the submit() or trigger() methods, i.e.
$('#Myform').submit()
or
$('#Myform').trigger('submit')
The former is merely a shortcut method to the latter.
how are you?
If you need to send to another php page, you can to send AJAX, if don't want to send, you can show data directly to your js, without ajax.
https://jsfiddle.net/5L9Leso8/
UPDATE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>teste</title>
</head>
<body>
<div>
<label for="test">
<input type="text" name="test" id="test">
<p id="rest"></p>
</label>
</div>
<script>
$('#test').on('change', function(e) {
e.preventDefault();
var self = $(this);
/** if you don't need to send to your php code
$('#rest').html(self.val());
**/
if (self.val().length > 0) {
$.ajax({
url: 'yourUrlphp',
type: 'post',
data: {
yourText: self.val()
},
success: function(data) {
$('#rest').html(data);
}
});
}
});
</script>
</body>
</html>
first post. PHP noob. I'm surprised at how difficult this has been...
I have an html form (index.html) with a submit button that posts to a php file (sendemail.php).
The php file is set to collect form data and send it via email to an address I specify.
I would like to display a success icon next to the submit button when this email is sent. (Honestly, there is no fail condition, so I would be happy with just displaying the success icon when the user clicks Submit, so they know not to keep clicking Submit).
I have tried a number of approaches after reading this and many other forums. I've been at this for two days and could use some help.
Here's some snippets below. I'm basically just trying to detect the email being sent in the php file, then sending a flag ($val) using echo json_encode back to the HTML page. I'm trying to capture it using the javascript with an onload trigger, and then trying to use the javascript to manipulate the DIV visbility when the page is refreshed after the submit action is completed.
It processes the php but it doesn't seem to reach the Header line to reload the html page. It just refreshed the screen and shows the word "inline" and nothing else.
I'm stumped. Please help! Thanks
sendmail.php
// Check, if message sent to your email
// mark success or fail then refresh page
if($send_contact){
$val="inline";
echo json_encode($val);
}
else {
echo "Error";
}
if($send_contact){
header('location:index.html');
}
else {
echo "Error";
}
?>
javascript in html
<script type="text/javascript">
function success(){
var val = <?php echo json_encode($val); ?>;
document.getElementById('success').setAttribute('display', val);
}
window.onload = success;
</script>
HTML DIV I'm trying to control
<div style="text-align: left; font-weight: bold; color:#000000; display:val;"
class="success" id="success" name="success"><img src="success.png"
height="25px">Event added! It may take 20 minutes to appear on
the calendar. </div>
UPDATE:
Ok I tried manRo's suggestion and was able to get the behavior I wanted out of the green checkmark...it would be hidden on page load and then appear when it received the 200 status message from the PHP file.
However when I try to build this logic into my ajax something is breaking and the form data is no longer submitting, and the green checkmark logic stops working.
Allow me to run through my updates:
Currently my script header looks like this:
<script type="text/javascript" src="util-functions.js"></script>
<script type="text/javascript" src="clear-default-text.js"></script>
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
I've got an onload in the body to call a function to set the green checkmark to "hidden", just to keep things tidy:
<body onload="setdisplay()">
Calling this function:
<script>
function setdisplay();
document.getElementById("success").style.display = "none";
</script>
I get my form started like this now:
<form id="main" name="main" action="">
Here's an example input:
<td style="text-align: right; "> <br>
</td>
<td><input id="title" name="title" value="Event title" class="cleardefault rounded"
required="true" type="text"> </td>
The form submit button, which currently is type=button
<input style="background-color: #99d6ff; text-align:center;
font-weight: bold;" value="Add event" id="addevent" name="addevent" onclick="processmain();"
class="button" type="button">
This is the DIV I need to make visible or hidden depending on success:
<div style="text-align: left; font-weight: bold; color:#000000; display:none;"
class="success" id="success" name="success"><img src="success.png"
height="25px"></div>
Now the beefy part....I've tried integrating your manRo's suggestions into my main form processing script, as part of the ajax "success" state:
<script>
}
function processmain()
{
// event.preventDefault();
var title = $("input#title").val();
var location = $("input#location").val();
var startdate = $("input#startdate").val();
var starttime = $("input#starttime").val();
var enddate = $("input#enddate").val();
var endtime = $("input#endtime").val();
var other = $("input#other").val();
$.ajax({
url: "sendemail.php",
type:'POST',
data:
{
title: "title",
location: "location",
startdate: "startdate",
starttime: "starttime",
enddate: "enddate",
endtime: "endtime",
other: "other"
},
success: function(event)
{
$.get('sendmail.php', function(data) {
document.getElementById("success").style.display = "inline";
})
}
});}
</script>
At the moment:
The form data is not passed to the php
The green checkmark does not show
The screen is no longer refreshing (because button type=button now, instead of submit).
I feel like I am close. I need to get the form data sent to the php so the email is sent. I need the page to not refresh so I can properly introduce the green checkmark.
Please take a look at how I'm implementing your solution in my code and let me know what I'm doing wrong. Thank you!!
What you want is HTML form with ajax call to php script that will return 200 http status code on success.
I will try to explain you that on very simple example.
Please take a look at below html file:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
</head>
<body>
<form action="sendmail.php">
<input type="email" name="email"/>
<input type="submit"/>
</form>
<script>
$(document.forms[0]).submit(function(event) {
event.preventDefault();
$.get('sendmail.php', function(data) {
alert('all good');
});
});
</script>
</body>
</html>
sendmail.php in that case should contain code responsible for sending email eg:
<?php
//code here...
if ($email_sent) {
http_response_code(200);
} else {
http_response_code(400);
}
This is my code:
<html>
<body>
<?php
include('header.php');
?>
<div class="page_rank">
<form name="search" id="searchForm" method="post">
<span class="my_up_text">ENTER THE WEBSITE TO CHECK GOOGLE PAGE RANK:</span>
<br /><br />
<input type="text" name="my_site"/></form></div>
<div class="p_ity">
PAGE RANK</div>
<div id="my_pass"></div>
<script>
function sub_form()
{
document.forms["search"].submit();
}
$(function () {
$('form#searchForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'check-google-page-rank.php',
data: $('form').serialize(),
success: function (data) {
$('#my_pass').html(data);
}
});
e.preventDefault();
});
});
</script>
</body>
</html>
The problem is the ajax post works perfect if I use a submit button in the form.It doesn't work if I use a sub_form() method to submit the form after on click event.My doubt is will the java script sub_form() method trigger the jquery ajax function or not?
Note:
The data returned by the post url is
echo "<img width=\"165\" height=\"55\" src=\"./images/page-rank/pr".$rank.".gif\" />"
document.forms[].property
This returns an array of all the forms in the current document.
Since it is a array, you should pass the index value as integer.
document.forms[0].submit();
this will submit the form, if you have this form as your first form in the html page from top.
I am creating a team registration form. and the required condition is that user must be already registered and can choose only registered members in the team.
for checking user existence in database i am using email.
The form contains multiple email fields triggered by a button that adds a field in the form
I need to check for all user's existence when user types in the respective email field using ajax call and display the result in <span class='form_hint'></span>
The form is contained in a hidden div and is called by colorbox
but it doesn't seem to work somehow
Here's my html code:
Update: Now Working fine
<!DOCTYPE html>
<html dir="ltr" lang="en-US"> <head>
<title>Event Description </title>
<meta charset="UTF-8"/>
<!--Colorbox-->
<link rel="stylesheet" media="screen" href="colorbox/css/styles.css" >
<link rel="stylesheet" media="screen" href="colorbox/css/colorbox.css" >
<script src="colorbox/js/jquery.min.js"></script>
<script src="colorbox/js/jquery.colorbox.js"></script>
<script>
$(document).ready(function(){
$(".register").colorbox({inline:true,maxHeight:"95%", maxWidth:"90%"} );
});
</script>
<!--Colorbox ends-->
</head>
<body>
<a class="register" href="#register">Event Registeration</a>
<script type="text/javascript">
function usercheck(){
$(document).ready(function(){
$('input[type="email"]').keyup(function() {
var name = $(this).val();
if(name=="")
{
$(".form_hint").html("");
}
else
{
$.ajax({
type: "POST",
url: "user_check.php",
data: { email: name } ,
success: function(html){
$(".form_hint").html(html);
}
});
return false;
}
});
});
}
</script>
<div style='display:none'>
<div id='register' style='padding:10px; background:#fff;'>
<center>
<form class="contact_form" action="../../register/register.php" method="post" name="contact_form">
<ul>
<li>
<h2>Registration</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="email">Email:</label>
<input type="email" name="email" placeholder="mail#example.com" onkeyup="usercheck();" required />
<span class="form_hint">Proper format "mail#example.com"</span>
</li>
<span id="dynamicInput"></span>
<li><input type="button" value="+" onClick="addInput('dynamicInput');"/></li>
<li>
<button class="submit" type="submit">Register</button></h4>
</li>
</ul>
</form></center>
</div>
</div>
<script type="text/javascript">
function addInput(liName){
//var counter=1;
var newfield = document.createElement('li');
newfield.innerHTML = "<label for='email'>Email:</label><input type='email' name='email[]' onkeyup="usercheck();" placeholder='mail#example.com' /><span class='form_hint'></span>";
document.getElementById(liName).appendChild(newfield);
}
</script>
</body>
</html>
PHP code to check users in Database:
<?php
include('connect.php');
if(isset($_POST['email']))
{
$name=$_POST['email'];
$query=mysql_query("select * from user_details where email='$name'");
$row=mysql_num_rows($query);
if($row==1)
{
echo "Okay Pal!";
}
else
{
echo "User doesn't exist";
}
}
?>
I don't know where the error is as i am implementing it using dynamic fields for very first time
Also i want to know a good method to handle multiple email fields like i am using above.
I dont think your IF-Statement in your PHP-Code is executed.
You're checking for an email-parameter, but your ajax-data looks like data: "name="+ name
Try to change it to data: { email: name },
First of all selector $('#email[]') is invalid. Try adding some class to the email input or use this selector $('input[type="email"]') to add event handler to all email fields.
Next thing is keyup handler. Inside handler function you can use $(this) instead trying to select field again.
The last one consider using JSON as the data exchange type. On the server return string like: {registered:true} and on the client parse it as a JSON in the jQuery.ajax function setting dataType to JSON.
The Above code is now fully functional.
Earlier only 1st field was calling the function and checking through php. so as to resolve it, I added a
function usercheck(){}
to handle the user interactions.
And on every key up on <input type='email'> I added onkeyup() function that triggers usercheck() as:
<input type='email' name='email[]' onKeyUp='usercheck();'>
and result of the query is displayed within <span> with every <input type='email'> field
Thank you everyone for your valuable responses :) You made my day!
I was trying to write a script that checks the second text field if it has the same data as that in the first field.When the user enters in the second text field the script keeps telling him if he is going right.If he makes a mistake immediately the script points out by setting the label equal to "emails do not match".
Bu i have not been successful till now.
script :
window.onload = startChecker;
function startChecker() {
//while(true) {
if( document.getElementById("first_field").value != "" ) {
var idFromFirstField = document.getElementById("first_field").value;
if(idFromFirstField != document.getElementById("second_field").value ) {
document.getElementById("alert_message").value = "Incorrect Email ! ";
} else {
document.getElementById("alert_message").innerHTML = "Two emails match !";
}
}
//}
}
In case this is a HTML file :
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="cross_checker.js">
</script>
<title>Untitled Document</title>
</head>
<body>
<form>
<label>Email<input type="text" id="first_field" /></label> <br /> <br />
<label>Verify your Email<input type="text" id="second_field" /></label>
<label id="alert_message" value="" style="color:#CC0000"></label>
<!--the above label outputs if the user is entering the same id !--->
<br /> <br />
<input type="submit" value="submit" style="color:#CC0000"/>
</form>
</body>
</html>
Earlier i was trying to use an infinite while loop but that hangs the browser and sometimes the browser keeps fetching the page.
How can i improve this script so that i am able to instantly check if the user is going right or wrong ?
Add a keyup handler to the input element. In the HTML code, add onkeyup="startChecker();".
Using JavaScript, you can dynamically assign event handlers, in this way:
if(window.addEventListener) element.addEventListener("keyup", startChecker, true); //All major browsers
else if(window.attachEvent) element.attachEvent("onkeyup", startChecker);
else element.onkeyup = startChecker;
//Where element refers to the HTML element.