I've been experimenting with modal dialogue boxes and came across one which uses the FancyBox JQuery tool. I am trying to understand why the validation script works correctly when the modal elements are in HTML form on the same page (in the body tags) as the script, however if I generate these elements in a php file the validation script fails.
Please see my index.php file:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" media="all" href="style-modal.css">
<link rel="stylesheet" type="text/css" media="all" href="fancybox/jquery.fancybox.css">
<script type="text/javascript" src="fancybox/jquery.fancybox.js?v=2.0.6"></script>
<script type ="text/javascript" src="like2.js"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function() {
$(".load").load('show.php');
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var commentid = $("#commentid").val();
alert("clicked!");
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(mailvalid == true) {
$("#send").replaceWith("<em>Sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
});
}
});
});
</script>
</head>
<body>
<div class="load">
</div>
</body>
</html>
Please see the php file "show.php" which I load:
<?php
include('connect.php');
echo '<div class="load">
<button class="modalbox" href="#inline">Click</button>
</div>
<div id="inline">
<h3>Enter your email to receive updates</h3>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<input type="hidden" id="commentid" name="commentid" value="5">
<br>
<button id="send">Send E-mail</button>
</form>
</div>
</div>';
?>
In this format when I click "Click" on index.php, the modal appears as normal, however when I click "Send E-mail" with or without data, the modal fades without any feedback or validation. Is it possible to work with this set up? All works as expected when the contents of div id="inline" from show.php are put into the body of index.html. Please assist
Related
I just need to display names of the array using ajax. Following code is working but the result ( Nilantha Ruwan Nimal Shamitha Alex) is just display and disappears.
Index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
</head>
<body>
<div class="container" style="margin-top:50px";>
<form >
<div class="form-group">
<input type="text" id="name" class="form-control" placeholder="Enter Name....">
</div>
<div class="form-group">
<button class="btn btn-success" id="btn">Enter</button>
</div>
</form>
<div class="msg"></div>
</div>
<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
var name = $("#name").val();
$.post("ajax.php",{ajax_name:name},function(response){
$(".msg").html(response);
})
.fail(function(error){
alert(error.statusText);
})
})
})
</script>
</body>
</html>
ajax.php
<?php
if(isset($_POST['ajax_name'])){
$store = array("Nilantha","Ruwan","Nimal","Shamitha","Alex");
foreach($store as $names) {
echo $names,"<br>";
}
}
?>
Try the following code.
<script type="text/javascript">
function submit() {
jQuery("form").submit(function(e) {
e.preventDefault();
var name = jQuery("#name").val();
jQuery.ajax({
type: 'POST',
url: 'ajax.php',
data: {ajax_name:name},
success: function(response) {
jQuery(".msg").html(response);
jQuery('#name').val('');
},
error: function() {
console.log("Something wrong");
}
});});
}
jQuery(document).ready(function() {
submit();
});
</script>
I would suggest looking at the network tab of Chrome Devtools and ensuring that the AJAX call isn't running twice. I would think that if the query ran twice but the second one did not have any name attached then it would return blank once the first one had received its response.
when ajax is called data is not passed . wen send function is called validat() is assigned to valid variable after validation the return is true however ajax is not called to pass through POST into php file for updates.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" >
<link rel="stylesheet" type="text/css" href="css/style.css" >
</head>
<body>
<div class="container">
<div id="res1"></div>
<div class="row">
<input type="checkbox" name="language" id="language1" value="English" >English<br/>
<input type="checkbox" name="language" id="language2" value="French" >French<br/>
<input type="checkbox" name="language" id="language3" value="German" onclick="validate();">German<br/>
<input type="checkbox" name="language" id="language4" value="Latin" >Latin<br/>
<button type="button" onclick="send();" >Send</button>
</div>
<div id="res"></div>
</div>
</body>
</html>
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function send(){
var valid = validate();
if(valid){
$.ajax({
type:'POST',
url:'process.php',
data:{fruit:fruit},
success:function(msg){
$("#res1").html(msg);
},
error:''
});
}
}
function validate(){
var valid = true;
var fruit = Array();
$('input[name="language"]:checked').each(function(){
fruit.push(this.value);
});
if((fruit == '')){
$("#res1").html("Atleast one checkbox requiered").css({'color':'red'});
$("#dem-res").html("Required").css({'color':'red'});
valid = false;
}else if(!(fruit == '')){
$("#res1").html("");
$("#dem-res").html("");
}
return valid;
}
</script>
You missing variable:
var fruit_name = "orange";
$.ajax({
type:'POST',
url:'process.php',
data:{"fruit" : fruit_name},
success:function(msg){
$("#res1").html(msg);
},
error:''
});
Replace your ajax code with
$.ajax({
type:'POST',
url:'process.php',
data:{'fruit':fruit},
success:function(msg){
$("#res1").html(msg);
},
error:''
});
You have error on sending data. Which is in incorrect format.i.e. Missing quotes.
depending upon type of response sending form server. It is possible to help more.If you are just echo some html code in server i think this is enough.
Hello so I have 2 submit buttons with different names (btn1, btn2) in my html form and what I am trying to do is to submit to another page without refreshing page. So what I wanted to do is if I click btn1 submit it will do something and if I click btn2 it will do another thing. My code in the html page is this
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'update.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1"> <input type="submit" name="btn2">
</form>
</body>
</html>
And the code in my update.php page
<?php
if(isset($_POST['btn1'])) {
//insert query
} else if(isset($_POST['btn2'])) {
//another insert query
}
?>
I actually got it working if I only have 1 submit button and no if(isset()) thing in the update.php page. What can I do to use 2 submits and with issets in another page without refreshing the main page?
$(this).serialize();
The above code statement doesn't include name of the submit button as a key value pair.
So, as people have suggested before me, you should use button instead of submit button. Something like this.
HTML and JS
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#btn1, #btn2').on('click',function(e) {
var datastr = $(this).serialize() + "&button_id="+$(this).attr('id');
$.ajax({
url:'update.php',
data:datastr,
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm" action="update.php">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<button id="btn1">Button1</button><button id="btn2">Button2</button>
</form>
</body>
</html>
AND PHP would be:
<?php
if($_POST['button_id'] == 'btn1') {
//do something
} else if($_POST['button_id'] == 'btn2') {
//do something else;
}
?>
Use this, may useful for you
try
$('#myForm').on('submit',function(e) {
e.preventDefault();
});
OR
<button type="button">
Use on click event on the button and add the value attribute to the submit button, the value of the click button will be pased to the php file
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('input[type="submit"]').on('click',function(e) {
e.preventDefault();
$.ajax({
url:'update.php',
data:{'txt_amount':$('input[name="txt_amount"]').val(),'btn': $('input[type="submit"]').val()}
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1" value="btn1"> <input type="submit" name="btn2" value="btn2">
</form>
</body>
</html>
php:
<?php
if($_POST['btn'] == 'btn1') {
//do something
} else if($_POST['btn'] == 'btn2') {
//do something else;
}
?>
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","root") or die("not connecting");
mysql_select_db("demo") ;
echo"database connecting";
if(isset($_POST['type']))
{
if($_POST['type']=="booking"){
$dname = $_POST ['Name'];
$dpwd = $_POST ['Pwd'];
//$mail = $_POST ['Email'];
$query1 = "SELECT count(*) FROM user WHERE username='$dname' AND password='$dpwd'";
$result1=mysql_query($query1);
$num_row = mysqli_num_rows($result1);
echo json_encode($result1);
if( $num_row>0 )
{
while( $row=mysqli_fetch_array($result) ){
$_SESSION['userid'] = $row['userid'];
}
}
}
}
else{
echo "Invalid format";
}
?>
Php code working fine placed in xampp server ,after putting in xampp server htdoc .
this html code with validation with json and ajax. I am not getting any confirmation message
<!DOCTYPE html>
<html>
<head>
<title>Admin Login</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<!-- using ajax and json to get data from login fields -->
<script>
$(document).ready(function(){
$("#loginform").validate({
rules: {
username: "required",
password: {
required: true,
minlength: 2
},
},
messages: {
username: "Please enter your Name",
password: "Please enter your Mobile number"
},
submitHandler: function(form) {
alert("12");
// get values from textboxs
var uname = $('#username').val();
var upasssword = $('#password').val();
$.ajax({
//url:"http://service4homes.com/Test/bookService4Homes.php",
url:"http://localhost/service4homes/bookService4Homes1.php",
type:"POST",
dataType:"json",
data:{type:"booking", Name:uname, Pwd:upassword },
//type: should be same in server code, otherwise code will not run
ContentType:"application/json",
success: function(){
// alert(JSON.stringify(response));
$("#result").html('Submitted successfully');
//alert("success");
window.location.href = 'index1.html';
},
error: function(err){
// alert(JSON.stringify(err));
$("#result").html('There is error while submit');
//alert("fail");
window.location.href = 'index.html';
}
});
return false; // block regular submit
}
});
});
</script>
</head>
<body id="login">
<div class="container" >
<div id="result"></div>
<form class="form-signin" id="loginform" >
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="input-block-level" placeholder="Email address" id="username">
<input type="password" class="input-block-level" placeholder="Password" id="password">
<!-- <label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
</label> -->
<button class="btn btn-large btn-primary" type="submit" >Sign in</button>
</form>
</div> <!-- /container -->
</body>
</html>
Php code working fine placed in xampp server ,but in json validation is not working ,please help me .
When you want to talk to javascript from php, you should use json or xml.
In your php you can make this response when the login and pass match :
$response = array('success' => true, 'message' => 'Login successful');
And when it fail :
$response = array('success' => false, 'message' => 'Login fail');
Then send it (I choose json format) :
header('Content-type: application/json');
echo json_encode($response);
And in your javascript :
$.ajax({
...
dataType: 'json',
success: function(response) {
if (response.success == true) {
window.location.href = 'index1.html';
} else {
alert(response.message);
}
}
});
My Index.html file code as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mindcorpus - Placement</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery-mobile.js" type="text/javascript"></script>
<script src="/cordova.js" type="text/javascript"></script>
<script>
$(function()
{
$('#frm').submit(function()
{
var username = $('#textinput').val();
var username = $.trim(username);
var password = $('#passwordinput').val();
var password = $.trim(password);
if(username=='')
{
$('.error').html('Please enter username');
return false;
}
else if(password =='')
{
$('.error').html('Please enter password');
return false;
}
else
{
var user = $('[name=username]').val();
var pass = $('[name=password]').val();
$.ajax({
type: 'POST',
url: 'http://localhost/mc-new/admin/mobile1/process.php',
data: { username: user, password: pass},
success: function(data){
alert(data.success);
},
error: function(){
alert('error!');
}
});
return false;
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<div data-role="header">
<h1><img src="images/logo.png" /></h1>
</div>
<div data-role="content">
<div class="error"></div>
<form action="" method="post" id="frm">
<div data-role="fieldcontain">
<input type="text" name="username" placeholder="Username" id="textinput" value="" />
</div>
<div data-role="fieldcontain">
<input type="password" name="password" placeholder="******" id="passwordinput" value="" />
</div>
<button data-icon="arrow-r" type="submit">Submit</button>
</form>
</div>
<div data-role="footer">
<h4 style="font-weight:normal">Powered By: Mind Processors</h4>
</div>
</div>
</body>
</html>
And my process.php file is:
<?php
if(isset($_POST['username']) || isset($_POST['password']))
{
$data['success'] = 'Done';
echo json_encode($data);
}
?>
This functions is properly working when I use localhost on my browser. BUt when I use Dreamweaver and build & Emulate this site. It always alert error. The Ajax is not functioning in emulator. The request is not passed to process file. Please help me & sort out this problem.
You need to specify in the ajax that the expected return data type is JSON and also cross domain has to be enabled.
Try the below code for the ajax,
$.ajax({
type: 'POST',
url: 'http://localhost/mc-new/admin/mobile1/process.php',
crossDomain: true,
data: { username: user, password: pass},
dataType: 'json',
success: function(data){
alert(data.success);
},
error: function(){
alert('error!');
}
And also add the following in your php file,
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
header('Content-Type: application/json');
if(isset($_POST['username']) || isset($_POST['password']))
{
$data['success'] = 'Done';
echo json_encode($data);
}
?>
Hope this helps to someone who falls onto this question, looking for an answer.