I have a problem with my very simple chat. The page is constanly refreshing with AJAX with an timeout of 750ms. If I press or use enter to submit my 'reaction', the page refreshes: is there an way to remove that, so that you can instantly see what you've posted?
You can see the chat at my website: chat
The code:
Index.php
<!DOCTYPE HTML>
<?php include 'config.php'; ?>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.js">
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}
</script>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="chatwindow">
</div>
<div class="inputMessage">
<form method="post">
enter code here
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="text" value="" name="username" />
<input type="submit" value="verstuur" name="submit" onKeyPress="return submitenter(this,event)" />
</form>
<?php include 'send.php'; ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
setInterval ( "get()", 750 );
});
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatwindow").html(data);
}
});
}
</script>
</div>
</body>
</html>
chat.php
<?php
include 'config.php';
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
send.php
<?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>';
}
}
?>
if my question is not clear say it please.
And is there a topic/question/post about good spacing? google translated it as "indent".
Thanks
Replace
<form method="post">
With
<form onsubmit="event.preventDefault()" method="post">
You may also use your callback function here like:
<form onsubmit="event.preventDefault();return submitenter(this,event);" method="post">
Working demo: http://jsfiddle.net/usmanhalalit/5RCwF/2/
Add e.preventDefault(); in JS.
Your desired action is to prevent the onSubmit action as the other answers have mentioned. Currently your script isn't quite ready to block submit as you don't have an ajax post method.
You need ajax functionality for the submission side of the application still. For this you can use jQuery post().
You want to create something like
function send() {
$.post(); // Fill in appropriate post() code.
return false;
}
And then call it from your event handlers like onsubmit="return send()" and in place of myfield.form.submit() in your keypress handler.
Related
I am wanting to submit a form using ajax to go to my page 'do_signup_check.php'.
There it will check the email address the user entered against the database to see if there is a match.
If there is a match I want my ajax form to redirect the user to the login.php page.
If there isn't a match I want it to load my page 'do_signup.php'
for some reason the code seems to be doing nothing. Please can someone show me where I am going wrong?
My Ajax form:
<html lang="en">
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
<?php include 'assets/config.php'; ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
</head>
<body>
<div class="sign_up_contain">
<div class="container">
<div class="signup_side">
<h3>Get Onboard.</h3>
<h6>Join the directory.</h6>
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName = $_POST["name"];
$myEmail = $_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($check) > 0) {
echo '1';
} else {
echo '0';
}
?>
Try to use input id 'submt' to trigger the form as such :
$("#submt").click(function(){
e.preventDefault();
//your logic
You have not included the jquery in your page, the function is also missing the closing parentheses.
Include the jquery at the top
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Replace your function with the following code:-
<script>
$(function () {
$('form').on('submit', function (e) {alert(123);
e.preventDefault();
$.ajax({
type: 'post',
url: 'receive-callback.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
});
}
}
});
});
});
</script>
After receiving success in Ajax and doing all necessary logic (fadeOut etc) just relocate user to login.php:
window.location.href = 'path/to/login.php';
Otherwise, in error function (it is goes just after success function) do the next:
window.location.href = 'path/to/do_signup.php';
Upd:
In case you want to have some piece of code from another file, you can use jQuery method load.
$('#some-selector').load('path/to/course/login.php');
It's a very basic example of using 'load', go google around it to explore more.
Please Try this code.
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function (result) {
if(result == 0){
window.location.href = 'do_signup.php';
}else{
window.location.href = 'login.php';
}
});
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($check) > 0){
echo json_encode(array('result'=>'1'));
exit;
}else{
echo json_encode(array('result'=>'0'));
exit;
}
?>
I hope this will work for you.
can anyone tell me how to retrieve data from database and display it in text box in html by using php ajax and jquery? it will just only display if the button is click. Thanks for helping!
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>registion</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function () {
$('#btn').click(function () {
$.post(
'checkUserName.php',{
username:$('#username').val()
},function(data,textStatus){
$('#result').html(data);
});
});
});
</script>
</head>
<body>
<h1>registion</h1>
<form action="" method="post">
userNameļ¼<input type="text" name="username" id="username">
<input type="button" value="Verify userName" id="btn">
<br>
<span id="result"></span>
</form>
</body>
</html>
checkUserName.php
<?php
$uname = $_POST['username'];
$conn = mysqli_connect('localhost','root','root','db_user');
$query = "SELECT * from tb_user where name = '$uname' ";
$result = mysqli_query($conn,$query);
$nums = mysqli_num_rows($result);
//echo $query;
//echo $nums;
if($nums > 0){
echo "Username already exist";
}else{
echo "Username OK";
}
mysqli_close($conn);
Next time please post together what have you done so far. From there only the community will be able to help you.
HTML Code :
<input type="text" id="input-box">
<button type="button" id="btn_get">Click</button>
Ajax Code :
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box').val(data);
}
});
});
PHP Code :
//get data from db here
$data = 'foo';
echo $data;
I have a HTML form which reads some data and saves in the text file with help of PHP. The form's HTML code looks like below.
What is happening now:
1. once i click on submit button it redirects to the 'myprocessing.php'
2. successfully saving in data.txt
The help i required on
1. when i click on submit it shouldn't redirect me to the php page, it should stay on the HTML form page
2. it should show the php file's output on the same HTML page
In simple words, I want to stay on the HTML page itself. Since I'm pretty new to HTML and PHP, struggling much to do these. Thanks in advance :-)
<html>
<head>
<title></title>
</head>
<body>
<form action="myprocessing.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
</body>
</html>
This is my data prcoessing PHP file.
<?php
echo "starting...";
if(isset($_POST['myTextBox']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
echo "Ended...";
}
else {
die('no post data to process');
}
?>
Try below. Call refresh_div() on button click :-
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'YOUR PHP page url',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
}
</script>
Write php code in same html file and use isset() function to check for $_POST data
Try this
<?php
if(isset($_POST['field1']) && isset($_POST['field2']))
{
echo "starting...";
if(isset($_POST['myTextBox']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
echo "Ended...";
}
else {
die('no post data to process');
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="current_page.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
</body>
</html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST" name="testForm" id="testForm">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
<div class="result"></div>
</body>
</html>
add the name and id for form tag. if you keep action as blank, it will submit your form to current page itself.
You need a ajax call to perform as per your requirement.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$( "#testForm" ).on( "submit", function( event )
{
$.ajax({
url:'myprocessing.php',
type:'POST',
data: $("#testForm").serialize()
success:function(results) {
jQuery(".result").html(results);
}
});
return false;
});
</script>
Dont forget to put a return false at the end. If we dont put return false, it will submit your form after the ajax call.
I am using Pure JS to first prevent the form from submitting then I have some validation code and finally automatic submission but the data is not passing from client side to server script.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Chat Room</title>
<link type="text/css" href="main.css" rel="stylesheet" />
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="container" class="add-nick">
<h3>Enter Your Name</h3>
<form action="chat.php" method="post" id="add-nicki">
<input type="text" placeholder="At least 6 alphabets e.g. Jackson" class="text" name="name" />
<input type="submit" value="Submit" class="submit" name="btnsubmit" />
</form>
</div>
</body>
</html>
The JS:
window.onload = function() {
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var regexp = new RegExp("^[A-Za-z]+$"),
elem = this.elements[0],
value = elem.value;
if(regexp.test(value) && typeof value != "null" && value.length > 5) {
elem.className = "text correct";
var formElem = this;
setTimeout(function() { formElem.submit(); }, 0);
}
else elem.className = "text wrong";
};
};
The PHP file:
<?php
session_start();
if(isset($_POST['btnsubmit'])) {
$_SESSION['name'] = $_POST['name'];
echo $_SESSION['name'];
}
else {
if(!isset($_SESSION['name']))
echo "Header";
else
echo $_SESSION['name'];
}
?>
Is there something wrong or JS submit function is not functioning properly ?
The request parameter corresponding to a submit button is only passed if the form is submitted as a result of clicking that button. That's not the case here since you suppress the original form submit (the one triggered by the button), then later call formElem.submit() from JavaScript; no button click means no request parameter, and therefore isset($_POST['btnsubmit']) in your PHP script won't ever return true.
One solution might be to add the btnsubmit parameter to the form's action before submitting it:
formElem.action += (formElem.action.indexOf('?') == -1 ? '?btnsubmit=Submit' : '&btnsubmit=Submit');
I'm trying to display data from mysql on the same page that i've got my form with checkboxes. The question is how to write js script that gonna display it.
The code is:
<form id="myForm" action="pdoakcja.php" method="post">
<!--Instruktor: <input type="text" name="name" /> -->
Permissions:<input type="checkbox" name="M1" value="M1" />M1
<input type="checkbox" name="M2" value="M2" />M2
<input type="submit" value="Szukaj" />
</form>
<div id='name-data'>Instruktorzy o podanych uprawnieniach:</div>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
............??????
</script>
You could solve your problem by using jquery form plugin, which will help you to submit the form without having to reload the page and show you the return from your target page in the same page. Just follow the instructions:
Download this jquery form plugin first and save it.
Then
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<!-- This jquery.form.js is for Submitting form data using jquery and Ajax -->
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm').ajaxForm(options);
});
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
if(responseText==1){
$("#error").html('No Result Found');
} else{
$("#result").html(responseText);
}
}
</script>
<form id="myForm" enctype="multipart/form-data" action="pdoakcja.php"
method="post" name="myForm">
<!--Instruktor: <input type="text" name="name" /> -->
Permissions:<input type="checkbox" name="M1" value="M1" />M1
<input type="checkbox" name="M2" value="M2" />M2
<input type="submit" value="Szukaj" />
</form>
<span id="error"></span>
<span id="result"></span>
YOUR pdoakcja.php file: (I have got the following code from your another post here, haven't checked it though)
<?php
$query = mysql_query("SELECT * FROM permissions WHERE m LIKE '".$_POST['M1']."' OR m LIKE '".$_POST['M2']."' OR mn LIKE '".$_POST['MN1']."' ");
if($query) {
while($permissions = mysql_fetch_assoc($query)){
$query2 = mysql_query("SELECT name_surname FROM instruktorzy WHERE instruktor_id='".$permissions['instruktor_id']."'");
while($Mdwa = mysql_fetch_assoc($query2)){
echo "<p style=\"font-size: 14px; font-family: Helvetica; background-color: #FFFFFF\"> ".$Mdwa['name_surname']."<br />" ; "</p>" ;
}
}
} else {echo "1";}
?>
I hope this will work for you. For detail information you could study the jquery form plugin's website.
Heres a pseudo example showing how you can do it with jQuery, this will also update as you click the check box so you could remove the submit altogether;
You say you already have a database doing the job so I wont include that. Just copy and paste.
<?php
//Some pseudo data kinda as your receive it from a query
$datafromSql = array(
array('id'=>1,'permission'=>'M1','theData'=>'User has M1 permission'),
array('id'=>2,'permission'=>'M2','theData'=>'User has M2 permission'),
array('id'=>3,'permission'=>'M1','theData'=>'User has M1 permission'),
array('id'=>4,'permission'=>'M1','theData'=>'User has M1 permission'),
);
//Access the data
if($_SERVER['REQUEST_METHOD']=='POST'){
$is_ajax = false;
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
$is_ajax = true;
}
//pseudo code, really you would put your query here
// SELECT theData FROM your_table WHERE permission=POST_VALUE ... ...
//And then format your output
$result=array();
foreach($datafromSql as $row){
if($is_ajax == true){
foreach($_POST as $key=>$value){
if($_POST[$key] == 'true' && $row['permission']==$key){
$result[]=$row['theData'].'<br />';
}
}
}else{
foreach($_POST as $key=>$value){
if($_POST[$key] == $row['permission']){
$result[]=$row['theData'].'<br />';
}
}
}
}
$result = implode('<hr />',$result);
//AJAX Response, echo and then die.
if($is_ajax === true){
header('Content-Type: text/html');
//example output sent back to the jQuery callback
echo $result;
//echo '<pre>'.print_r($_POST,true).'</pre>';
die;
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
function update(){
$.post('./<?php echo basename(__FILE__)?>',
{
M1: $("#M1").is(':checked'),
M2: $("#M2").is(':checked')
},
function(data) {
$('#result').replaceWith('<div id="result"><h1>The Result:</h1>'+ data +'</div>');
});
}
</script>
</head>
<body>
<form method="POST" action="<?php echo basename(__FILE__)?>">
Permissions:
<input type="checkbox" id="M1" name="M1" value="M1" onChange="update()"/>M1
<input type="checkbox" id="M2" name="M2" value="M2" onChange="update()"/>M2
<input type="submit" value="Szukaj" />
</form>
<p id='result'><?php echo isset($result)?$result:null;?></p>
</body>
</html>
You should use the PHP MySQL functions to retrieve the data you want from your database and then display them via PHP, not javascript.
Especially have a look at this: mysql_fetch_assoc - there is a fully working example.