Interactive forms with PHP and Ajax via JQuery - php

I can't make the html loaded via ajax update the DOM. What am I doing wrong?
HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Test</title>
<link rel="stylesheet" type="text/css" href="//atpc.info/f/styles.css" media="all">
<link rel="stylesheet" type="text/css" href="//atpc.info/f/form.css" media="all">
<link rel="stylesheet" type="text/css" href="//atpc.info/f/pesquisa.css" media="all">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="//atpc.info/f/t/test.js"></script>
</head>
<body>
<form id="form_p" action="">
<fieldset class="p_test">
<legend>Test question text?</legend>
<label for="p_test_y"><input type="radio" id="p_test_y" name="p_test" value="y">Yes!</label>
<label for="p_test_n"><input type="radio" id="p_test_n" name="p_test" value="n">No!</label>
<a class="continue_r">Continue →</a>
</fieldset>
<small id="update_p"></small> <span id="status_p"></span>
</form>
</body>
</html>
JQuery:
$(document).ready(function() {
$('label').css('display','block');
$('a.continue_r').live('click',function(event) {
var id_p=$('input:radio:first').attr('name');
var v_r=$('input:radio:checked').val();
alert(v_r);
$.post(
'test.php',
{ id_p:id_p, v_r:v_r },
function(data){
alert('Retorno:\n' + data);
//$('form').append($(data).hide().fadeIn('slow'));
$('body').append(data);
$('label').css('display','block');
}
);
});
});
PHP:
<?
if(!empty($_REQUEST['id_p'])) $id_p=$_REQUEST['id_p'];
else die('Ops! no id_p');
if(!empty($_REQUEST['v_r'])) $v_r=$_REQUEST['v_r'];
else die('Ops! no v_r');
if($_REQUEST['id_p']=='p_test1') die('Victory!!!');
echo<<<FORM
<fieldset class="p_test1">
<legend>Test 1 question text?</legend>
<small>Last question was $id_p and you option was $v_r</small>
<label for="p_test1_y"><input type="radio" id="p_test1_y" name="p_test1" value="ohy">Oh, Yes!</label>
<label for="p_test1_n"><input type="radio" id="p_test1_n" name="p_test1" value="ohn">Oh, No!</label>
<a class="continue_r">Continue →</a>
</fieldset>
FORM;
?>
For those interested, here is the final working JQuery code:
$(document).ready(function() {
$('label').css('display','block');
$('a.continue_r').live('click',function(event) {
//var fieldset=$(this).closest('fieldset');
var fieldset=$(this).parent('fieldset');
//alert(fieldset.attr('class'));
//var id_p=$('input:radio').attr('name');
//var id_p=fieldset.attr('class');
var id_p=$('fieldset:last').attr('class');
var v_r=$('input:radio:checked:last').val();
if(v_r=='') v_r=$('textarea:last').val();
fieldset.hide();
//alert('id_p = '+id_p+' - v_r = '+v_r);
$.post(
'test.php',
{ id_p:id_p, v_r:v_r },
function(data){
//alert('Retorn:\n' + data);
$('body').append($(data).hide().fadeIn('slow'));
//$('body').append($(data));
//$('body').append($data);
$('label').css('display','block');
//console.log(data);
}
);
});
});

Actually, the DOM is updated. But I think the selector is wrong.
Try this?
$(':radio:checked:last')
This will get the last checked radio input, which is probably what you want instead. Based on the markup:
<fieldset class="p_test">
<legend>Test question text?</legend>
<label for="p_test_y"><input type="radio" id="p_test_y" name="p_test" value="y">Yes!</label>
<label for="p_test_n"><input type="radio" id="p_test_n" name="p_test" value="n">No!</label>
<a class="continue_r">Continue →</a>
</fieldset>
The fieldset tag wraps everything up, so your handler can be defined like:
$('a.continue_r').live('click', function() {
var $fieldset = $(this).parent('fieldset');
// Do stuff like $fieldset.find(), which ensures that your matches are contained therein.
});

Related

Issue with displaying the Jquery Ajax result

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.

php jquery ajax checkbox validation

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.

Unable to get jquery response when form is submited using submit button

I am sending state,city,zip code to ajax.php file. using jquery.
I am unable to get those values in response
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Jquery Ajax</title>
</head>
<body>
<!------------------------Jquery-------POST DATA----------------------------------------->
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
-->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#id-submit').click(function() {
var reg_state = $('#reg_state').val();
var reg_city = $('#reg_city').val();
var reg_zip = $('#reg_zip').val();
var dataString = 'reg_state='+ reg_state;
//alert(dataString);
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data)
{
//$("#state").html(data);
alert(data);
}
});
});
});
</script>
<!------------------------Jquery-----------POST DATA END------------------------------------->
<form id="registration_form" action="" method="post">
<div id="state"></div>
<div class="reg-id">
<label>
<input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
</label>
</div>
<div class="reg-id">
<label>
<input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
</label>
</div>
<div class="reg-id-last">
<label>
<input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
</label>
</div>
<input type="submit" value="submit" tabindex="3" name="reg_btn" id="id-submit">
</div>
</form>
</body>
</html>
This is the ajax.php file , from where i need to send response, and make it visible in div id="state
<?php
if($_POST['reg_state'])
{
echo $_POST['reg_state'];
}
else{
echo 'nothing';
}
?>
Try create an object
var dataString = { reg_state: reg_state, reg_city: reg_city, reg_zip : reg_zip }
I believe your problem lies in the type=submit. Replacing this with type=button gives you the result you want.
I'm unsure why this is, but I'm guessing it type=submit gives extra functionality to the input. The page seems to reload after hitting the submit button.
ps. don't forget you actually need to click the button in order for the function to trigger. Hitting enter after filling out the input fields will do nothing.
When ever we use input['type']="submit" in form
we have to use
$('#id-submit').click(function(e) {
e.preventDefault();
}
Here is the full working code
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Jquery Ajax</title>
</head>
<body>
<!------------------------Jquery-------POST DATA----------------------------------------->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#id-submit').click(function(e) {
e.preventDefault();
var reg_state = $('#reg_state').val();
var reg_city = $('#reg_city').val();
var reg_zip = $('#reg_zip').val();
var dataString = { reg_state: reg_state, reg_city: reg_city, reg_zip : reg_zip }
//alert(dataString);
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(data)
{
$("#state").html(data);
// alert('hi');
}
});
});
});
</script>
<!------------------------Jquery-----------POST DATA END------------------------------------->
<form id="registration_form" action="" method="post">
<div id="state"></div>
<div class="reg-id">
<label>
<input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
</label>
</div>
<div class="reg-id">
<label>
<input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
</label>
</div>
<div class="reg-id-last">
<label>
<input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
</label>
</div>
<input type="submit" value="Response" tabindex="3" name="reg_btn" id="id-submit">
</div>
</form>
</body>
</html>
ajax_city.php
<?php
if($_POST['reg_state'])
{
echo 'STATE: '.$_POST['reg_state'].'<br/>';
echo 'CITY: '.$_POST['reg_city'].'<br/>';
echo 'ZIP: '.$_POST['reg_zip'].'<br/>';
}
else{
echo 'nothing to respond';
}
?>

Modal not validating when elements generated through external file

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

How to get a text field value from the form in PHP by using jQuery Tagit

I am using the JQuery Tags Plugin and when user enter some tags by comma separated then i want to get those tags after form submit by using PHP.
my coding...
<?php
if(isset($_REQUEST['submit_tag'])) {
print_r($_REQUEST['tags']);
}
?>
<!-- tags -->
<script src="http://webspirited.com/tagit/demo/js/jquery.1.7.2.min.js"></script>
<script src="http://webspirited.com/tagit/demo/js/jquery-ui.1.8.20.min.js"></script>
<script src="http://webspirited.com/tagit/js/tagit.js"></script>
<link rel="stylesheet" type="text/css" href="http://webspirited.com/tagit/demo/css/jquery-ui-base-1.8.20.css">
<link rel="stylesheet" type="text/css" href="http://webspirited.com/tagit/css/tagit-awesome-blue.css">
<script type="text/javascript">
$(function () {
$('#demo3').tagit({triggerKeys:['enter', 'comma', 'tab'], select:true});
$('#demo3GetTags').click(function () {
showTags($('#demo3').tagit('tags'))
});
function showTags(tags) {
console.log(tags);
var string = "Tags (label : value)\r\n";
string += "--------\r\n";
for (var i in tags)
string += tags[i].label + " : " + tags[i].value + "\r\n";
alert(string);
}
});
</script>
<!-- tags -->
<form method="post" id="add_tag" action="" name="add_tag">
<button id="demo3GetTags" value="Get Tags">Get Tags</button>
<ul id="demo3" name="tags[]"></ul>
<br />
<input type="submit" name="submit_tag" value="Submit Tag" />
</form>
You can add following script in your code.
$('input[type=submit]').click(function(){
tag = $('#demo3').tagit('tags');
console.log(tag);
for (var i in tag)
$('form').append("<input type='hidden' name='tags[]' value='"+tag[i].value+"' >");
});
So your code will be look like below:
<?php
if(isset($_REQUEST['submit_tag'])){
print_r($_REQUEST['tags']);
}
?>
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>jQuery Tagit Demo Page (PHP/ThemeRoller)</title>
<script src="http://webspirited.com/tagit/demo/js/jquery.1.7.2.min.js"></script>
<script src="http://webspirited.com/tagit/demo/js/jquery-ui.1.8.20.min.js"></script>
<script src="http://webspirited.com/tagit/js/tagit.js"></script>
<link rel="stylesheet" type="text/css" href="http://webspirited.com/tagit/demo/css/jquery-ui-base-1.8.20.css">
<link rel="stylesheet" type="text/css" href="http://webspirited.com/tagit/css/tagit-awesome-blue.css">
<script type="text/javascript">
$(function () {
$('#demo3').tagit();
$('#demo3GetTags').click(function () {
showTags($('#demo3').tagit('tags'))
});
$('input[type=submit]').click(function(){
tag = $('#demo3').tagit('tags');
console.log(tag);
for (var i in tag)
$('form').append("<input type='hidden' name='tags[]' value='"+tag[i].value+"' >");
});
function showTags(tags) {
console.log(tags);
var string = "Tags (label : value)\r\n";
string += "--------\r\n";
for (var i in tags)
string += tags[i].label + " : " + tags[i].value + "\r\n";
alert(string);
}
});
</script>
<!-- tags -->
<form method="post" id="add_tag" action="" name="add_tag">
<button id="demo3GetTags" value="Get Tags">Get Tags</button>
<ul id="demo3" name="tags[]"></ul>
<br />
<input type="submit" name="submit_tag" value="Submit Tag" />
</form>
use select:true. and make sure you give a name to your <ul>
try this
<ul id="demo3" name="tags[]"></ul> //<-- array to post multiples
$('#demo3').tagit({triggerKeys:['enter', 'comma', 'tab'],select:true});
here is the link to the docs..

Categories