Ok I have a onchange event on a select field. It now works great. When the dropdown "networks" is changed it refreshes the second dropdown. I also want the ajax code at the top to trigger on page load as well as onchange so the second list gets populated. This is due to it being on an edit page. Here is the ajax call im using first
function get_cities(networks) {
$.ajax({
type: "POST",
url: "select.php", /* The country id will be sent to this file */
beforeSend: function () {
$("#folder").html("<option>Loading ...</option>");
},
//data: "idnetworks="+networks,
data: "idnetworks="+networks +"&doc="+ <?php echo $row_rs_doc['parentid']; ?>,
success: function(msg){
$("#folder").html(msg);
}
});
}
now the two dropdown boxes
<label for="networks"></label>
<select name="networks" id="networks" onChange='get_cities($(this).val())'>
<?php
do {
?>
<option value="<?php echo $row_rs_net['idnetworks']?>"<?php if (!(strcmp($row_rs_net['idnetworks'], $row_rs_doc['network']))) {echo "selected=\"selected\"";} ?>><?php echo $row_rs_net['netname']?></option>
<?php
} while ($row_rs_net = mysql_fetch_assoc($rs_net));
$rows = mysql_num_rows($rs_net);
if($rows > 0) {
mysql_data_seek($rs_net, 0);
$row_rs_net = mysql_fetch_assoc($rs_net);
};
?>
</select>
<select name="folder" id="folder">
</select>
You can use .trigger() to trigger a change event onto the select-box so the onchange code will be called like it would if the user just switched the option.
jQuery('#networks').trigger('change');
Just include this into the load event/function for the page.
jQuery(document).ready(function() {
jQuery('#networks').trigger('change');
});
I'm not 100% clear what you want but the standard way to do something with JQuery when the page is loaded, is to use
$(document).ready(handler)
This waits till the page is "ready" which is better.
So, in your document head you'd have something like this...
<script type="text/javascript">
$(document).ready( function(){
do_some_stuff();
});
</script>
Can't you just call get_cities($('#networks').val()) when the DOM is ready?
$(function() { // will be run by jQuery when DOM is ready
get_cities($('#networks').val());
});
Related
I tried to coding it. I am still getting stuck over it. The main goal was if user select value from mysqli database selected it and send the values to other pages. I know people recommend it use by AJAX. I tried to use it. still not working. I'll put details code below.
Main pages Code(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
click
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
as alert box i am getting value of it but second pages get error that key value doesn't exist. here the second one pages (database1.php) -
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
so what the problem occurred?
UPDATED ANSWER
Thanks to #swati which she mentioned that use form tag instead of AJAX (i know its simple answer) still by the way thanks for answer. :)
UPDATED CODE FULL -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
SECOND PAGE(database1.php) CHANGES LITTLE -
$database=$_GET['tables'];
You are calling each loop on page load that will give you the already selected value not the value which is selected by user.Also , this loop is not need as you have to pass only one value .
Your script should look like below :
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
Also , as you are using ajax no need to give href="database1.php" to a tag because you are calling this page using ajax .i.e: Your a tag should be like below :
<a>click</a>
And whatever you will echo in php side will be return as response to your ajax .So , your alert inside success function will show you that value.
I have a drpcategory dropdown in a form. I will just paste the dropdown code below;
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
Then I AJAX post every time I make a selection in the above drpcategory dropdown as below;
<script>
$(function(){
$('#drpcategory').on('change',function()
{
$.ajax({
method: 'post',
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
});
});
</script>
This seems to be currently working as I'm getting outputs like below in Chrome Browser > Inspect > Network tab every time I make a selection in drpcategory. Here is the screenshot;
The question is how can I capture this AJAX post data using PHP within the same page and echo it within the same page? So far I have tried;
<?php
if(isset($_POST['drpcategory']))
{
echo 'POST Received';
}
?>
I'm looking for a solution using only PHP, JQuery and AJAX combined.
This question was later updated and answered here:
AJAX POST & PHP POST In Same Page
First of all, this line -> type: $(this).attr('post') should be type: $(this).attr('method'),. So this will give the value ** type:post** and
As far as i understand, you are asking to send ajax whenever you select options from drpcategory. Why are you submitting the entire form for this. If i where you, i should have done this problem by following way
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
On you php side, you can get your data like,
echo $_POST['drpcategory'];
I recommend you read the documentation for the ajax function, I tried to replicate it and I had to fix this:
$.ajax({
// If you don't set the url
// the request will be a GET to the same page
url: 'YOU_URL',
method: 'POST', // I replaced type by method
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
http://api.jquery.com/jquery.ajax/
OUTPUT:
First change to $value
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category2 = file($category, FILE_IGNORE_NEW_LINES);
foreach($category2 as $value)
{
echo "<option value='".$value."'>".$value."</option>";
}
?>
</select>
then add url
<script>
$(function()
{
$('#form').submit(function(e)
{
e.preventDefault();
$.ajax({
url:'folder/filename.php',
type: 'post',
data: '{ID:" . $Row[0] . "}',
success: function(result) {
console.log(result);
}
});
});
$('#drpcategory').on('change',function()
{
$("#form").submit();
});
});
try request
if(isset($_REQUEST['ID']))
The result will/should send back to the same page
Please try this code:
$.post('URL', $("#FORM_ID").serialize(), function (data)
{
alert('df);
}
I think you have an eroror syntax mistake in ajax jQuery resquest because ajax post 'http://example.com/?page=post&drpcategory=Vehicles' does not return this type url in browser Network Tab.
<?php var_dump($_POST); exit; ?> please do this statment in your php function if anything posted to php page it will dump.
Here ajax request example
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
`
It sounds like you're trying to troubleshoot several things at once. Before I can get to the immediate question, we need to set up some ground work so that you understand what needs to happen.
First, the confusion about the URL:
You are routing everything through index.php. Therefore, index.php needs to follow a structure something like this:
<?php
// cleanse any incoming post and get variables
// if all your POST requests are being routed to this page, you will need to have a hidden variable
// that identifies which page is submitting the post.
// For this example, assume a variable called calling_page.
// As per your naming, I'll assume it to be 'post'.
// Always check for submitted post variables and deal with them before doing anything else.
if($_POST['calling_page'] == 'post') {
// set header type as json if you want to use json as transport (recommended) otherwise, just print_r($_POST);
header('Content-Type: application/json');
print json_encode(array('message' => 'Your submission was received'));
// if this is from an ajax call, simply die.
// If from a regular form submission, do a redirect to /index.php?page=some_page
die;
}
// if you got here, there was no POST submission. show the view, however you're routing it from the GET variable.
?>
<html>
(snip)
<body>
<form id="form1" method="post">
<input type="hidden" name="calling_page" value="page" />
... rest of form ...
<button id="submit-button">Submit</button>
</form>
}
Now, confusion about JQuery and AJAX:
According to https://api.jquery.com/jquery.post/ you must provide an URL.
All properties except for url are optional
Your JQuery AJAX will send a post request to your index.php page. When your page executes as shown above, it will simply print {message: "Your submission was received"} and then die. The JQuery will be waiting for that response and then do whatever you tell it to do with it (in this example, print it to the console).
Update after discussion
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
<!-- HTML to receive AJAX values -->
<div>
<label>Item</label>
<select class="" id="drpitem" name="drpitem"></select>
</div>
<script>
$(function(){
$('#drpcategory').on('change',function() {
$.ajax({
url: '/receive.php',
method: 'post',
data: $(this).serialize(),
success: function(result) {
workWithResponse(result);
}
});
});
});
function workWithResponse(result) {
// jquery automatically converts the json into an object.
// iterate through results and append to the target element
$("#drpitem option").remove();
$.each(result, function(key, value) {
$('#drpitem')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
</script>
receive.php:
<?php
// there can be no output before this tag.
if(isset($_POST['drpcategory']))
{
// get your items from drpcategory. I will assume:
$items = array('val1' => 'option1','val2' => 'option2','val3' => 'option3');
// send this as json. you could send it as html, but this is more flexible.
header('Content-Type: application/json');
// convert array to json
$out = json_encode($items);
// simply print the output and die.
die($out);
}
Once you have everything working, you can take the code from receive.php, stick it in the top of index.php, and repoint the ajax call to index.php. Be sure that there is no output possible before this code snippet.
The whole idea is to limiting the number checkboxes through dropdown, the approach is:
I have dropdown with following code
<select name="form[norequnit][]" id="norequnit" class="rsform-select-box">
<option value="">...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>01</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>02</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>03</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>04</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>05</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>06</label>
And some check boxes which are loading by ajax and below code is running to get dropdown value and also after ajax part to limit the number of selection based on the selected dropdown,
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#norequnit").on("change", function () {
$('#unitcount').html($(this).find('option:selected').text());
});
$( document ).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
var nux = $('#unitcount').text();
$("input[name=chk]").change(function(){
var max= nux;
if( $("input[name=chk]:checked").length == max )
{
$("input[name=chk]").attr('disabled', 'disabled');
$("input[name=chk]:checked").removeAttr('disabled');
}
else{
$("input[name=chk]").removeAttr('disabled');
}
})
});
});
</script>
Problem:
variable "nux" get value only in first attempt by selecting dropdown, for example 5 so you to limit the boxes to 5 checks, but after this if you change dropdown to any other number the checkbox limitation remains on 5, in other word "nux" wont get new variable.
There's a few things wrong with your code, I'll try and go through them piece by piece with explanations and fixes.
Select onChange handling:
Separate your data from your view
Use val() instead of text() to get a select's current value
Code:
var nux; // 1. This will hold the value of nux for use in your script
$("#norequnit").on("change", function () {
nux = $(this).val(); // 1. Save the data, 2. Use using val()
$('#unitcount').html(nux); // 1. Use the data
});
Do you really need to use ajaxComplete?
I don't think ajaxComplete is the right way to go about responding to an ajax call (I could be wrong, I don't have all your code in front of me). Below I've done a best guess as to what you should (maybe, probably) do.
Code:
// Assuming you've got your ajax call somewhere else, use the "success"
// handler instead of the "ajaxComplete" function
$.ajax({
url: yourUrl,
method: 'get',
data: {
param1: 'value1',
param2: 'value2', // etc
},
success: function(html) {
// Presumably this is the HTML for your checkboxes, so add them
// to the DOM
$('#norequnit').after(html);
// And the only thing that really should go here otherwise is
// your bit of debug logging
console.log("Triggered ajax success handler.");
}
});
Use console.log if you are just outputting debug text
Maybe you actually do want to print the message on the page, if so you can ignore this. At very least, be aware of this wonderful debug-enabling tool. You can hit F12 (developer console) in your browser to view the output.
console.log("Triggered ajaxComplete handler.");
Move your checkbox onChange handler outside of any ajax closures
You could run into some incredibly hard to debug issues otherwise.
Code:
$(document).on('change', 'input[name="chk"]', function() {
// Handler code here
});
Notice the slightly different call to on, which uses the document object and includes the context parameter. This ensures any objects added to the DOM after the event handler is registered will still be handled.
All of it together
jQuery(document).ready(function($) {
var nux;
$("#norequnit").on("change", function () {
nux = $(this).val();
$('#unitcount').html(nux);
});
$.ajax({
url: yourUrl,
method: 'get',
data: {
param1: 'value1',
param2: 'value2', // etc
},
success: function(html) {
$('#norequnit').after(html);
console.log("Triggered ajax success handler.");
}
});
$(document).on("change", 'input[name="chk"]', function() {
if ($('input[name="chk"]:checked').length == nux) {
$('input[name="chk"]').attr('disabled', 'disabled');
$('input[name="chk"]:checked').removeAttr('disabled');
// Alternatively you could do this:
$('input[name="chk"]').not(':checked').attr('disabled', true);
} else {
$("input[name=chk]").removeAttr('disabled');
}
});
});
I try to use Ajax (my first time) and i don't know what i am doing bad. I have two files: home.html and ajax.php
On first one (home.html) i have this
<html>
<head>
<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#Client_ID').live('change', function(event) {
$.ajax({
url : 'ajax.php',
type : 'POST',
dataType: 'json',
data : $('#myform').serialize(),
})
.done(function(data) {
for(var id in data) {
$(id).val( data[id] );
}
});
});
});
</script>
</head>
<body>
<form id='myform'>
<select name='Client_ID' id='Client_ID'>
<option value=''>Select</option>
<option value='1'>Client 1</option>
<option value='2'>Client 2</option>
</select>
<input type='text' name='address1' id='address1'>
</form>
</body>
</html>
and my AJAX.php file it's
<?php
define('WP_USE_THEMES', false);
require('../wp-blog-header.php');
global $wpdb;
$clientid = $_POST['Client_ID']; // Selected Client Id
$result = $wpdb->get_row( "SELECT * FROM wp_com_plantillas WHERE id=$clientid" );
$addr1 = $result->asunto;
$arr = array( 'input#address1' => $addr1);
echo json_encode( $arr );
?>
On database connection i use wordpress global var $wpdb.
To test ajax.php i change POST by GET and load url like ajax.php?client_id=1 and result it's ok, but when i test it on home.html, when dropdown change, input don't fill.
Thank you so much
If you are using Wordpress, consider taking a look in this article that explains how to properly declare ajax on Wordpress
Also, make usage of your Developer Tools, if you use Chrome. Pressing F12, you can see a tab named Network. Every request that your page does, it will be logged there. If you want to filter only AJAX requests, click on filter button then select XHR. Each line is a request and each request, when clicked, can provide information about the response. Check if that response is working, if response code is actually 200.
I have created one application in that there is one text box for searching information from table. Although i have written the code when we enter the character in search text box, after accepting one character control goes out of textbox.
this is my code for searching`
<script type="text/javascript">
$(document).ready(function()
{
var minlength = 1;
$("#searchTerm").keyup(function () {
value = $(this).val();
if (value.length > minlength )
{
searchTable(value);
}
else if(value.length < minlength)
{
searchTable("");
}
});
});
function searchTable(value)
{
$.ajax({
type: "GET",
url: "dispatient.php",
data:({search_keyword: value}),
success: function(success)
{
window.location.href = "dispatient.php?search_keyword="+value;
$("#searchTerm").focus();
},
error: function()
{
alert("Error occured.please try again");
},
complete: function(complete)
{
$("#searchTerm").focus();
},
});
}
<input id="searchTerm" Type="text" class="search_box" placeholder="Search"
value = <?php echo $_GET['search_keyword'] ?> >
`
Please suggest to me..
thanks in advance..
value is default attribute of javascript try to change the variable name of value into something like searchData
In your success callback, you are redirecting the page to dispatient.php. I believe, this is the same page that has the search functionality. Once you redirect, the page is reloaded again and there is no point in writing:
$("#searchTerm").focus();
Since, you are already using AJAX, try loading the data from success on to your page through JavaScript/jQuery without reloading the page.
create one div and load your data in that instead of reloading entire page.
try something like this instead of ajax Call
<div id="searchResult"></div>
$("#searchResult").load("search.php?search_keyword=value",function(){
//your callback
});