php jquery ajax checkbox validation - php

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.

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.

Validate if value in input field is an Instagram URL in blade.php

I am using blade.php in my development, and I have a concern in validating if the input is a valid instagram url. I have tried doing this:
<form class="search_form" id="apply" action=" method="post">
#csrf
<label>
<input type="url" pattern="https?://.+" required id="instagram" value="" placeholder="Instagram Post URL (Paste Here)">
</label>
<div class="flex_box">
<button class="btn pink applyfnsh_btn" type="button" id="save">Confirm</button>
</div>
</form>
UPDATE this modal is displayed after validation
<div class="applyfnsh_modal">
<div class="applyfnsh_box">
<div class="modal_close">
<img src="../../assets/images/close.png" alt="close">
</div>
<p>Success</p>
</div>
</div>
modal.js
$(".applyfnsh_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$(".applyfnsh_modal").toggleClass("open");
});
$(".applyfnsh_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.applyfnsh_box').length) {
$(".applyfnsh_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
location is here
<script src="{{ url('/assets/js/modal.js') }}"></script>
And by the way, I'm using ajax in saving data to db so that page is not refreshed.
<script>
$(document).on("click", "#save", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "post",
url: '/contest/apply/{{ $contest->id }}',
data: {url : $("#instagram").val(), user_id: 1, contest_id: {{ $contest->id }} },
success: function(store) {
},
error: function() {
}
});
});
</script>
This isn't working and even processes the data when the button is clicked even if the input is not a url or empty.
Is there a way to do it without making a function?
here it is :
$(document).on("click", "#save", function() {
var instagramLink = $('#instagramLink').val();
var pattern = new RegExp('https://www.instagram.com/p/(.+?)', 'g');
if((instagramLink != undefined || instagramLink != '') && instagramLink.match(pattern)){
alert(instagramLink + 'is valid');
/*
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
url: '/contest/apply/{{ $contest->id }}',
data: {url :instagramLink, user_id: 1, contest_id: {{ $contest->id }} },
success: function(store) {
},
error: function() {
}
});
*/
}else{
alert('Please Enter Valid Instagram Link');
$('#instagramLink').val('');
// show modal
$('.applyfnsh_modal').modal('open');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<form class="search_form" id="apply" action="" method="post">
<label>
<input type="url" required id="instagramLink" value="" placeholder="Instagram Post URL (Paste Here)" class="form-control"/>
</label>
<div class="flex_box">
<button class="btn btn-primary" type="button" id="save">Confirm</button>
</div>
</form>
</body>
</html>
update-2 : remove your existing scripts :
$(".applyfnsh_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$(".applyfnsh_modal").toggleClass("open");
});
$(".applyfnsh_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.applyfnsh_box').length) {
$(".applyfnsh_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
display modal using this way when it is required to display :
to OPEN MODAL : $('.applyfnsh_modal').addClass('open');
to CLOSE MODAL : $('.applyfnsh_modal').removeClass('open');
so
if (validation successfull){
// submit form using AJAX
}else{
$('.applyfnsh_modal').addClass('open');
}
also create one function to close modal :
$(document).on('click','.modal_close',function(){
$('.applyfnsh_modal').removeClass('open');
});

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

Interactive forms with PHP and Ajax via JQuery

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.
});

Categories