how to submit the form without refreshing the page - php

this is my html code when i click on submit button it displays alert and then when i open the retrieveform.php it does not show me the value please solve this mystery
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function () {
alert('helllo');
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text"name="t1">
<input type="submit"name="s1"value="submit">
</form>
</body>
</html>
and my retrieveform.php is
<?php
if($_POST['t1'])
{
echo $_POST['t1'];
}
else
{
echo "hekllojjio";
}
?>

Is it possible that the element "t1" is present since it's part of your form, but empty or just empty characters .. perhaps check if this is the case?
<?php
if($_POST['t1'] && !empty($_POST['t1'])) {
echo "You submitted t1 of: ".$_POST['t1'];
} else {
echo "t1 is empty";
}
?>
Also of note is you may want to use something like firebug to view the ajax page loaded and its results. The echo statement on the ajax loaded page will not display on the parent page unless you set the contents of the response into the page:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$('.form').on('submit', function (e) {
tValue = $(this).find(input[type=text]:first).val();
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function (response) {
alert('helllo');
$('#placeholder').html(response);
$('#placeholder2').html(tValue);
}
});
});
});
</script>
</head>
<body>
<?PHP for ($i = 1; $i <= 10; $i++) { ?>
<form class="form" name="form_<?PHP echo $i; ?>" id="form_<?PHP echo $i;?>">
<input type="text" id="t<?PHP echo $i; ?>" name="t<?PHP echo $i; ?>">
<input type="submit" name="s<?PHP echo $i; ?>" value="submit">
</form>
<?PHP } ?>
<div id="placeholder"></div>
<div id="placeholder2"></div>
</body>
</html>
with this your ajax loaded page's echo will be put on the page in the "placeholder" div.

Related

Submit form using Ajax/Jquery and check result?

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.

Post data with ajax or ajax(json) to php in same page

I'm trying message application. My goal is get sender id and receiver id with a click on one button.
After then post this datas with ajax or ajax(json) to php in same page.
I will use the incoming data in php with mysql_query. I tryed many examples. But never get result. My example code at below.
Little Note: Success alert comes but doesn't print any data on screen.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<button type="button" onclick="myFunc()">Get ID</button>
<script>
function myFunc()
{
var id = 'example';
jQuery.ajax({
url:'index.php',
type: "POST",
data: {'name':id},
success: function(data)
{
alert("success");
}
});
};
</script>
<?php
if(isset($_POST['name']))
{
$value = $_POST['name'];
echo $value;
}
else
{
echo "don't work.";
}
?>
</body>
</html>
<?php
if(isset($_POST['name']))
{
echo json_encode(array(
'value' => $_POST['name']
));
exit();
}
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<button type="button" onclick="myFunc()">Get ID</button>
<script>
function myFunc()
{
var id = 'example';
jQuery.ajax({
url:'index.php',
type: "POST",
data: {'name':id},
dataType : 'json',
success: function(data)
{
alert("success");
}
});
};
</script>
</body>
</html>

chat app with user typing partly working

This code works very well for chatting. I have added ajaxcall.php for real time notification. The problem is; instead of displaying a typing notification when other users are typing, it will be displaying myself whenever am typing.please how do i make it to show other users typing.
index.php
<?php
ob_start();
?>
<?php
session_start();
?>
<!doctype>
<html>
<head>
<title>Chat</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="jscolor.js"></script>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
complete: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
success: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
}
});
var $container = $("#messages");
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
var refreshId = setInterval(function()
{
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
}, 3000);
$("#userArea").submit(function() {
$.post('ajaxPost.php', $('#userArea').serialize(), function(data) {
$("#messages").append(data);
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
document.getElementById("output").value = "";
});
return false;
});
});
</script>
<!--Ajax Server Call-->
<script>
function getAjaxFromServer(str){
if (str.length==0){
document.getElementById("ajaxResponse").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("ajaxResponse").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",'ajaxcall.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>',true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="chatwrapper">
<!--display-->
<!--http://www.youtube.com/watch?v=FyXeOX-uYMc-->
<div id="messages"></div>
<!--post-->
<form id="userArea">
<div id="usercolor">
<input name="reciever" type="hidden" value="<?php echo htmlentities($_GET['id'], ENT_QUOTES, "UTF-8");?>"><br>
<input name="text" class="color" id="text" maxlength="6" value="000000" />
</div>
<div id="messagesntry">
<textarea id="output" name="messages" placeholder="Message" onkeyup="getAjaxFromServer(this.value)"/></textarea>
</div>
<div id="messagesubmit">
<input type="submit" value="Post message" id="submitmessage" />
</div>
</form>
</div>
</body>
</html>
ajaxload.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
include('connect.php');
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM messages ORDER BY id ASC");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
echo '<div style="color:'.$row['textcolor'].'">' .$row['user'] . ' : '. $row['message'] .'</div>';
}
?>
ajaxcall.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
$txt=strip_tags($_GET['id']);
$txt1=strip_tags($_SESSION['SESS_MEMBER_ID']);
echo $txt;
echo " is typing ";
?>
The idea is to store a flag on a database and have an a .setTimeOut on your script on which will run whenever your field flag turns from 0 to 1
here is the code snippet to try
$('#txt_message').keyup(function(){
// Start a flag loop with an id of 'loop' and a counter.
var i = 1;
var dataString = 'flag='+ i ;
$.ajax({
type: "POST",
url: "notif.php",
data: dataString,
cache: false,
success: function(url){
}
});
this snippet will update your database whenever you type on your text field
var timer;
function AjaxRetrieve()
{
$.get("type_on.php?flag=0",function(data)
{
window.clearTimeout(timer);
$("#typing_on").html(data);
timer=window.setTimeout(function(){AjaxRetrieve()},3100);
});
}
timer=window.setTimeout(function(){AjaxRetrieve()},1300);
this snippet will be the one to update your flag after a few seconds

How to detect the number of uploaded files and their names before uploading from client side by javascript or jquery?

I want to upload multiple files and have a file called test.php with this code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery-1.8.0.min.js"></script>
<script>
$(function(){
var myVar;
$('form').submit(function(){
myVar = setInterval(ajax, 1000);
});
var ajax = function() {
$.ajax({
url: 'test2.php',
type: 'post',
success: function(ajax_result){
$('.result').html(ajax_result);
if (!ajax_result) {
clearInterval(myVar);
}
},
error: function(){
alert('error');
}
});
};
});
</script>
</head>
<body style="width:100%; height:100%;">
<form action="test2.php" target="iframe" method="post" enctype="multipart/form-data" >
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="fil" />
<input name="file[]" type="file" multiple />
<input type="submit">
</form>
<iframe id="iframe" name="iframe"></iframe>
<div class="result" style="width:100%; height:100%;"></div>
</body>
</html>
and a file called test2.php with this code:
<?php
session_start();
if (isset($_FILES['file'])){
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
move_uploaded_file($_FILES['file']['tmp_name'][$i],'a/'.$_FILES['file']['name'][$i]);
}
}
if (isset($_SESSION[$key = ini_get("session.upload_progress.prefix") . 'fil'])) {
var_dump($_SESSION[$key]);
} else echo false;
?>
Now I want before sending files to server to detect the number of files selected via their names in the client side.
How can I do this?
$('form').submit(function() {
var numberOfFilesAboutToBeSubmitted = $("[name='file[]']", this ).prop("files").length;
});
Note that you are not submitting any files with your ajax request, it has no association with your form at all.
Also note that this doesn't work in IE < 10

jQuery.ajax - Duplicate Content After Posting Data Back To The Same Page

Problem 1: My content overlaps itself twice after I post some data back to the same page using jQuery.ajax(). The reason why I'm posting data back to the same page is because I need to pass my JavaScript values to the PHP side.
Question: How do I edit my code such that there will only be 1 copy of my content, before and after posting of data to the same page?
Problem 2: You may have noticed there is a $("#test").html(data); in my bingo function and a <span id="test"></span> in my body. I can't seem to remove them if not the passing of Javascript values to the PHP side would not work as shown by my print_r().
Question: Is there any way I can remove them but still pass my values from JavaScript to PHP using jQuery.ajax()?
bingo.php
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<?php
if (!isset($_POST['varA']) && !isset($_POST['varB']))
{
?>
<script type="text/javascript">
$(document).ready(bingo);
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123", varB: "456"},
success: function(data)
{
alert("POST to self is successful!");
$("#test").html(data);
}
});
}
</script>
<?php
}
else
{
print_r($_POST['varA']);
echo " - ";
print_r($_POST['varB']);
}
?>
</head>
<body>
<input type="text" value="meow"/>
<span id="test"></span>
</body>
</html>
Omg that is so messy! Try the following code anyway:
<?php
if (isset($_POST['varA']) && isset($_POST['varB'])) {
print_r($_POST['varA']);
echo " - ";
print_r($_POST['varB']);
} else {
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(bingo);
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123", varB: "456", ajax: true},
success: function(data)
{
alert("POST to self is successful!");
$("#test").html(data);
}
});
}
</script>
</head>
<body>
<input type="text" value="meow"/>
<span id="test"></span>
</body>
</html>
<?php
}
?>
If you wish to keep your ! in your conditions, you can do it the other way round also.
<?php
if (!isset($_POST['varA']) && !isset($_POST['varB'])) {
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(bingo);
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123", varB: "456"},
success: function(data)
{
alert("POST to self is successful!");
$("#test").html(data);
}
});
}
</script>
</head>
<body>
<input type="text" value="meow"/>
<span id="test"></span>
</body>
</html>
<?php
}
else {
print_r($_POST['varA']);
echo " - ";
print_r($_POST['varB']);
}
?>

Categories