Value from selected dropdown option cannot be retrieved using $_POST - php

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>

Related

Send HTML Form Select Option to PHP validation via Ajax

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?

Ajax call to same page is not working

I am getting records from database in WordPress then creating and adding value in select tag(HTML) dynamically.
<?php
global $wpdb;
$registeredUsers = $wpdb->get_results('SELECT * FROM wp_users where user_login != "Admin"',ARRAY_A);
$select='<select name="users" class="form-control" id="users">';
$select.= '<option value="Select User"> Select User</option>';
foreach($registeredUsers as $user)
{
$select.='<option value="'.$user['user_email'].'">'.$user['user_login'].'</option>';
}
$select.='</select>';
?>
I am using $select variable in Html and drop down is being displayed properly.
<form id="a" action="" method="post">
<div style="margin: 0 auto;width:500px;">
<?php echo $select ?>
</div>
</form>
I have written code to get selected drop down onchange event in jquery. It return success but I am not able to get selected value of dropdown.
<script type="text/javascript">
$(document).ready(function(){
$("select[name='users']").change(function () {
jQuery.ajax({
type: "POST",
data: $("form#a").serialize(),
success: function(data){
alert("SUCCESS");
}
});
});
});
</script>
Below code return nothing
if(isset($_POST['users'])) {
echo $_POST['users'];
}
Set url option to your page in your ajax function:)
<script type="text/javascript">
$(document).ready(function(){
$("select[name='users']").change(function () {
jQuery.ajax({
type: "POST",
url:"yourpage.php"
data: $("form#a").serialize(),
success: function(data){
alert("SUCCESS");
}
});
});
});
</script>
replace yourpage.php

How to use jQuery Ajax to pass multiple form values to php?

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>

how to send multiple ajax request and process the multiple request

Below is the ajax code to perform the subjected action but it is implemented in a manner of elaboration instead of do it with simple one.
Here implemented separate code for each ajax request and response.
please see the below code:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery- 1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#country").change(function(){
var country=$("#country").val();
$.ajax({
type:"post",
url:"getstate.php",
data:'typeId='+country,
success:function(data){
$("#state").html(data);
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state=$("#state").val();
$.ajax({
type:"post",
url:"getdistrict.php",
data:'typeId='+state,
success:function(data){
$("#district").html(data);
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#district").change(function(){
var district=$("#district").val();
$.ajax({
type:"post",
url:"getward.php",
data:'typeId='+district,
success:function(data){
$("#ward").html(data);
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#ward").change(function(){
var ward=$("#ward").val();
$.ajax({
type:"post",
url:"getslum.php",
data:'typeId='+ward,
success:function(data){
$("#slum").html(data);
}
});
});
});
</script>
</head>
<body>
Country :
<select name="country" id="country">
<option>-select your country-</option>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "dbconfig.php";
$result=sqlsrv_query($conn,"SELECT [CountryId],[Country] from toilet_Country order by Country");
while($country=sqlsrv_fetch_array($result)){
echo "<option value = $country[CountryId]>$country[Country]</option>";
} ?>
</select> <br><br>
State :
 
<select name="state" id="state">
<option>-select your state-</option>
</select> <br><br>
District :
<select name="district" id="district">
<option>-select your District-</option>
</select> <br><br>
Ward :
<select name="ward" id="ward">
<option>-select your ward-</option>
</select> <br><br>
Slum :
<select name="slum" id="slum">
<option>-select your slum name-</option>
</select> <br><br>
</body>
</html>
And i have written code in separate files to retrieve country,state,district information from database.
I am unaware of these ajax call request and response an looking for advise how can i make this code portable.
Thanks in advance.

Using jQuery's .get() to retrieve PHP data

I'm using jQuery's .ajax() to post to a PHP file called process.php. Process.php has a lot of code in it, but for simplicity's sake, let's just say it contains <?php echo 'hello'; ?>.
Is this the proper jQuery to insert process.php's results into div.results? :
$.get('process.php', function(data) {
$('.results').html(data);
});
So far it doesn't seem to be working.
Here's the HTML/Javascript file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#form").submit(function() {
var username = $('#username').attr('value');
$.ajax({
type: 'POST',
url: 'process.php',
data: 'username=' + username,
success: function() {
$('form#form').hide(function() {
$.get('process.php', function(data) {
$('.results').html(data);
});
});
}
});
return false;
});
});
</script>
</head>
<body id="body">
<form id="form" method="post">
<p>Your username: <input type="text" value="" name="username" id="username" /></p>
<input type="submit" id="submit" value="Submit" />
</form>
<div class="results"></div>
</body>
</html>
Here's process.php (greatly simplified):
<?php
/* get info from ajax post */
$username = htmlspecialchars(trim($_POST['username']));
echo $username;
?>
If you simply want to place the resulting string back into an element, use load().
$('.results').load('process.php');
However, looking at your code...
$.ajax({
type: 'POST',
url: 'process.php',
data: 'username=' + username,
success: function() {
$('form#form').hide(function() {
$.get('process.php', function(data) {
$('.results').html(data);
});
});
}
});
...shows you have misunderstood something. The correct anonymous function to assign to the success callback would be...
function(data) {
$('form#form').hide()
$('.results').html(data);
}
You could try something like this.
function ajax_login() {
if ($("#username").val()) {
$.post("/process.php", { username : $("#username").val() }, function(data) {
if (data.length) {
$("#login_form").hide();
$("#login_result").html(data);
}
})
} else {
$("#login_result").hide();
}
Then in process.php just echo out some text if the post sucesses.
process.php =>
if (isset($_POST['username'])
{
echo 'hello '.$_POST['username'];
}

Categories