drop down list send values through AJAX call - javascript

I'm new to AJAX and trying to learn basic calls through AJAX and jQuery.
I have a simple drop list of countries, where I want to select a particular country and send the value of it to server, where it would process which country was selected and give particular output. For now, it could just echo simple output in php file. There is some kind of problem with this code. I would appreciate if anyone could help me with it. thanks
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function load()
{
$.ajax({
type:"GET",
url: "test.php",
data: { country: $("#country").val()}
}).done(function(msg){
$("#right #myDiv").html(msg);
});
}
</script>
</head>
<body>
<div id="main">
<div id="left">
Select Country: <select id="country" name="country">
<option value="germany">Germany</option>
<option value="england">England</option>
</select>
<input type="button" value="Run Query" onClick="load()"></input>
</div>
<div id="right">
<div id="myDiv"></div>
</div>
</div>
test.php
<?php
$name=$_GET['country'];
if($name=="England")
{
echo "Works";
}
else
{
echo "doesnt Work";
}
?>
?>

The only issue I see is that in your PHP you have
if($name=="England")
But in your html you have
<option value="england">England</option>
It is sending over "england". "england" != "England".
Also, I would just do
$("#country").val()
instead of
$("#country option:selected").val()

if you mean too get work message from php file replace England with england, because php is case sensitive.

There is 2 errors in your code :
data: { country: $("#country option:selected").val()}
should be $("#country").val()
and
if($name=="England")
shoudl be "england"
So Here is the right code :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function load()
{
$.ajax({
type:"GET",
url: "test.php",
data: { country: $("#country").val() }
}).done(function(msg){
$("#right #myDiv").html(msg);
});
}
</script>
</head>
<body>
<div id="main">
<div id="left">
Select Country: <select id="country" name="country">
<option value="germany">Germany</option>
<option value="england">England</option>
</select>
<input type="button" value="Run Query" onClick="load()"></input>
</div>
And for the test.php :
<?php
$name=$_GET['country'];
if($name=="england")
{
echo "Works";
}
else
{
echo "doesnt Work";
}
?>
EDIT : It's pretty straight forward for me, but : be sure you call your page via your web server. The url in your browser should be :
http://localhost/whatever/page.html
and not (if from your hard drive) :
file://c:/whatever/page.html

Related

Laravel Dynamic Ajax Dependent Dropdown

I Dont know whats wrong with this code but when i choose one of it no option value shown
Here my Blade View
<div style="overflow:hidden; float:left; width:250px;">
<select id="division" class="" name="">
<option value="groups">-- Division --</option>
<option value="Male">Male</option>
<option value="Female">Femmaleale</option>
</select><br>
<select id="participant">
<option value="choosetools">-- Choose Participant --</option>
</select>
</div>
here my script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#division').change(function(){
var division = $('#division').val();
$('#participant').html('');
$.ajax({
url:'getParticipant/{id}',
type:'GET',
data:{myID:division},
dataType: "json",
success:function(data)
{
$.each(data, function(key, participant)
{
// alert(city.city_name)
$('#participant').prop('disabled', false).css('background','aliceblue').append('<option value="'+participant.gymnastid+'">'+'participant.FULLNAME'+'</option>');
});
}
});
});
});
</script>
here my route
Route::get('/getParticipant/', 'App\Http\Controllers\ScoreController#getParticipant');
here my controller
public function getParticipant()
{
$getdiv = $_GET['divSelect'];
if ($getdiv == 'Male') {
$res = Magmodel::all();
return Response::json($res);
}else{
$res = Wagmodel::all();
return Response::json($res);
}
}
Can Someone please help me so all data from model Magmodel or Wagmodel showup based on dropdown choose

POST variables are never set

I have form with 2 inputs, country name and country rating (0-5) and submit button to add country. When button is clicked it executes addCountry function.
I always get an error as message and I don't know why $_POST['country'] and $_POST['ratings'] are not showing.
Function looks like this:
<script>
function addCountry(){
var $country="country";
var $ratings="ratings";
$.ajax({
type:"POST",
url:"../actions/addCountry.php",
data:{ $country: "country", $ratings: "ratings" },
success:function(result){
alert(result);
}
});
}
</script>
Php script should get country name and rating, it looks like this:
<?php
if(isset($_POST['country']) &&
isset($_POST['ratings'])){
$country= $_POST['country'];
$ratings = $_POST['ratings'];
echo $country;
echo "is country. You rated it: ";
echo $ratings;
}
else{
echo "Error";
}
?>
Html looks like this:
<head>
<link rel="stylesheet" href="../styles/styles.css">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript"src= "../actions/mapData.php"></script>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery
3.1.1.min.js"></script>
</head>
<body>
<div id="map" style="width: 90%; height: 20%;"></div>
</body>
<body>
<form autocomplete="off" method="POST">
<div class="autocomplete" style="width:100%;">
<input id="country" type="text" name="country" placeholder="Country">
<label for="ratings"> Rate this country: </label>
<select id="ratings" name="ratings">
<option value="one"> 1 </option>
<option value="two"> 2 </option>
<option value="three"> 3 </option>
<option value="four"> 4 </option>
<option value="five"> 5 </option>
</select>
</div>
<input type="submit" id="add" value="Add Country" onclick="addCountry()"/>
</form>
The problem is with your script.
<script>
function addCountry(){
var $country="country";
var $ratings="ratings";
$.ajax({
type:"POST",
url:"../actions/addCountry.php",
data:{ country: $country, ratings: $ratings },
success:function(result){
alert(result);
}
});
}
</script>
The data passed to the page is in the form name : value and you were giving it wrongly.

Unable to send two strings together using PHP to JavaScript

I'm trying to pass database value javascript / ajax. If if send directly it works well,
The same I'm trying to do from database. And some how it doesn't work.
I'm sending value of the option to script like this,
<select name="users" onchange="showUser(this.value)">
and when I send value directly like this, It show the correct value in script.
<option value="Peter Grif">Peter Griffin</option>
Script Result is = Peter Grif
And if the same I fetch from database, like this.
while($row=$select->fetch_assoc())
{
echo "<option value=".$row['name'].">".$row['name']."</option>";
}
In Dropdown box it is exactly working with full name like "Peter Grif"
But the script result is = "Peter" the second part of name after space never comes.
Full Program:
<html>
<head>
<script>
function showUser(str) {
window.alert(str);
}
</script>
</head>
<body>
<body>
<form>
<center> <select name="users" onchange="showUser(this.value)"> </center>
<option value="Peter Grif">Peter Griffin</option>
<option value="Lois Griff">Lois Griffin</option>
<?php
include("connection.php");
$select=$con->query("select name from users group by name");
while($row=$select->fetch_assoc())
{
echo "<option value=".$row['name'].">".$row['name']."</option>";
}
?>
</select>
</form>
<br>
</body>
</html>
I modified your code in while loop and it works as you want. Its the quotation issue.
<html>
<head>
<script>
function showUser(str) {
window.alert(str);
}
</script>
</head>
<body>
<body>
<form>
<center> <select name="users" onchange="showUser(this.value)"> </center>
<option value="Peter Grif">Peter Griffin</option>
<option value="Lois Griff">Lois Griffin</option>
<?php
include("connection.php");
$select=$con->query("select name from users group by name");
while($row=$select->fetch_assoc())
{
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
?>
</select>
</form>
<br>
</body>
</html>
echo "<option value=".$row['name'].">".$row['name']."</option>";
The option value needs to be quoted. You are ending up with
<option value=Peter Grif>Peter Grif</option>
It needs to be quoted so it ends up like
<option value='Peter Grif'>Peter Grif</option>
So either
echo "<option value='".$row['name']."'>".$row['name']."</option>";
or perhaps
echo "<option value='{$row['name']}'>{$row['name']}</option>";
(you can reference arrays within double quotes by surrounding by curly brackets, I feel it makes it easier to read than concatenation, so you don't get quote confused when echoing HTML especially, but it's just my preference).
Doing view source on page can help with these things to make sure the generated HTML is valid.

JavaScript from ajax modified file doesn't work in main page

I have a problems with a form and ajax behavior when I populate my dynamic div using JavaScript.
I have a drop box which contains different time periods and it triggers JavaScript function which modifies the container div based on provided value.
The problem is that the POST behavior of the form and all JavaScript elements doesn't work in the main file.
Here is the code. I simplified it to emphasize the problem.
this is the drop Box:
//jQuery for datePicker comes here
<select id="QSelector" method="post" onchange="populateDiv(this.value)">
<option value="0">All Values</option>
<option value="1">Sets for 1</option>
<option value="2">Sets for 2</option>
<option value="3">Sets for 3</option>
<option value="4">Sets for 4</option>
</select>
<div id="OUtputDiv" ></div>
here is the javascript function:
function populateDiv(id){
var xmlhttp;
if(window.XMLHttpRequest){//safari, chrome, opera, ffox
xmlhttp=new XMLHttpRequest();
}
else{//IE
xmlhttp=ActiveXObject("Microft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("OUtputDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../scripts/supportFile.php?ID=" + id, true);
xmlhttp.send();
}
And here is the content of the support file. don't mind the id variable it does some logic (ant it works), but I removed it because it's irrelevant to a given problem.
<?php
$Id= $_GET['ID'];
echo "<script> alert('it works'); </script>";
echo "<form name='AddForm' class='AddForm' method='post' >";
echo "<span > Date: </span> <input type='textbox' id='datepicker' name='datepicker' > ";
echo "<input type='submit' name='SubBtn' value='Save' >";
echo "</form>";
if(isset($_POST['SubBtn']))
{
echo $_POST["datepicker"];
}
?>
Nether JavaScript or JQuery does not work from the main file. And form does not post anything if I press the save button.
Can anyone suggest how can I make it responsive in the main file where I call ajax function from?
Avoid using IE5/6 support, use jQuery instead:
The problem is that you put all code in the same page, it will not work in that way, you need to make 2 files, 1 for post 1 for result
Good:
test_post.php
<?php
$Id = $_POST['id'];
if(!empty($Id)){
$result = "
<script> alert('it works'); </script>
<form name='AddForm' class='AddForm' method='post' >
<span > Date: </span> <input type='textbox' id='datepicker' name='datepicker' >
<input type='submit' name='SubBtn' value='Save' >
</form>
";
echo json_encode(array('status' => 'success', 'result' => $result));
}
?>
test.php
<select id="QSelector">
<option value="0">All Values</option>
<option value="1">Sets for 1</option>
<option value="2">Sets for 2</option>
<option value="3">Sets for 3</option>
<option value="4">Sets for 4</option>
</select>
<div id="OUtputDiv" ></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var $ =jQuery.noConflict();
$(document).ready(function(){
$(document).on( "change", '#QSelector',function(e) {
e.preventDefault();
var id = $(this).val();
$.ajax({
type: "POST",
url:"<?php echo './test_post.php'; ?>",
data: {id: id},
dataType: 'json',
success: function(data){
if(data.status == 'success'){
$('#OUtputDiv').html(data.result);
}
}
});
});
});
</script>

Data not getting passed to the ajax function

The form below is present in every row of an html table.However alert("dfd") pops up only for the first row of the table and not for the forms in the other rows(these forms appear on the webpage).Can anyone tell why is it happening?
HTML:
<form class='form form-horizontal' method='post' role='form' id='formsel' name='formsel'>
<fieldset >
<div>
<span class='control-group' >
<span class='controls'>
<select id='formcont' name='formcont' class='form-control' style='cursor:pointer;'>
<option selected='selected' style='display:none;'>Select</option>
<option value='1'>Option1</option>
<option value='2'>Option2</option>
<option value='3'>Option3</option>
</select> <button id='selbtn' name='selbtn' type='submit'>Sub,it</button>
</span>
</span></div>
</fieldset>
</form>
JS:
$("#formsel").submit(function () {
alert("dfd");
$.ajax({
url:"add.php",
data:$("#formcont").val().serialize(),
type:"POST",
success:function(data){
console.log(data);
if(data=="done"){
alert("success");
}
},
error:function(data){
alert("Network ERROR");
}
})
return false;
});
$("#selbtn").click(function () {
("#formsel").submit();
});
PHP:
<?php
include ('db.php');
session_start();
echo "done";
?>
Yes, because you're not sending any data:
$("#formcont").val().serialize()
Should be:
$(this).serialize()
Since the button you're clicking to trigger the submit is a submit button, you really do not need the following code:
$("#selbtn").click(function () {
("#formsel").submit();
});

Categories

Resources