Dispay content based on dropdown choice - javascript

Hi I'm making a web app using mvc .net(c#) with a registration page. There are two types of users, lets call them type 1 and type 2. I'm my form I have a drowpdown list where they can choose their type. If the option for type 2 is selected I would like to display an input for a pdf file. I don't have much experience with javascript or ajax so I was wondering if I can use one of them for this purpose. Thanks in advance.

Your HTML looks like:
<select name="user_type" id="user_type">
<option value="">Select User Type</option>
<option value="type_1">Type 1</option>
<option value="type_2">Type 2</option>
</select>
<!-- Where to show your result? -->
<div id="result"></div>
<!-- Load your jQuery script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Your JavaScript
// Provided that you have load your jQuery
$("#user_type").change(function()
{
$.ajax({
url:"page.asp", // The ASP page to fetch your user result
type:"POST",
data: {"user_type":$(this).val()},
success: function(response)
{
//Success, display the result
$("#result").html(response);
},
error: function(response)
{
//In case error occurs, handle your errors
alert("Error occurs!"+response);
}
});
});
Then in your ASP file:
Just retrieve the post DATA with the name user_type, then after your queries, print the result, this will be captured to the response parameter in the success() method of the ajax if the query is successful or in the error() method if the query is not successful.
Hope this helps!

Related

How to pass input text value to another page using javascript

I am building a management system in which the admin can select an item from the database table and update the details. To achieve this I have two forms on two pages. The first form is to select the item from table and pass it's ID to the second page where I will use the ID to fetch the details from the table using php. I want to do this with javascript so it will not refresh the page. My question is how to pass this value? I am using the following code, but it is not working.
HTML
<div id="result"></div>
<form action="update_item.php" id="update" method="post" >
<select name="selected" class="form-control" id="myItem" required>
<option>Select item</option>
<?php
<!-- PHP script to select the item -->
?>
</select>
<button id="submit">Select</button>
</form>
JAVASCRIPT
$(document).ready(function() {
$("#submit").click(function() {
var chat = $('#myItem').val();
if(chat=='')
{
alert("Please select an item!");
}
else{
$.ajax({
type: "POST",
url:"update_item.php",
data:{
data:chat,
},
success: function (msg) {
//alert(msg):
$('#result').html(msg);
},
error: function(){
alert('error');
}
});
}
});
});
PHP
Second page
$item_id = $_POST['data'];
$get_item = "select * from items where item_id='$item_id'";
<--PHP script continues-->
You can add a hidden field and send this input back to your server:
<input type="hidden" name="something" value="<?= $_SERVER['id'] ?>" />
And then access it with via:
$_SERVER['id']
If you are not changing the page between forms you should be able to just create a variable on the client side that stores the necessary data. Since the second form is loading into the same environment, any variables you have from the first form will still exist.
From your example, I'm guessing chat is the data you're trying to use in the second form. Right now it is local to the click function (once that function completes the variable disappears). You could either move the declaration of that variable into the global scope (outside of document.ready), or use it as intended inside the success callback. (From your example it is unclear what you are trying to do with this data)

Laravel Routes with AJAX file

I'm new to Laravel and I'm trying to learn how to create a dynamic drop down box where the 2nd drop down box will change depending on what is selected in the 1st one.
Here is my form code inside my blade file:
{!! Form::open(array('url'=>'', 'files'=>true)) !!}
<label>Select a Cinema:</label><br>
<select id = "cinema" name = "cinema">
#foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
#endforeach
</select>
<br>
<label>Select a session:</label>
<br>
<select id = "sesh" name = "sesh">
<option value=""></option>
</select>
<br>
<label>Number of tickets:</label><br>
<select id = "count" name ="count">
#for ($i = 1; $i < 10; $i++)
<option value="{{$i}}">{{$i}}</option>
#endfor
</select>
<br><br>
<input type="submit" value="Submit">
{!!Form::close()!!}
Here is my AJAX code (also inside the blade file but in <script> tags:
<script>
$('#cinema').on('change', function(e){
console.log(e)
window.alert("On Change");
var cinema_id = e.target.value;
//ajax
$.get('/ajax-subcat?cinema_id=' + cinema_id, function(data){
//success data
console.log(data);
window.alert("On Success");
$('#sesh').empty();
$.each(data, function(index, subcatObj){
$('#sesh').append('<option value=""' + subcatObj.id +'">'+subcatObj.name+'</option>');
});
});
});
</script>
And finally here is my route:
Route::get('/ajax-subcat', function(){
$cinema_id = Input::get('cinema_id');
$sessions = Session::where('cinema_id', '=', $cinema_id)->get();
return Response::json($sessions);
});
So this code is not generating any data and is instead giving me a 404 error.
I have verified that the AJAX code does go inside the "change" function, through alerts, however it is not showing the 2nd alert. In my limited understanding, I feel like there may be an issue in my routes file? As if the route file is returning data, the next function in AJAX should be running.
One thing I don't understand in the routes code is what Input::get('cinema_id') is doing. I think it's grabbing what the user input in the drop down box?
Since it's giving 404 error, I hope using full url will solve this. Use
//ajax
$.get('{{ url('/ajax-subcat') }}?cinema_id=' + cinema_id, function(data){
//success data
Add header in your ajax call
headers : {
'csrftoken' : '{{ csrf_token() }}'
}
Seems like theres a few things going on here. It's important to separate what is happening on the on the server with Laravel, and in the client with your Javascript.
SERVER
Sends the form with data in it. Any blade syntax you use like this.
#foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
#endforeach
Is rendered on the server before it is sent to the client. That is how the first drop down is being populated with data when you load the page.
CLIENT
Looks like your using AJAX to make request based on users selection from the first drop down. This line:
$.get('/ajax-subcat?cinema_id=' + cinema_id, ...
Is going build request to your Route::get('/ajax-subcat', ... along with a query string. ?cinema_id=1. Input::get('cinema_id'); should take the value of the query string (1).
It looks like you've set up the the route correctly so I'm thinking its a problem with var cinema_id = e.target.value;. I'd check it's value before the request is made and make sure it lines up with the value that your query on the server is going to need.
The value of var cinema_id on the client, is going to be the value of $cinema_id on the server for your query.
Hope this helps,
Matt
Change
uploadUrl: '{{route("product/create")}}',
to
uploadUrl: '{{url("product/create")}}',
and add this in ajax
headers: {
'X-CSRF-Token':{{ csrf_token() }},
},

Passing a blank value using javascript of jquery

Is there a way to pass a "blank" value to a hidden input type? And when I say blank, I mean an actual whitespace character or something?
For example, I have this select:
<select name="Sample">
<option value="BB515_Hu_CD3" >BB515, Human CD3</option>
</select>
On one form, it's a drop down where a user selects the option. Upon submission, the value of the option gets written to the "Sample" database field.
On another web form that writes to the same database and doesn't have Sample select, I would like to pass a blank value so that the current value in the database field is deleted and empty.
<input type="hidden" value="" name="Sample" />
I can add a dash '-' in the value and then it will overwrite the BB515_Hu_CD3 value with a dash, but I would rather have a blank field then a dash in it. Keeping value="" will just keep the original data which I don't want.
Each form has contact matching enabled on it via email address. So if I use the same email for both forms, the original form submission data will be updated with the second form submission data.
Any ideas on how I can accomplish this?
Thanks in advance.
That hidden field should be in the post array as an empty variable.
On the server side you can just insert into the database whatever value is given for Sample.
For example if you have this:
<select name="Sample">
<option value="" >Choose Sample</option>
<option value="BB515_Hu_CD3" >BB515, Human CD3</option>
</select>
or this
<input type="hidden" value="" name="Sample" />
Then server side:
$data['Sample'] = $_POST['Sample'];//if it is empty it will update the database with an empty string if not then it will update with the value
You can also use a value like - if so, then do this:
if(!empty($_POST['Sample']) && $_POST['Sample'] == '-')
{
$data['Sample'] = "";
}
For the javascript/jquery portion:
// this is the id of the form
$("#idForm").submit(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements automatically
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
alert(data); is where you would handle the response from the server
If it does not work like this in your current code we may need to see the code. Validation libraries or javascript may do some strange things.

how to receive selected option on the same php page

I need to display the content(per page) based on the option(per page) selected by the user
for which i need the selected option value in the same php page to display the content
but i cannot receive the value in php code ,Kindly give some solution to this problem
I've tried
Pass Javascript variable to PHP via ajax
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get2
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_option_value
HTML Code for selecting option :
<select id="page_count" >
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
JavaScript when option changed :
var total_items;
$(document).ready(function(){
$("#page_count").change(function(){
var x = document.getElementById("page_count").selectedIndex;
total_items=document.getElementsByTagName("option")[x].value;
alert(total_items);
AJAX for posting the selected option :
$.ajax({
type : "POST",
url : "start_landing_page.php",
data : {total_items: total_items},
success : function(data){
alert("sucess!");
}
});
received via AJAX in php :
<?php
if(isset($_POST['total_items'])){
$uid = $_POST['total_items'];
var_dump($uid);
}
>
The POST request should send data like this:
data : 'total_items='+encodeURIComponent(total_items),
I feel you can use many options to get and pass the value, following is the simplest way you can access the selected value and pass it in your ajax function:
$("#page_count").change(function(e){
total_items = $(this).val();
....
...
});
Full Example: Jquery Receive selected option and Passing it in Ajax by using $.param()

How can i refresh form after submit?

i have form like
<form id="abc">
<div>
<select >
<option id= "1"> ha1 </option>
<option id= "1"> ha2 </option>
<option id= "1"> ha3 </option>
<option id= "1"> ha4 </option>
</select>
<input type="submit">
</div>
</form>
for form submit i have used like
$(document).ready(function() {
$('#abc').submit(function(){
$.post('filter.php', $(this).serialize(), function(data){
$('#abc').reset(); //(this).reset();
});
return false;
});
});
Here reset is not working. Any problem with reset i am not getting.
After form submit, i want to refresh form with db values (to display values selected just now).
how can i refresh page after submit or either div refresh.
$(document).ready(function() {
$('#abc').submit(function(){
$.post('filter.php', $(this).serialize(), function(data){
window.location.href=window.location.href;
});
return false;
});
});
reloads the page by setting the href to the actual one :)
or you can also use this:
parent.document.getElementById("abc").reload();
by the way: i dont see your serverside code, you have to render the selected values, of course, i am assuming that you are returning them, my answer doesnot cover the serverside scene. my code is only for the case that you are returning the selected values from server after saving them into db.
Reset form fields using Pure JavaScript.
document.getElementById("formid").reset();
If you own server side code, you can return the values in the response and then fill the fields with these values in the callback.
Let's say this is your response JSON:
{
data: [{
"username": "john doe"
}]
}
$('#abc').submit(function(){
$.post('filter.php', $(this).serialize(), function(data){
$('#abc').reset(); //(this).reset();
$('input#username').val(data.username);
});
return false;
});
As said in the answer by doniyor, you can use window.location.href to refresh the page, but this will not populate your form with the values you just wrote to your database.
you have two options available for populating your form with the database, implementing both might be desirable in your case (up to you).
The first is to populate the form when you first load your html. This can be done server side by making a query to your database and getting the values, and then setting the correct radio button based on the value like so:
<input type="radio" selected="selected" />
The other option is to set the checkboxes async with jquerys .prop() method. This requires that your tags have unique ID's (which they should have anyways). Example:
$("#yourIDHere").prop('checked',true);
In the latter case, you could have the script you post to output the correct ID to use. This is up to your discretion, and is dependant on your case, but hopefully this answer points you in the right direction.
Best regards
Try to use this,
$('#abc').submit(function(){
$.post('filter.php', $(this).serialize(), function(data){
$('#abc').find('input:text, input:password, input:file, select, textarea').val('');
$('#abc').find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
});
return false;
});

Categories

Resources