Im trying to build a form which uses AJAX but its failing to execute properly heres the code of my first file:
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(fn);
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Todo: <input id="first_name" name="first_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();">
<br /><br />
<div id="status"></div>
</body>
</html>
and heres the second:
<?php
echo $_POST['firstname'];
?>
All it does is show the "processing..." and then it goes blank...any way around this?
I think it's because you're not passing a key value pair.
hr.send('firstname=' + encodeURIComponent(fn));
Related
We have a set up with multiple forms on a single page. We are rendering each recaptcha successfully, however I'm struggling to invoke the recaptcha challenge programatically targeted to an ID.
Looking at the docs (https://developers.google.com/recaptcha/docs/invisible#programmatic_execute) my understanding is that I can pass an ID with the execute command so the response is filled into g-response within the correct form, otherwise the response defaults to the first g-response it finds on the page (which is no good for anything other than the first form on the page).
I've tried it with a slightly modified version of Googles own example, however we get the error message 'Invalid site key or not loaded in api.js: recaptcha123' even though the key is correct.
Does anyone have any idea how we might get this working?
<html>
<head>
<script>
function onSubmit(token) {
alert('thanks ' + document.getElementById('field').value);
}
function validate(event) {
event.preventDefault();
if (!document.getElementById('field').value) {
alert("You must add text to the required field");
} else {
grecaptcha.execute('recaptcha123');
}
}
function onload() {
var element = document.getElementById('submit');
element.onclick = validate;
}
</script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form>
Name: (required) <input id="field" name="field">
<div id="recaptcha123" class="g-recaptcha"
data-sitekey="XXXXXXXXXXXXXXXX"
data-callback="onSubmit"
data-size="invisible"></div>
<button id="submit">submit</button>
</form>
<script>onload();</script>
</body>
</html>
The following code works:
<html>
<head>
<title>reCAPTCHA demo: Explicit render after an onload callback</title>
<script>
var onSubmit = function(token) {
console.log('success!');
};
var onloadCallback = function() {
widgetId1 = grecaptcha.render('recaptcha', {
'sitekey' : 'XXXXXXXXXXXXXXXXXX',
'callback' : onSubmit
});
};
</script>
</head>
<body>
<script src="/wp-content/themes/kc_water_care_services/js/pristine.min.js"></script>
<form action="?" method="POST" id="contactForm">
<div class="form-group">
<label for="name">Name (required)</label>
<input type="text" required data-pristine-required-message="Please enter your name"
id="name" name="name" />
</div><!--/.form-group-->
<div id="recaptcha" data-size="invisible"></div>
<input id="submit" type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
</script>
</body>
</html>
<script>
var form = document.getElementById("contactForm");
// create the pristine instance
var pristine = new Pristine(form);
form.addEventListener('submit', function (event) {
event.preventDefault();
// check if the form is valid
var valid = pristine.validate(); // returns true or false
if(valid == true){
grecaptcha.execute(widgetId1);
}
});
</script>
Turns out the id doesn't refer to the css ID, it refers to an ID created when you use the render function.
I created the main page that has 2 datepickers and 1 input mask for time. A button will trigger a GET request for a page with the same content to be loaded within a div. I have put all the js, CSS and function script on the main page.
At the main page, all the datepickers and input mask work correctly but the GET request got trigger and the new page is loaded, all the datepickers and input mask are not working.
Please help.
Date Picker and Input Mask Not Working
The MAIN PAGE Code
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- IN SUBFOLDER PLUGIN -->
<!-- Date Picker -->
<link rel="stylesheet" href="plugins/datepicker/datepicker3.css">
<!-- JQuery 2.2.3 Compressed -->
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- datepicker -->
<script src="plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
</head>
<body>
<form name="form1">
<label>Date : </label>
<div>From :<input name="dt_DateFr" type="text" date-picker></div>
<div>To : <input name="dt_DateTo" type="text" date-picker></div>
<div>Time: <input id="txtOTOut" name="txtOTOut" type="text"
data-inputmask="'alias': 'hh:mm'" data-mask>
</div>
<button type="submit" id="btnShow" name="btnShow"
onclick="showContent();return false;">
Show</button>
</form>
<br />
<br />
<div id="content2" style="display: none">
<!-- CONTENT HERE -->
</div>
<script>
$(function () {
//Date picker
$("[date-picker]").datepicker({
format: "dd/mm/yyyy",
autoclose: true,
}).datepicker("setDate", new Date());
});
$(function () {
//Time mask
$("[data-mask]").inputmask();
});
$(function () {
$("#btnShow").click(function () {
$("#content2").show();
});
});
</script>
<script>
function showContent() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("content2").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ax_test.asp?", true);
xhttp.send();
}
</script>
The GET REQUEST Page ax_test.asp
<form name="form2">
<label>Date : </label>
<div>From :<input name="dt_DateFr" type="text" date-picker></div>
<div>To : <input name="dt_DateTo" type="text" date-picker></div>
<div>Time: <input id="txtOTOut" name="txtOTOut" type="text"
data-inputmask="'alias': 'hh:mm'" data-mask>
</div>
</form>
Manage to get it working by including the jquery in the showContent()
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- ALL script in subfolder plugins -->
<!-- Date Picker -->
<link rel="stylesheet" href="plugins/datepicker/datepicker3.css">
<!-- JQuery 2.2.3 Compressed -->
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- datepicker -->
<script src="plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
</head>
<body>
<form name="form1">
<label>Date : </label>
<div>From :<input name="dt_DateFr" type="text" date-picker></div>
<div>To : <input name="dt_DateTo" type="text" date-picker></div>
<div>Time: <input id="txtOTOut" name="txtOTOut" type="text"
data-inputmask="'alias': 'hh:mm'" data-mask>
</div>
<button type="submit" id="btnShow" name="btnShow"
onclick="showContent();return false;">
Show</button>
</form>
<br />
<br />
<div id="content2" style="display: none">
<!-- CONTENT HERE -->
</div>
<script>
$(function () {
//Date picker
$("[date-picker]").datepicker({
format: "dd/mm/yyyy",
autoclose: true,
}).datepicker("setDate", new Date());
});
$(function () {
//Time mask
$("[data-mask]").inputmask();
});
$(function () {
$("#btnShow").click(function () {
$("#content2").show();
});
});
</script>
<script>
function showContent() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("content2").innerHTML = xhttp.responseText;
$("[data-mask]").inputmask();
$("[date-picker]").datepicker({
format: "dd/mm/yyyy",
autoclose: true,
}).datepicker("setDate", new Date());
}
};
xhttp.open("GET", "ax_test.asp?", true);
xhttp.send();
}
</script>
</body>
</html>
So, here's some background: I am working on a MEAN stack app for my school where we can read and post our Galaga and Dig Dig highscores to a mongo database.
I am getting an error:
POST http://url.com/api/scores 500 (Internal Server Error)
TypeError: Cannot read property 'userName' of undefined at /app/server.js:37:22
server.js:37 is:
app.post("/api/scores", function(req, res){
Score.create({
name:res.body.userName,
game:res.body.game,
points:res.body.userPoints
});
});
The index.html that the res.body.* is coming from is:
<!DOCTYPE html>
<html ng-app="nameOfApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="core.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<div class="jumbotron text-center">
<div class="container">
<h1>HelpDesk Gaming Leaderboard</h1>
</div>
</div>
<div class="container">
<table>
<tr>
<td><b>Name</b></td>
<td><b>Score</b></td>
</tr>
<tr ng-repeat="score in scores">
<td>{{score.name}}</td>
<td>{{score.points}}</td>
</tr>
</table>
</div>
<br/>
<h2>Score?</h2>
<form>
<input name="userName" type="String" class="form-control" id="userName" ng-model="formData.userName" placeholder="Your Name">
<input name="game" type="String" class="form-control" id="game" ng-model="formData.game" placeholder="The game?">
<input name="userPoint" type="Number" class="form-control" id="userPoint" ng-model="formData.userPoint" placeholder="Points?">
<button type="submit" class="btn btn-default" ng-click="createScore()">Submit</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js">
</script>
</body>
</html>
and the core.js, which is the angular piece is:
var nameOfApp= angular.module('nameOfApp', []);
nameOfApp.controller("mainController", ["$scope", "$http", function($scope, $http) {
$scope.formData = {};
// when landing on the page, get all scores and show them
$http.get('/api/scores')
.success(function(data) {
$scope.scores = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.createScore = function() {
$http.post('/api/scores', $scope.formData)
.success(function(data) {
$scope.formData = {};
$scope.scores = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}]);
Thanks for your input, and if there are any stylistic things that I have wrong, I would love to hear them. I am trying to get better at MEAN stack development.
It's not res.body.* you want to use in your Score.create method, you want to be using req.body.*. 'req' is what has all the data from your http request.
Should be:
app.post("/api/scores", function(req, res){
Score.create({
name:req.body.userName,
game:req.body.game,
points:req.body.userPoints
});
});
I have search already on google and come empty handed because all the answer that I found are not working for me for some reason, maybe there is someone out there that can look at my codess:
<html>
<head>
<meta charset="utf-8">
<title>jQuery Adapter — CKEditor Sample</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="ckeditor.js"></script>
<script src="adapters/jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
CKEDITOR.disableAutoInline = true;
$( document ).ready( function() {
$( '#editor1' ).ckeditor(); // Use CKEDITOR.replace() if element is <textarea>.
$( '#editable' ).ckeditor(); // Use CKEDITOR.inline().
} );
function setValue() {
$( '#editor1' ).val( $( 'input#val' ).val() );
}
</script>
</head>
<body>
<form id="f1" action="some.php" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Title:</td>
<td><input type="text" name="articletitle" id="articletitle" required/></td>
</tr>
<tr>
<td>Featured Image:</td>
<td><input name="MAX_FILE_SIZE" value="2097152" type="hidden">
<input name="image" id="image" type="file" required/></td>
</tr>
<tr>
<td colspan="3"><textarea cols="80" id="editor1" name="editor1" rows="10"></textarea></td>
</tr>
<tr>
<td><input id="save" type="submit" value="Save"></td>
<td><button id="reset">RESET</button></td>
</tr>
</table>
</form>
<script type="text/javascript">
$(document).ready(function(){
var options = {
success: function(){
//$("#articletitle").val("");
alert('HELLO');
}
};
$('#f1').ajaxForm(options);
//$("#button").click(function(){
// $('#f1').clearForm();
// alert("Successfully Added Record");
//});
});
</script>
</body>
</html>
I just want my user to have an alert so that they are aware that their form has been submitted.
If You want to show some of the message inside Ajax callback function You have to return some values in some.php using 'echo' and you have to put die();
eg.
echo '1'; die();
In jQuery You have to do like this:
$('#f1').ajaxForm(function(result){
if(result)
{
alert('Success');
});
// this is the id of the submit button
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
I have a problem with AJAX , I cant find a good solution to refresh only my div "chatwindow" every second. I have tried many posts from stackoverflow and from google.
Can someone help me... to make this.
So far my code
<!DOCTYPE HTML>
<?php
include 'config.php';
?>
<html>
<head>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</script>
</head>
<body>
<div class="container">
<div id="chatwindow">
<?php
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
</div>
<div class="inputMessage">
<form method="post">
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="submit" value="verstuur" name="submit"/>
<input type="text" value="" name="username" />
</form>
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
</div>
</div>
</body>
</html>
[1]: http://chaotix.nl/chat/ "chat"
first you have to download latest jquery file from http://code.jquery.com/jquery-1.7.1.js
put this
<script type="text/javascript" src="jquery-1.7.1.js"></script>
under the head section
now put below code after <script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function(){
$.ajax({
url: 'chat.php',
type: "POST",
data: "",
cache: true,
success: function(response){
$("#chatwindow").html(response);
}
}, 1000);
});
</script>
you should extract php code form chatwindow div into another file and call it with AJAX and setInterval function every second.. if you wish to do it in this way.
This would be
chat.php
<?php
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
Then you would have your main file from which you would call ajax and refresh div:
<!DOCTYPE HTML>
<?php
include 'config.php';
?>
<html>
<head>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</script>
</head>
<body>
<div class="container">
<div id="chatwindow">
</div>
<div class="inputMessage">
<form method="post">
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="submit" value="verstuur" name="submit"/>
<input type="text" value="" name="username" />
</form>
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
</div>
<script type="text/javascript">
$(document).ready(function(){
setInterval ( "get()", 1000 );
});
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatwindow").html(data);
}
});
}
</script>
</div>
</body>
</html>
Try this one
<html>
<head>
<script langauge="javascript">
var counter = 0;
window.setInterval("refreshDiv()", 5000);
function refreshDiv(){
counter = counter + 1;
document.getElementById("test").innerHTML = "Testing " + counter;
}
</script>
</head>
<body>
<div id="test">
Testing
</div>
<div id="staticBlock">
This is a static block
</div>
</body>