I have a problem in my code. I've been trying to design a form that could update data in a database and showing it without refreshing the page. I could do this, but I wanted that the form would work if the user pressed the Enter key.
Here is my code:
<form name="chat" id="chat">
<textarea name="message" type="text" id="message" size="63" ></textarea>
<input type="button" value="Send" onClick="send();"/>
</form>
<script>
//This function will display the messages
function showmessages(){
//Send an XMLHttpRequest to the 'show-message.php' file
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","chat.php?jogo=<?php echo $numerojogo;?>",false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","chat.php",false);
xmlhttp.send();
}
//Replace the content of the messages with the response from the 'show-messages.php' file
document.getElementById('chatbox').innerHTML = xmlhttp.responseText;
//Repeat the function each 30 seconds
setTimeout('showmessages()',30000);
}
//Start the showmessages() function
showmessages();
//This function will submit the message
function send(){
//Send an XMLHttpRequest to the 'send.php' file with all the required informations~
var sendto = 'adicionar.php?message=' + document.getElementById('message').value + '&jogador=<?php echo $user;?>' + '&jogo=<?php echo $numerojogo;?>';
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",sendto,false);
xmlhttp.send(null);
document.getElementById("chat").reset();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",sendto,false);
xmlhttp.send();
}
var error = '';
//If an error occurs the 'send.php' file send`s the number of the error and based on that number a message is displayed
switch(parseInt(xmlhttp.responseText)){
case 1:
error = 'The database is down!';
break;
case 2:
error = 'The database is down!';
break;
case 3:
error = 'Don`t forget the message!';
break;
case 4:
error = 'The message is too long!';
break;
case 5:
error = 'Don`t forget the name!';
break;
case 6:
error = 'The name is too long!';
break;
case 7:
error = 'This name is already used by somebody else!';
break;
case 8:
error = 'The database is down!';
}
if(error == ''){
$('input[type=text]').attr('value', '');
showmessages();
}
else{
document.getElementById('error').innerHTML = error;
}
}
</script>
I've tried to put onsubmit instead of onclick but without success :/
EDIT:
Already solved I'm so dumb.. Thank you for the help misko!
Here is my code in case you're having the same trouble as me:
<form name="chat" id="chat" onsubmit="send();return false;">
<input name="message" type="text" id="message" size="63" ></input>
<input type="button" value="Send" onClick="send();"/>
</form>
You will need to add an event listener on that input field. See http://api.jquery.com/keypress/ and my example below.
$( "#message" ).keypress(function( event ) {
if ( event.which == 13 ) {
event.preventDefault();
send();
}
});
If it works onclick I think that onsubmit in <form> should work too:
<form name="chat" id="chat" onsubmit="send();">
<textarea name="message" type="text" id="message" size="63" ></textarea>
<input type="button" value="Send" onClick="send();"/>
</form>
Have you tried that this way?
What about this approach.
Determines if carriage return has been pressed. (Ascii 13)
$(document).ready(function(){
$("form").keydown(function(event){
if(event.which == 13) {
event.preventdefault();
// submit
}
});
});
Related
I'm working on a Stripe API integration and have a simple model that works. I would like to add two more fields for users to fill out, the card holder name and the billing zip code for each transaction. The Stipe token, email address, amount and record_id are all being passed to Stripe's site for validation, and that information is also being sent back to the PHP processing script. Does anyone know what Stripe uses for both the cardholder's name and the zip code? These are options that can be added, but I can't find Stripe's naming convention for these.
HTML
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://checkout.stripe.com/checkout.js"></script>
<div class=“container”>
<form>
<input type="text" onclick="getPrice()" value="Click for Price" />
<!-- This grabs the price determined by a PHP backend process -->
</form>
<br />
<br />
<form id="myForm" action="charge.php" method="POST">
<input type="hidden" id="stripeToken" name="stripeToken" />
<input type="hidden" id="stripeEmail" name="stripeEmail" />
<input type="hidden" id="stripeZipcode" name="stripeZipcode" />
<input type="hidden" id="cardHolder" name="cardHolder" />
<input type="hidden" id="amountInCents" name="amountInCents" />
<input type="hidden" id="record_id" name="record_id" />
</form>
<input type="button" id="customButton" value="Pay" placeholder="$10.00">
</div>
JavaScript
// Get Price Function
function getPrice() {
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 (this.readyState == 4 && this.status == 200) {
// CREATE THE myPromo VAR AND USE promoDct VAR WITH INNERHTML FOR OUTPUT
var myPrice = JSON.parse(this.responseText);
// Create a variable to hold the error message
var errorMes = myPrice.errorMes;
var price = myPrice.price;
// Use a switch statement to output proper info
switch (errorMes) {
case 'Error':
window.alert('Something went wrong.');
break;
case 'No error':
// set the value of the PHP derived charge to JS var
window.charge = price;
break;
}
}
};
xmlhttp.open("POST", "get_price.php", true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send('string');
}
// Stripe API Function
// Convert PHP Instance ID to JS var
var recordNum = "<?php echo $record_id; ?>";
var handler = StripeCheckout.configure({
key: 'pk_test_6fFZO2AWrKR8NqFslGt2POfsahKN5jZg0e',
token: function(token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#stripeZipcode").val(token.zipCode);
$("#stripeHolder").val(token.cardHolder);
$("#amountInCents").val(window.charge);
$("#record_id").val(recordNum);
$("#myForm").submit();
}
});
$('#customButton').on('click', function(e) {
var amountInCents = Math.floor($("#amountInDollars").val() * 100);
var displayAmount = parseFloat(window.charge / 100);
// Open Checkout with further options
handler.open({
name: 'Travelers Free Classifieds',
description: 'Custom amount ($' + displayAmount + ')',
amount: window.charge,
});
e.preventDefault();
});
// Close Checkout on page navigation
$(window).on('popstate', function() {
handler.close();
});
PHP
// BACK END Charge the user's card:
$charge = \Stripe\Charge::create([
'description' => $_SESSION['record_id'],
'amount' => $amount,
'currency' => 'usd',
'source' => $token,
]);
Any help with this will be most appreciated!
Cheers,
Rick
I have an html form. The form sends login request to server. The html response from server is put in an iframe.
$(document).ready(function(){
$("#submit").click(function(event){
$("#dummyframe").on('load',function() {
var myiframe = $("#dummyframe").val();
var iframedocument = myiframe.contentDocument;
var response = iframedocument.queryselector("pre");
var errormessage = '{"code":500,"message":"入力項目に誤りがあります","data":{}}';
if (response == errormessage ){
alert('wrong password');
}
else {
alert('password is ok');
}
});
});
});
<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form method="post" target="dummyframe" action="https://kintai.jinjer.biz/v1/sign_in">
<input name="company_code" type="hidden" value="1234" />
<input name="email" type="hidden" value="1234" />
<input name="password" type="hidden" value="1234" />
<input type="submit" value= "submit" id= "submit" />
</form>
I want to read response from the server to validate password. If I get error message from server, I want to alert "wrong password" in my html page. Am I missing something? It doesn't work. The code doesn't seem incorrect. Your help is greatly appreciated.
You need to change your script to below:
$(document).ready(function(){
$("#submit").click(function(event){
$("#dummyframe").on('load',function() {
var myiframe = $("#dummyframe");
var iframedocument = myiframe.contentDocument;
if (iframedocument.document) iframedocument = iframedocument.document;
var response = iframedocument.queryselector("pre").innerHTML;
var errormessage = '{"code":500,"message":"入力項目に誤りがあります","data":{}}';
if (response == errormessage ){
alert('wrong password');
}
else {
alert('password is ok');
}
});
});
});
Two forms exist, it doesn't matter which one is last, always the last one is submitted.
<script>
function submitall()
{
document.getElementById("form2").submit();
document.getElementById("form1").submit();
}
</script>
Try it this way
HTML
These belong to form1
<input type="text" id="form11" name="i1" />
<input type="text" id="form12" name="i2" />
Let's say this one belonged to form2
<input type="text" id="form21" name="i3" />
Javascript should look something like this
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mypostrequest.responseText // ajax response
}
else{
alert("An error has occured making the request")
}
}
}
function submitForm(page,parameters)
{
mypostrequest.open("POST", page, true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters);
}
var value1=encodeURIComponent(document.getElementById("form11").value);
var value2=encodeURIComponent(document.getElementById("form12").value);
var value3=encodeURIComponent(document.getElementById("form21").value);
var p1="i1="+value1+"&i2="+value2;
var p2="i3="+value3;
var parameters=[p1,p2];
var pages = ['basicform1.php','basicform2.php'];
for(var i=0;i<pages.length;i++)
{
submitForm(pages[i],parameters[i]);
}
I can't seem to figure out how to use ajax to post. I made a silly form to try it out and even after having cut it all the way down to just two values, still can't get anything to work. My html is this:
<html>
<head>
<script type="text/javascript" src="j.js"></script>
<title>Test this<
<body>/title>
</head>
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="submit" value="Submit Form" />
</form>
<div id="status"></div>
</body>
</html>
Then, my external javascript is just a single function so far:
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
While my php just echoes the stuff back:
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
I can't find anything wrong in firebug or in chrome's toolsy thingies..
Can anybody who me what I'm doing wrong?
The whole problem is caused by the fact that you are both submitting the form and performing an AJAX call! status is for sure updated, but in the same moment the page is refreshed (notice that the <input>-values disappear)
Simply avoid the form submit by altering the markup,
<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />
and your code works. Or dont use a form at all. It is to no use when you are AJAXing anyway.
update
I reproduced the whole scenario before answering :
xhr.html
<html>
<head>
<title>Test this</title>
</head>
<body>
<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />
</form>
<div id="status"></div>
<script>
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "xhr.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
console.log(hr);
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</body>
</html>
xhr.php
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
Make the:
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /> <br />
Last Name: <input type="text" name="lname" id="lname" /> <br />
<input type="submit" value="Submit Form" />
</form>
into a button tag:
<form name="testForm">
First Name: <input type="text" name="fname" id="fname" /> <br />
Last Name: <input type="text" name="lname" id="lname" /> <br />
<button type="button" onclick="postStuff();">Submit Form!</button>
</form>
The page refreshes from the form submit as far as I can see. You don't need to use a form if you're using ajax.
Also read: Why is using onClick() in HTML a bad practice? since you're enclosing the post in a function anyway.
EDIT: I just noticed your title and head tags are broken in the source you've put up.
Here's how I do it:
In your html file put <SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></SCRIPT>
Then you can call this function that will call (in my case) queryDB.php script.
function queryDB(db,query,doAfter){
$.ajax({
type: 'POST',
data: { host: "localhost",
port: "5432",
db: db,
usr: "guest",
pass: "guest",
statemnt: query
},
url: 'scripts/php/queryDB.php',
dataType: 'json',
async: false,
success: function(result){
// call the function that handles the response/results
doAfterQuery_maps(result,doAfter);
},
error: function(){
window.alert("Wrong query 'queryDB.php': " + query);
}
});
};
Send post to test.php in the same hierarchy and accept the result in html variable
$.ajax(
{
type: "POST",
url: "test.php",
data: {'test': test, 'name': 0, 'asdf': 'asdf'},
success: function(html)
{
alert(html);
}
});
In PHP of the recipient, specify it as follows
<?php
echo "come here";
echo $_POST['test'];
?>
Directory structure
$ tree
.
├── a.php
└── test.php
reference
https://off.tokyo/blog/ajax%E3%81%A7post%E3%82%92%E5%8F%97%E3%81%91%E5%8F%96%E3%82%8B%E6%96%B9%E6%B3%95/
Perhaps it's best for you to use a library like jquery and then you can do something like : $('form').submit(function(){$.post('detinatnion', $('form').serialize());});
but to answer your question since you have a reason for using pure js then:
<form method="post" action="pathToFileForJsFallback.">
First name: <input type="text" id="fname" name="fname" /> <br />
last name: <input type="text" id="lname" name="lname" /> <br />
<input type="submit" value="Submit Form" />
<div id="status"></div>
</form>
JS:
function postStuff(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
mypostrequest = new ActiveXObject(activexmodes[i]);
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
mypostrequest = new XMLHttpRequest();
else
return false;
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var fname=encodeURIComponent(document.getElementById("fname").value);
var lname=encodeURIComponent(document.getElementById("lname").value);
var parameters="fname="+fname+"&lname="+lname;
mypostrequest.open("POST", "destination.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
Again my recommendation to you is to learn js with a library like jquery, because by the time you learn how to do these stuff, these libraries, hardware and everything will be so fast that javascript code like this will become useless for practical every day use.
u need to return false at the end of the function.
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
return false;
}
I have a very small page being managed by some javascript. When I load the page into the browswer the link after the form (id=login_linker) works fine.
However, when I load it into a div the same link wont work. Does anyone have any ideas.
Here is the body of the page that is being included.
<body>
<p>Forgot your password?</>
<form name="forgotpassform" id="forgotpassform" onsubmit="return false;">
<label for="email">Email: </label>
<input id="email" type="text" class="searchbox" onfocus="emptyElement('status')" maxlength="35">
<input type="button" style="margin-top: 15px; position:relative; left:50px;" id="forgotpassbtn" onclick="forgotpass()" value="Send me a new password">
<br>
</form>
<span id="emailstatus"> </span>
<span id="status"></span>
Log In
</body>
The javascript:
function forgotpass(){
var e = _("email").value;
var status = _("status");
var forgotpassform = _("forgotpassform");
if(e != ""){
_("forgotpassbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "forgotpass.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "no_user"){
status.innerHTML = 'There was no matching email in the system.';
_("forgotpassbtn").style.display = "block";
} else if(ajax.responseText =="email_not_sent"){
status.innerHTML = 'There was a problem sending your temporary password.';
} else {
//status.innerHTML = ajax.responseText;
forgotpassform.innerHTML = "You have sent a temporary password to your email address. Please check your email.";
}
}
}
ajax.send("e="+e);
} else {
status.innerHTML = "Please enter your email address.";
}
}
function emptyElement(x){
_(x).innerHTML = "";
}
function loadlogin(){
$('#loginwindow').toggle(400);
$('#loginwindow').load("forgotpass.php");
$('#loginwindow').toggle(400);
}
$(document).ready(function(){
$(document).on('click', '#login_linker', function(){
alert('ok');
showlogin();
});
});
function showlogin(){
$('#loginwindow').load("login.php");
$('#loginwindow').toggle(400);
}
Here is the script to load the forgot password page ie the HTML above
function forgotpass(){
$('#loginwindow').toggle(400);
$('#loginwindow').load("forgotpass.php");
$('#loginwindow').toggle(400);
}
I don't know how your code to load the link using js is (it would be better if you post it too), but I guess the problem is you try to bind the event just after document is ready, and at that moment, the link isn't loaded yet. Bind it after loading it.