I'm trying to send a form to php for validation before inserting data into mySQL. I'm trying to use AJAX to do it. I am unable to get through the validation process when sending a <select> <option>. If I remove the validation for the <select <option> the form processes as expected. When sending via AJAX I get the following response in console:
When I process the form by just sending it without AJAX, the validation works fine. Below is my code:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Validate SelectWith Ajax</title>
<meta charset="UTF-8">
</head>
<body>
<form id="frm" action="process.php" method="post" novalidate>
<label for="yourOptions">Your Options</label>
<select id="yourOptions" name="yourOptions" required>
<option value="" hidden selected>Select One</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
</select>
<input type="submit" value="Submit" name="Submit">
<?php echo "hello"; ?>
</form>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<script src="ajax.js"></script>
</body>
</html>
PHP
<?php
$errors = array();
$data = array();
if($_SERVER["REQUEST_METHOD"] === "POST") {
if($_POST["yourOptions"] == "") {
$errors["yourOptions"] = "Please Select One";
}
if(!empty($errors)) {
$data["success"] = false;
$data["errors"] = $errors;
} else {
$data["success"] = true;
$data["message"] = "Success!";
}
echo json_encode($data);
}
?>
jquery AJAX
alert("loaded");
$(document).ready(function() {
$("#frm").submit(function(event) {
alert("sub");
event.preventDefault();
console.log(typeof document.getElementById("yourOptions"));
$(".form-group").removeClass("is-invalid");
$(".text-muted").remove();
var formData = {
"yourOptions" : $("input[name=yourOptions]").val()
};
$.ajax({
type : "POST",
url : "process.php",
data : formData,
dataType : "json",
encode : true
})
.done(function(data) {
console.log(data);
if(!data.success) {
if(data.errors.yourOptions) {
$("#yourOptions").addClass("is-invalid");
$("#frm").append("<span class='text-muted'>" + data.errors.yourOptions + "</span>");
}
} else {
$("form").append("<span class='alert alert-success'>" + data.message + "</span>");
}
})
.fail(function(data) {
alert("failed");
console.log;
});
});
});
The data-type is object, but then again, so were the other fields. How do I get php to process the selected option?
Replace
$("input[name=yourOptions]").val()
with
$( "#yourOptions" ).val()
Serialize ajax will post all data you want
$(document).ready(function(){
$('#frm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"process.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data === 'ok'){
$('#result').html(data);
} else {
$('#result').html(data);
$('#frm')[0].reset();
}
}
});
});
});
How you show result :
<div id="result"></div>
See this question for detailed explanition and more : Jquery ajax setTimeout after form succes not redirecting?
Related
I can't seem to get the selected option value from the select.php into the value_selected.php file.The console.log(data) displayed nothing. Why is that?
select.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="js/jquery-3.2.0.min.js"></script>
<form method="POST" action="">
<label for "sel_opt">Select value: </label>
<select name="sel_opt" id="sel_opt">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input name="submit" type="submit" id="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
url:"http://localhost/value_selected.php",
type:"POST",
success:function(data)
{
console.log(data);
$('#result').html(data);
}
});
});
});
</script>
</body>
</html>
value_selected.php
<?php
$output = "";
if(isset($_POST["submit"])) {
if(isset($_POST["sel_opt"])) {
$val = $_POST["sel_opt"];
if ($val == 1) {
$output = "<p>Value 1 selected</p>";
} else {
$output = "<p>Value 2 selected</p>";
}
echo $output;
}
?>
Add data: to your ajax config object with form values.
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
url:"http://localhost/value_selected.php",
type:"POST",
data: $('form').serialize(),
success:function(data)
{
console.log(data);
$('#result').html(data);
}
});
});
});
</script>
How do I want to post a form using jquery serialize function? I tried to post the form value but on the php part, the value is not shown. Below are my codes:
html
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
jQuery
$(document).on("click", "#submit", function(e){
e.preventDefault();
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
data = $('form').serialize();
$.post('result.php',
{
data : data
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
});
PHP
if(isset($_REQUEST["sort"])){
$sort = $_REQUEST['sort'];
$id_staff = $_REQUEST['id_staff'];
echo "Your Id : $id_staff <p/>";
echo "You choose : $sort";
}
If I console.log(data), I get: id_staff=12345&sort=1
Your server is receiving a string that looks something like this (which it should if you're using jQuery serialize()):
"param1=someVal¶m2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params should then be an array that contains all the form element as indexes
If you are using .serialize, you can get rid of this:
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
You data will be available as follows with .serialize:
your-url.com/sort=yoursortvalue&id_staff=youridstaff
It should be:
$(document).ready(function(e) {
$("#myform").submit(function() {
var datastring = $( this ).serialize();
$.post('result.php',
{
data : datastring
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
})
})
On PHP side you simple need to access it using the $_GET['sort'].
Edit:
To view the data, you should define a div with id result so that the result returned is displayed within this div.
Example:
<div id="result"></div>
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
I am able to do it this way:
jQuery
<script type="text/javascript">
$(document).ready(function() {
var form = $("#myform");
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'result.php',
data: form.serialize(),
success: function(response) {
console.log(response);
$("#result").html(response);
},
error: function() {
alert('Error Submitting');
}
})
})
})
</script>
PHP
if(isset($_POST["id_staff"])){
$sort = $_POST['sort'];
$id_staff = $_POST['id_staff'];
echo "<p>Your Id : $id_staff</p>";
echo "You choose : $sort";
}
Do give a comment if it need improvement or better solution.
I have a select option, to get the value from this, I used jquery (please see below code). After I display the selected value in the textbox, I'm now having problem on how to get the value of textbox to process a such code. Even simply echo of the value is not working. What's the problem with the code? Please help. Thanks.
Select option:
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
Jquery:
$('#shiptype').change(function () {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
}
});
Text Field:
<input type='text' id='strkey' name='keyname' />
Display the value:
$key = $_POST['keyname'];
echo $key;
Please try this code :
HTML file contains this below code. File name test.html.
Form to submit your data.
<form id="frm_post">
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
<input type="text" name="name" id="strkey">
<input id="btn_post" type="button" name="submit" value="Submit">
</form>
This is a div for your output.
<div>
<p id="output"></p>
</div>
This is jquery for ajax call function.
<script>
$(document).ready(function(){
$('#shiptype').change(function() {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
}
});
$("#btn_post").click(function(){
var parm = $("#frm_post").serializeArray();
$.ajax({
type: 'POST',
url: 'your.php',
data: parm,
success: function (data,status,xhr) {
console.info(data);
$( "#output" ).html(data);
},
error: function (error) {
console.info("Error post : "+error);
$( "#output" ).html(error);
}
});
});
});
</script>
And for PHP File to get the post value like this below. File name your.php.
<?php
// $key = $_POST['keyname'];
// echo $key;
print_r($_POST);
?>
Your post result will be show up in output id. Hope this help you out. :D
Why I can not get response from php by using jQuery Ajax? When I click the "page" buttons, the weblink will change from:
http://localhost/jQuery1.html
to something like:
http://localhost/jQuery1.html?state_chosen=Alabama&Type=&page=1
However, no echo-ed results from PHP.
HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("form").change(function(){
$.ajax({
type:"POST",
url:"passdata.php",
data: $('form').serialize(),
success: function(data){
$('#result').html(data);
} });
}); });
</script>
</head>
<body>
<form >
<select class="dd1" name="state_chosen">
<option selected value = ""> Location </option>
<option value="Alabama" > US: Alabama </option>
</select>
<select class="dd2" name="type">
<option selected value = ""> Type </option>
<option value="Plumber" > Plumber </option>
</select>
<button name="page" value="1" >1</button>
<button name="page" value="2" >2</button>
</form>
<div id="result"></div>
</body>
</html>
passdata.php
<?php
echo '<div>' .$_POST['state_chosen']." <br>". $_POST['type']."<br>". $_POST['page']. '</div>';
?>
I fully tested your code.
The error was just the extra semi-colon ; after the closing brace of the ajax success function.
I often label end braces so I can keep track. E.g. //END ajax block
Use this, it will work:
<script>
$(document).ready(function(){
$("form").change(function(){
$.ajax({
type:"POST",
url:"passdata.php",
data: $('form').serialize(),
success: function(data){
$('#result').html(data);
} //*****here was the error*****
}); //END ajax
}); //END form.change()
}); //END document.ready
</script>
Your jQuery should look something like:
<script>
$(document).ready(function(){
// Sorry, I put the form event in the (document) which is wrong.
$("form").change(function(form) {
$.ajax({
type:"POST",
url:"passdata.php",
data: $(this).serialize(),
success: function(data){
$('#result').html(data);
}
});
// This will stop the form being submitted
// form.preventDefault; Remove if you need submission
});
});
</script>
Also, as mentioned by #Robert Cathey, check your $_POST on your passdata.php page. You will get an Undefined index error.
Add a console.log to your success function so you can see what your PHP file is actually returning.
$(document).ready(function(){
$("form").change(function(){
$.ajax({
type:"POST",
url:"passdata.php",
data: $(this).serialize(),
success: function(data){
console.log(data)
//$('#result').html(data);
}
});
});
});
It's a problem with BUTTON. The form consider button as type=submit
So when you pressed to the button it's a submit event was issued. please try the following code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function onFormChange(){
$.ajax({
type:"POST",
url:"passdata.php",
data: $('form').serialize(),
success: function(data){
$('#result').html(data);
}
})
}
$(document).ready(function(){
$( "form > *" ).change(function(event){
event.preventDefault();
onFormChange()
})
$( "form" ).submit(function( event ) {
event.preventDefault();
onFormChange()
});
})
</script>
</head>
<body>
<form >
<select class="dd1" name="state_chosen">
<option selected value = ""> Location </option>
<option value="Alabama" > US: Alabama </option>
</select>
<select class="dd2" name="type">
<option selected value = ""> Type </option>
<option value="Plumber" > Plumber </option>
</select>
<button name="page" value="1" >1</button>
<button name="page" value="2" >2</button>
</form>
<div id="result"></div>
</body>
</html>
I want to retrieve districts and state from the database, and also to populate second dropdown list based on first dropdown list. In my code below the values are inserted directly:
<!DOCTYPE html>
<head>
<script type="text/javascript" src="C:\Program Files\BitNami WAPPStack\apache2\htdocs \Prj\Online\jquery-1.9.1.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
var options = $('#test2 option');
$('#test1').on('change', function(e) {
$('#test2').append(options);
if ($(this).val() != 'Select') {
$('#test2 option[value!=' + $(this).val() + ']').remove();
} else {
$('#test2').val('Select');
}
});
});
</script>
<form name="form1" method="post" action="fid1.html">
<select name="test1" id="test1">
<option value="Select">Select</option>
<option value="a">TamilNadu</option>
<option value="b">Kerala</option>
<option value="c">Andhra</option>
</select>
<select id="test2" name="test2">
<option value="Select">Select</option>
<option value="a">Chennai</option>
<option value="a">Trichy</option>
<option value="a">Madurai</option>
<option value="b">Trivandram</option>
<option value="b">Cochin</option>
<option value="b">Azhapuzha</option>
<option value="c">Hyderabad</option>
</select>
</form>
</head>
</html>
for that purpose you should use Ajax call on your first drop box .
Ajax is a server side tools to fetch data from database.
Create a ajax function, for example get_country()
$(function() {
$('#test1').change( function() {
var val = $(this).val();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
now do your database query on findstate.php and use state div to show particuler state list.