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()
Related
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!
I am creating a page that needs to send post data using Ajax (JQuery).
The (most relevant) HTML code is the following:
<div class="command-list">
<form action="app_page.php" method="post">
<select name="TYPE" class="form-control">
<option vaule="VALUE 1">DISPLAYED TEXT 1</option>
<option vaule="VALUE 2">DISPLAYED TEXT 2</option>
</select>
<input type="button" class="ibtnSave" value="Salvar">
</form>
</div>
The JQuery function that is being used to send the form data is:
$(document).ready(function () {
$(".command-list").on("click", ".ibtnSave", function (event) {
var tosave = $(this).closest("form"); // Gets the form that the button belongs to
var r = $.post('app_page.php', tosave.serialize()); // Sends the form data via POST to my application page
});
On the server-side (PHP application), when the POST data is retreived, the values received are either 'DISPLAYED TEXT 1' or 'DISPLAYED TEXT 2' instead of 'VALUE 1' or 'VALUE 2' as expected in a normal form sent via html.
How can I send only the data inside value attribute instead of the text displayed between the option tags?
Summarizing:
Current data being sent: TYPE=DISPLAYED TEXT 1
What I really want to send: TYPE=VALUE 1
EDIT
Status: Problem Solved
I've misspelled 'value' attribute on my HTML code.
On the code above, it says 'vaule' instead of 'value'.
Thanks.
Typo:
<option vaule="VALUE 1">DISPLAYED TEXT 1</option>
^^^ should be value
If an option has no value (in your case due to the typo), the displayed text is used instead.
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() }},
},
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;
});
I'm using Jquery to allow users to upload an image via Ajax in a form (the image uploads before the form is actually submitted). I've added the ability to add a watermark to each image that is uploaded (this is done in upload_image.php) this part works fine.
The user can select where they want the watermark to be placed on their image via a form select. I'm using Jquery's .val() to grab the value of the id="watermark" select and add it as a query string value to be passed to upload_image.php.
The problem is that it always passes the first select value no matter what I actually select in the form. I tried putting it in a function (thought it was grabbing the value on page load) no luck there. I changed the select to radio buttons. It still grabs the value of the first radio button on the page; no matter what you select.
Here is the portion of the script that handles this:
<script type="text/javascript" >
$(function(){
// build URL to php upload script with watermark placement
function setWatermark() {
var uploadUrl = 'http://www.mysite.com/upload_image.php?w=';
var watermarkValue = $('#watermark').val();
var watermarkUrl = uploadUrl + watermarkValue;
return watermarkUrl;
}
var btnUpload=$('#upload');
new AjaxUpload(btnUpload, {
action: setWatermark(),
name: 'uploadfile',
});
});
</script>
This is the form (with irrelevant fields removed):
<form id="image_form" action="this_form.php" method="post" enctype="multipart/form-data">
<select id="watermark">
<option value="top_left">Top Left</option>
<option value="top_right">Top Right</option>
<option value="center">Center</option>
<option value="bottom_left">Bottom Left</option>
<option value="bottom_right">Bottom Right</option>
</select>
<div id="upload" ><span><img src="upload_button.jpg" /></span></div>
</form>
To execute this code:
new AjaxUpload(btnUpload, {
action: setWatermark(),
name: 'uploadfile',
});
The browser must first construct the arguments to pass to the constructor. To construct the second argument, the object, it must call setWatermark to get the value for the action property. This is where your problem is; setWatermark is being called when the AjaxUpload object is created.
I don't know what AjaxUpload is, but you'll have to find a way to get it to call a function when it needs the action rather than it being provided as a constant in the options.