I do not use submit button
I want the selected value from the user sent to the test1.php page, but when the user selects an option nothing happen in the page, and the value is not sent to the test1.php page
Is there any mistake in my code, or did I miss something ?
test2.php
<?php include_once 'database.php';
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$('.category').change(function() {
var category = $('.category option:selected').val();
alert('category changed to ' + category);
$.ajax({
method: "POST",
url: "test1.php",
data: {
category1: $(this).val()
},
success: function(data) {
console.log(data);
}
});
});
});
</script>
</head>
<p> Filter By Category</p>
<select id="category" class="category">
<?php
$query = mysqli_query($conn,"select * from category ");
while($category = mysqli_fetch_array($query)) {
echo "<option value='" . $category['cat_name'] . "'>" . $category['cat_name'] . "</option> ";
}
?>
</select>
test1.php
<?php
include_once 'database.php';
if (isset($_POST['category1'])) {
$category = $_POST['category1'];
echo $category;
}
?>
is that all your file ? did you forget to include jquery ?
I just did the same script as yours but in html, and console said $ not found, after add jquery that's working
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$('.category').change(function() {
$.ajax({
method: "POST",
url: "https://webhook.site/2d574d22-5570-46f2-b5bd-343d715adff4",
data: {
category1: $(this).val()
},
success: function(data){
console.log(data);
}
});
});
});
</script>
</head>
<body>
<p> Filter By Category</p>
<select id="category" class="category">
<option value='1'>One</option>
<option value='2'>two</option>
</select>
</body>
</html>
here is the webhook to check your request, it is like test1.php but just for debugging purpose https://webhook.site/#!/2d574d22-5570-46f2-b5bd-343d715adff4/e3406220-f58e-45be-a4ef-13d8d3e0b0d3/1
here are some advices:
inspect your page using developer tools, maybe there are some errors
check with console.log .val()
hope this help
Related
I would like to know, how can I pass <select> element from html to PHP file by ajax.
Here is my index.php:
<p>
<form action = "display.php" method="post" enctype="multipart/form-data">
Select:
<select name="chosenOption" id="chosenOption" style="width:100px"">
<?php
include 'dbConnection.php';
$query = $db->query("SELECT id,name FROM products");
while($row = $query->fetch_assoc())
{
echo'
<option value="'.$row['id'].'">'.$row['name'].'
</option>';
}
?>
</select>
Display : <input type="submit" name="display" value="Display">
</form>
</p>
My display.php, where i have ajax method:
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption:chosenOption},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
<div class="result"></div>
And products.php, where i want to pass selected < select > element:
<?php
include 'dbConnection.php';
$chosenOption = $_POST["chosenOption"];
// Display section
$query = $db->query("SELECT cost,description FROM products_info WHERE products_id=$chosenOption);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
echo "Actual cost and description: ".$row["cost"]. " ".$row["description"]. ;
}
} else {
echo "No data";
}
?>
I expect that selected option from index.php will be pass to products.php by ajax and display the appropriate message. The current code does not work. Any idea?
You can't refer to $("#chosenOption") in display.php, because the page has been reloaded. You need to use $_POST['chosenOption'], since that was submitted by the form.
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption: <?php echo $_POST['chosenOption']; ?>},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
<div class="result"></div>
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
I'm trying to use ajax on a select tag with 2 options, but it's not getting the $_POST for some reason. It prints out the "---", but it does not print out the $_POST value, which is either 1 or 2. I'm not sure what I did wrong. Please take a look at my code:
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
<?php
echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"input\",\"name\",\"output\")'>";
echo "<option value = '1'> 1 </option>";
echo "<option value = '2'> 2 </option>";
echo "</select>";
echo "<div id = 'output'></div>";
?>
newtestx.php
<?php
$name = $_POST['name'];
echo $name."---";
?>
You are sending a POST parameter with the key "select" to the server in your AJAX call:
data: { select: $(type+'[name='+theName+']').val()},
In newtestx.php you are trying to retrieve the value from a POST parameter with the key "name" - which doesn't exist:
$name = $_POST['name'];
You could fix this easily by giving the parameter keys the same name. If you would look for $name = $_POST['select'] the parameter would be found.
Inline Javascript is considered bad practice and there's no need to echo out the HTML markup, it makes the mark up harder to work with.
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="[link to your javascript file here]"></script>
<select name='numbers' class="postValueOnChange" data-id-to-update="output" data-post-url="newtestx.php">
<option value='1'>1</option>
<option value='2'>2</option>
</select>
<div id='output'></div>
Javascript file
$(document).ready(function () {
$('.postValueOnChange').change(postSelectedValue);
function postSelectedValue(e) {
var $self = $(this);
var url = $self.data('post-url');
var $elementToUpdate = $('#' + $self.data('id-to-update'));
var jqxhr = $.ajax({
type: "POST",
url: url,
data: {
selected: $self.val()
}
});
jqxhr.done(function (data) {
$elementToUpdate.html(data);
});
jqxhr.fail(function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
});
}
});
newtestx.php
<?php
$name = $_POST['selected'];
echo $name."---";
?>
You are sending post param select and trying to receive as $_POST['name'].
Make sure they match...either both as name or as select
First, Since you are using jQuery, why are you still using inline javascript?
Well I suggest you first to restrucure your code around the jQuery change event:
$(document).ready(function() {
$('select').change(function(e) {
e.preventDefault();
var selected = $('.select option:selected').val();
var id, theName, url= ...// get it from the DOM
$.ajax({
type: "GET",
url: url,
data: { select: selected},
error: function(xhr,status,error){alert(error);},
success:function(data) {
$('#'+id).html(data);
}
});
});
});
Second, why are you coding HTML with PHP, you are making yourself struggle and lose time only with quotes and double quotes, and no-needed spaces.
<form action="">
<select name="name">
<option value="1">1</option>
<option value="1">1</option>
</select>
</form>
<div id="output"></div>
I am working on a script that echoes an answer based on a selected value. This will be multiple values later on but for now i'm just testing.
The php script is called trough AJAX so the results will show on the same page.
The only problem is that my variable $brand in this case isn't passed so the script will always return my else statement. I have included the variable in the echo to check wether it was passed, which it isn't. What is going wrong here?
this is my index file code:
<?php
session_start();
?>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="JS/jquery-1.10.2.js" ></script>
<script>
function myCall(){
var request = $.ajax({
url: "process.php",
type: "post",
dataType: "html"
});
request.done(function(msg) {
$("#response").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<div id="formulier">
<form method="" action="" name="form" id="form">
<label for="brand">Brand</label>
<select id="brand" name="brand">
<option value="" >- Select -</option>
<option value="1">Marlboro (1)</option>
<option value="2">Pall Mall (2)</option>
</select>
<input type="button" value="submit" onclick="myCall();">
</form>
</div>
<div id="response">
</div>
This is my php file (process.php):
<?php
session_start();
$brand = $_POST['brand'];
if( $brand == '1'){
echo "Value is 1";
}
else{
echo "Value is: ".$brand;
}
?>
I see several problems in your script:
at no point you reference the actual fields of your form
I'd rather put the handlers inside the ajax call
Try this:
function myCall(){
var request = $.ajax({
url: "process.php",
type: "post",
dataType: "html",
data: $('#form').serialize(), //here you send the form fields
success: function(msg) {
$("#response").html(msg);
},
error: function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
}
}
You should use json_encode (http://us1.php.net/json_encode) for responding in process.php.
Make sure you set the session variable and read it later (in your php else block), e.g.,
$_SESSION["brand"] = "2";
You should try the define the form attributes
<form method="POST" action="" name="form" id="form">
So, I have a search form in a php page (top.php) which is an include for the site I'm working on, one php page where all the mySQL stuff happens and the results are stored in a variable and echoed (dosearch.php) and lastly a php page where the results are displayed in a div through jQuery (search.php). This is the javascript code:
$(document).ready(function(){
$('#search_button').click(function(e) {
e.preventDefault();
var searchVal = $('#search_term').attr('value');
var categoryVal = $('#category').attr('value');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: "search_term=" + searchVal + "&category=" + categoryVal,
beforeSend: function() {
$('#results_cont').html('');
$('#loader').html('<img src="layout/ajax-loader.gif" alt="Searching..." />');
if(!searchVal[0]) {
$('#loader').html('');
$('#results_cont').html('No input...');
return false;
}
},
success: function(response) {
$('#loader').html('');
$('#results_cont').html(response);
}
});
});
});
The #search_term and #category fields are in top.php, the other divs (#loader and #results_cont) are in search.php. How would I go by in order to make the form submit and display the results in search.php from the top.php without problems? It works perfectly if the form and javascript are in search.php but I can't seem to separate those and make it work. What am I doing wrong?
PS. Sorry if I'm not clear enough, am at work, really tired. :(
SPLITTING:
<? include('functions-or-classes.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<? include('js-script.php'); ?>
</head>
<body>
<? include('results-div.php'); ?>
<? include('search-form.php'); ?>
</body>
</html>
You should just respect this order then you can split the code in different pieces and include it into your main php file;
PS: peraphs your code should look like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
$(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
var searchVal = $('#search_term').val();
var query = $(this).serialize(); // search_term=lorem&category=foo
if (!searchVal) {
$('#results_cont').html('No input...');
} else {
$('#results_cont').html('<div id="loader">'+
'<img src="layout/ajax-loader.gif" alt="" /><div>');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: query,
success: function(response) {
$('#results_cont').html(response);
}
});
}
});
});
</script>
</head>
<body>
<form id="search-form">
<input type="text" id="search_term" name="search_term" />
<select id="category" name="category">
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<input type="submit" name="search_button" />
</form>
<div id="results_cont"></div>
</body>
</html>
you can make your search_button redirect to your search.php an do the work when the pages is loaded instead of doing it on the click event.
and use $_GET['Search'] on the search page
and your url should look like this
/search.php?Search=1337