I'm new to ajax concept. Here i'm trying to insert the user details(signup form) into the database. it inserted the datas into the db succesfully. But, ajax is my problem.
1) i didn't get any error message if form fields are empty. you can see my below codes i've done validation on post.php page. but, it doesn't return the error values. 2) it stores the empty values into database. 3) if datas stored successfully i want to get the success message & if datas failed to store in db i want to get the error message. How should i do these all things?
Ajax.js
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function(msg) {
if(msg=='error_n')
{
$("#e_name").html('Name required');
}
if(msg=='error_m')
{
$("#e_mobile").html('Mobile required');
}
//success and error alert
if(data="inserted")
{
alert("insertion success");
}
else
{
alert("falid to insert into database");
}
}
});
e.preventDefault();
});
});
Post.php
<?php
include_once('config.php');
$name = trim($_POST["name"]);
$mobile = trim($_POST["mobile"]);
if($name == "")
{
echo 'error_n';
}
if($mobile == "")
{
echo 'error_m';
}
try
{
$stmt = $conn->prepare("INSERT INTO sample ( Name, Mobile ) VALUES ( ?, ? )");
$conn->errorInfo();
$stmt->bindParam('1', $name, PDO::PARAM_STR);
$stmt->bindParam('2', $mobile, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database' .$e->getMEssage();
}
?>
Homepage.php
<p>register here</p>
<div id="light" class="white_content">
Close
<form>
<input type="hidden" name="form" value="values" />
name : <input name="name" id="name" type="text" /><span id="e_name"></span> <br />
mobile : <input name="mobile" id="mobile" type="text" /><span id="e_mobile"></span> <br />
<input type="submit" value="submit" />
</form>
</div>
<div id="fade" class="black_overlay"></div>
After your error messages are returned, you need to stop the script execution. Your current code still tries to add the values and hence overrides your custom error messages. Most probably then your PHP returns your exception message and which is not what your JavaScript is expecting.
if($name == "")
{
echo 'error_n';
die(); // Stop here
}
if($mobile == "")
{
echo 'error_m';
die(); // Stop here
}
Also add echo 'inserted'; when your database insert is successful.
Related
I am absolute begginner for the programming. Here I want to pass a argument to $('form').submit(function () {. Just I want to pass the email value to .submit() function, that has been created like this,
Here is the HTML code,
<div id="friends">
<?php
$query=$pdo->prepare("SELECT DISTINCT * FROM users as u
WHERE EXISTS (SELECT * FROM appointment as a
WHERE u.user_id = a.user_id AND
a.p_id= '".$_SESSION['p_id']."')");
$row=$query->execute();
$rs=$query->fetchAll(PDO::FETCH_OBJ);
foreach ($rs as $message){
$filename= $message->image;
$filepath="../../adminpanel/profile/blog/";
?>
<div class="friend">
<?php
printf(
'<img class="inline-block" src="data:image/png;base64, %s" alt="user" />',
base64_encode(file_get_contents($filepath.$filename ) )
);
?>
<p>
<strong> <?php echo $message->username ?></strong> <br>
<span id="email"><?php echo $message->email ?></span>
</p>
<div class="status available"></div>
</div>
<?php } ?>
Here is the HTML for submit button
<form class="" id="msgform" action="chat.php" method="post">
<div id="sendmessage">
<input type="text" placeholder="Send message..." class="textarea" name="message"/>
<button id="send" class="textarea" ></button>
</div>
</form>
Below is the javascript code, that how to set email to html to appear.
$(".friend").each(function(x){
$(this).click(function(){
var name = $(this).find("p strong").html();
var email = $(this).find("p span").html();
LoadChat(email);
$("#profile p").html(name);
$("#profile span").html(email);
});
});
I have passed this email variable to submit function, but always takes the email of last user. Here is the .submit function to sent data to server.
$('form').submit(function() {
const email = <?= json_encode($message->email) ?>
var message = $('.textarea').val();
if ($(".textarea").val()) {
$.post("handlers/messages.php", {
action: "sendMessage",
message: message,
email: email
}, function(response) {
if (response == 1) {
LoadChat();
document.getElementById('msgform').reset();
}
});
} else {
myFunction();
}
return false;
})
Just I want to pass the particular email value to submit function. Please help me may highly appreciated and thanks in advance.
$('form').submit(function() {
var email = $('#email').val();
var message = $('.textarea').val();
if ($(".textarea").val()) {
$.post("handlers/messages.php", {
action: "sendMessage",
message: message,
email: email
}, function(response) {
if (response == 1) {
LoadChat();
document.getElementById('msgform').reset();
}
});
} else {
myFunction();
}
return false;
})
You were getting the email which was printed by php (server side). You need to send what is on client or browser side.
var email = $('#email').val();
This will solve your issue
I am currently working on a PHP based web-interface, with a login system.
But for some reason when I hit login, it seems to get to the login.php and return a response back.
But the thing is, the response is not what I need to have, and furthermore logging in is still not happening.
The HTML based login form (Within a modal):
<form class="form" method="post" action="<?php echo Utils::resolveInternalUrl('backend/Login.php') ?>" id="loginForm">
<div class="form-group">
<label for="loginUsername">Username:</label> <input type="text" class="form-control" name="loginUsername" id="loginUsername" />
</div>
<div class="form-group">
<label for="loginPassword">Password:</label> <input type="password" class="form-control" name="loginPassword" id="loginPassword"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
Javascript/jQuery related to login:
var form = $('#loginForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
'data': form.serialize(),
'type': $(this).attr('method'),
'url': $(this).attr('action'),
'dataType': 'JSON',
success: function (data) {
alert("Success: " + data)
},
error: function (error) {
alert("Error: " + error)
}
})
})
PHP backend, related to login:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$database = Database::getDefaultInstance();
if(isset($_POST['loginUsername']) && isset($_POST['loginPassword'])) {
$connection = $database->getConnection();
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
echo $username . ":" . $password;
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
if($stmt->fetch()) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['sessionId'] = Utils::randomNumber(32);
echo json_encode("Successfully logged in as ${username}.");
exit;
} else {
echo json_encode("No user exists with the name \"${username}\".");
exit;
}
} else {
echo json_encode("Username and/or password is not provided.");
exit;
}
} else {
echo json_encode("Submit method is not POST.");
exit;
}
The result of it:
Click here for screenshot
Edit:
Changed SQL query to: SELECT COUNT(*) FROM banmanagement.users WHERE username=:username;
Edit 2:
Per suggestion, I have used var_dump the output var_dump($_POST) is: array(0) { }.
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
I'm assuming you're using PDO on the backend. If so, you don't need the semicolon in your query. That's why your fetch is failing.
$stmt = $connection->query("SELECT * FROM banmanagement.users");
Ok, so that wasn't it. I was reading the wrong braces. Have you tried var_dump($_POST) to see what, if anything, is being sent?
Consider this image which is an iframe window when user clicks on a link.
My Problem
When user clicks deposit the form gets submitted and the window closes, thus the user does not know if deposit was successful or not.
What I want to do
I am looking for a way to keep the iframe window open after the form has been submitted, to display appropriate message
Form HTML
<form name="depForm" action="" id="register_form" method="post">
User Name<br /><input type="text" name="uname" value="" /><br />
Credit Card Nr<br /><input type="text" name="cc" value="" /><br />
CSV Nr<br /><input type="text" name="csv" value="" /><br />
Amount<br /> <input type="text" name="amount" value="" /><br />
<input type="submit" value="deposit" name="deposit" class="buttono" />
</form>
PHP Code
if(isset($_POST['deposit'])){
if(isset($_SESSION['FBID'])){
$uid=$_SESSION['FBID'];
$amount = $_POST['amount'];
$cc = $_POST['cc'];
$csv = $_POST['csv'];
//new bal
$bal = getBal($uid);
$newBal = $bal+$amount;
$sql="UPDATE members SET balance='$newBal' WHERE member_nr='$uid'";
$result = mysql_query($sql) or die("error please try again");
if($result){
}
}
if anyone can advise me how to keep iframe open after form has been submitted it will be greatly appreciated.
You would need to change the form submission to use AJAX. In the response you can include a state flag to indicate to the UI whether the request was successful or not and act appropriately. Something like this:
$('#register_form').submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(data) {
if (data.success) {
// show success message in UI and/or hide modal
} else {
// it didn't work
}
},
error: function(xhr, status, error) {
// something went wrong with the server. diagnose with the above properties
}
});
});
$success = false;
if (isset($_POST['deposit'])) {
if (isset($_SESSION['FBID'])) {
$uid = $_SESSION['FBID'];
$amount = $_POST['amount'];
$cc = $_POST['cc'];
$csv = $_POST['csv'];
$bal = getBal($uid);
$newBal = $bal + $amount;
$sql = "UPDATE members SET balance='$newBal' WHERE member_nr='$uid'";
$result = mysql_query($sql) or die("error please try again");
if ($result) {
$success = true;
}
}
}
echo json_encode(array('success' => $success));
I have a pair of radio buttons and I want to insert its value into my database in the form of bit. Following is the HTML code for the same.
<form id="Form" method="post" class="overlay" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input type="hidden" id="Keyy" name="key" value="">
<label for="JRadioYes">Active? Yes</label> <input type="radio" id="JRadioYes" name="activeradio"<?php if (isset($ActiveValue) && $ActiveValue == "yes") echo "checked='checked' "; ?>value="yes">
<label for="JRadioNo">No</label> <input type="radio" id="JRadioNo" name="activeradio"<?php if (isset($ActiveValue) && $ActiveValue == "no") echo "checked='checked' "; ?>value="no">
<input type="submit" id="submitter" name="sub" value="Submit!" onclick="decider(this)">
</form>
The following is the PHP code for inserting into the database
// Check if radio is submitted
if (isset ( $_POST ["activeradio"]))
{
//Extract values from $_POST and store in variables
$select_radio = $_POST ["activeradio"];
if ($select_radio == "yes") {
$active_status = true;
//I also tried assigning 1 instead of true
}
if ($select_radio == "no") {
$active_status = false;
//I also tried assigning 0 instead of false
}
if($_POST["key"] == "update")
{
try
{
echo "<script type='text/javascript'>
alert('$active_status');
</script>";
$JobInt = intval($JobTypeID);
$stmt = sqlsrv_query ( $conn, 'EXEC spEditThisJobType #Active = ?', array (
$active_status
) );
}
catch(Exception $e)
{
echo "Error :". $e;
}
if($stmt != null)
{
echo "<script type='text/javascript'>alert('Successfully Updated!$stmt');
</script>";
}
}
}
I am able to get the alert which says Successfully Updated, but I am also getting Resource #6 error along with it. Also the database does not get updated.
What is the mistake I have done here? Please guide me. Thank you in advance.
Have a look at the documentation for sqlsrv_query - it returns a resource object, not the result of the query.
Therefore when you echo "Successfully Updated!$stmt", the resource $stmt is converted to its string representation - Resource #6.
So you either need to remove $stmt from your echo, or do something with the resource such as reading the data using sqlsrv_fetch_array.
as title, I am a beginner about website design.
Please never mind if I ask a stupid question.
while i send the form, it didnt work.
here is html:
<form id="form1" name="form1" action="toSQL.php" method="POST" accept-charset="utf-8">
<input type="text" name="Cliname" id="textfield" maxlength = "10" />
<textarea name="message" id="message" rows="3" maxlength = "20" ></textarea>
<input type="submit" value="submit" id="submit" />
</form>
<div class="alert"></div>
and here is js:
<script type="text/javascript">
$(document).ready(function() {
var form = $(this) ;
var submited = $('#submit') ;
var alerted = $('.alert') ;
form.on( 'submit', this, (function(event) {
event.preventDefault();
if ( $.trim($form.find('input[name="Cliname"]').val()) == "" || $.trim($form.find('input[name="message"]').val()) == "" ) {
alert( "please enter!!" ) ;
return ;
}
else {
$.ajax({
url: 'toSQL.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alerted.fadeOut();
},
success: function(data) {
alerted.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
},
error: function(e) {
console.log(e)
}
});
}
}));
});
</script>
server side php:
<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['Cliname']) AND isset($_POST['message'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (send($name, $message)) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
function send( $name, $message ) {
$time = date("Y-m-d H:i:s");
$mysqlConnection=mysql_connect("localhost", 'root', '') or die("connect error!");
mysql_select_db('test') or die ("db error!");
$queryStr="INSERT INTO fortest (time, message, name)
VALUES ( '$time', '$message', '$name')";
mysql_query($queryStr,$mysqlConnection) or die(mysql_error());
return true ;
}
?>
here is the website i reference : http://www.w3bees.com/2013/08/submit-form-without-page-refresh-with.html
Did i miss something?
As a couple people have mentioned already, you are trying to serialize your entire dom object, which isn't going to work. Change it to var form = $("#form1") and it should work.
I recommend you open the webpage in chrome dev tools and click the network tab, click preserve log and then submit the form. When it is submitted you'll see the full headers that were sent to the server and can verify it works correctly to help narrow down the problem