update session and refresh page with ajax/jquery - javascript

I need help with a script that according to 2 parameters updated me a $ _SESSION variable and then refresh the page. One of these parameters comes from a select and the other according to a select class "active".
Here's my code:
<div class="simple-drop-down">
<select id="select-order">
<option>Price</option>
<option>Category</option>
<option>A - Z</option>
</select>
And my jquery function like this:
function order_visual() {
var type_order = $('#loader-wrapper').val();
var arrow_order = $( "#select-arrow" ).hasClass( "active" );
$.ajax({
url: "visual.php?order="+type_order="&"+arrow_order,
type: "post",
data: {},
success: function(data){
location.reload();
}
});
});
And then the PHP is a simple script that manages the $_SESSION.

Related

Add HTML code triggered by selection changed

I have a simple select into my HTML code (a dropdown menu).
HTML
<select name="razza" onchange="razzaChanged()">
<?php while ($row = gdrcd_query($result, 'fetch')){ ?>
<option value="<?php echo $row['id_razza']; ?>" <?php if(gdrcd_filter('get',$_POST['razza'])==$row['id_razza']){ echo 'SELECTED'; } ?>>
<?php echo gdrcd_filter('out',$row['nome_razza']); ?>
</option>
<?php } ?>
JavaScript
<script>
function razzaChanged()
{
alert("I am an alert box!");
}
</script>
When the selection of the dropdown is chosen, I have to add some information below the dropdown. The information I have to add is a bit complex and pretty formatted (I need to do some query to retrieve data and then add text and another dropdown after the info).
How can I achieve this? I can register via JavaScript that the selection changed but then I don't know how to go further.
You could use ajax methods. Get value from select using oninput/onchange, use that value as data in ajax request. If request is successful then show server's response in a container where ever you want.
HTML
<select name="razza" id="razza">
<option value="1">Some Option</option>
<option value="2">Another Option</option>
<!-- Use your loop here and remove these options -->
</select>
Javascript
$("#razza").on('input change',function(){
var value = $(this).val();
// Ajax Request
$.ajax({
type: 'post', // you can also use 'get'
url: '/link/to/your/server/file',
data: {
key: value // use key required by backend
},
success: function(response) {
$('#your-container-div-id').html(response);
}
});
});
Please note that I have used code without 'onchange' attribute, as this is better. Feel free to ask...
There are few ways to achieve this. One would be to use what jquery library offers.
Here are just some very rough steps of how one could do it:
In your razzaChanged() function establish which value is selected:
function razzaChanged()
{
var val = $('select[name="razza"] option:selected').val();
// step 2 here
}
Now use this value to fetch data from the server with the help of AJAX:
$.ajax({
type: "GET",
url: '/your-url-to-call',
data: 'your_value=' + val,
success: function(data) {
// step 3 here
}
});
Now having data from server (i.e. json format) build your new select dropdown, i.e.:
var newSelect = $('<select>').appendTo('body');
$(data).each(function() {
newSelect.append($("<option>").attr('value', this.some_property).text(this.some_text));
});
It's definitely not a ready-to-use code as you would have to make sure you return properly formatted data on server side or change the code accordingly. Also
make sure jquery library is loaded and the code is wrapped with its ready function (easy to find example on internet).
Hope this helps.
You will need to do an AJAX POST or GET request to retrieve data from your database and you will need to use document.createElement("elementtype"); to create an element to add to your page.
With jQuery, your AJAX would look something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",//can be GET or POST
url: "yoururl",
statusCode: {
404: function() {
alert( "page not found" );
},
data: {key: value},//you can have multiple keys and values
success: function(res){
//add elements to the page
$('#yourelememntid').html(res.someattribute);
}
}).done(function() {
//AJAX request finished
});
</script>

Ajax request doesn't auto trigger on form change

<form>
<select name="select-1">
<option value="option-1">Option 1</value>
<option value="option-2">Option 2</value>
</select>
<button type="submit">Submit</button>
</form>
I have a form that when the button is clicked, it populates a div with html content from an Ajax request without any page reload ( its done in the backend, cant say much more because its not my area of expertise ). When the submit button is clicked, it works as expected, but the behaviour I want is for the Ajax request to auto-trigger when the form has an option selected, without the need to press the button.
$(document).on(
"change",
"select[name=select-1]",
function(e) {
if ($(this).val()) {
$(document)
.find("form")
.submit();
}
}
);
The problem here is that the form submits and reloads the page, not triggering the Ajax request. I have also tried to trigger a click event on the button itself:
$(document).on(
"change",
"select[name=select-1]",
function(e) {
if ($(this).val()) {
$(document)
.find("button")
.click();
}
}
);
.. but nothing happens.
// try something like this, as suggested by #Anjana. try to submit form data
// using ajax.
$(document).on(
"change",
"select[name=select-1]",
function(e) {
if ($(this).val()) {
var formData = new FormData();
formData.append("select-1", $(this).val());
$.ajax({
url: {your url},
method: "post",
data: formData,
success: function(data) {
div.innerHTML = data;
}
});
}
}
);
In my opinion, if you are using AJAX, you should trouble with form. You only need something to trigger the call. That can simply be a button.
<select id="menu" name="select-1">
<option value="option-1">Option 1</option>
<option value="option-2">Option 2</option>
</select>
<button type="submit">Submit</button>
Select the value that the user has selected in the select menu with:
const selection = $( "#menu option:selected" ).text();
Then use the $.ajax() function provided by jQuery:
$(document).ready(function() {
$('#submit').click(function() {
$.ajax({
type: "POST",
url: "<CHANGE HERE>",
data: { selection: selection },
dataType: "json"
});
});
});
You have used button type ="submit", which makes the page reload. So remove type submit from your button and use ajax or use e.prevent default() like
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
url: url, //type your url,
method: "post",
data: data,
success: function(data) {
},
error: function(data){
}
});
After that on change when you submit the form on change event as you are doing, it will trigger the Ajax request and work as you expect.
Learn More about Ajax here
First of all, the jQuery code you are using is not AJAX, you can learn more about jQuery and AJAX from their documentation here:
http://api.jquery.com/jquery.ajax/
Here is the solution to your problem:
<!--HTML CODE-->
<form>
<select name="select-1">
<option value="option-1">Option 1</value>
<option value="option-2">Option 2</value>
</select>
<button type="submit">Submit</button>
</form>
Here's the jQuery code that actually uses AJAX.
A selector is used to get the <select></select> and then we set an event listener to listen when the object is changed.
UPDATE: This now allow you to attach event listener to dynamically created elements
$(document).ready(function() {
$(body).on('change', "select[name=select-1]", function() {
$.ajax({
url: "https://example.com",
method: 'GET',
data: {"id": 123, "value": $('select[name=select-1]').val()}
})
.done(function (){
alert("success");
})
.fail(function (){
alert("error" + $('select[name=select-1]').val());
});
})
});
You can change the url in the AJAX, as well as method with GET or POST, and the data to be sent to the URL.
After that, if the AJAX request is successful, the code in the .done() section will be executed.
Similarly, if the request fails, the code in fail() will be executed.

JQuery - Change $_GET variable on button click

I'm trying to create a series of buttons that update my website's $_GET['year'] variable. I want the buttons to work on these pages:
example.com
example.com/?search=foo
example.com/?search=foo&year=2015.
So for example if I clicked on <a>2016</a> my 'year' tag would be updated to year=2016 and the webpage would show search results or everything from that year. I've tried using a JQuery AJAX like so:
<ul class="dropdown-menu dateDropdown">
<li><a>2016</a></li>
<li><a>2015</a></li>
<li><a>2014</a></li>
</ul>
<script>
$(document).ready(function () {
$(".dateDropdown>li>a").each(function() {
$(this).click(function() {
alert("pressed");
$.get({
url: "index.php",
data: $(this).html(),
callback: alert("sent")
});
;})
;})
;}
</script>
Currently I'm getting the "pressed" and "sent" alert, but the webpage is not updating. I figured I could probably get it to work using window.location and regex to change or add 'year' to the URI, but this way would be much neater.
Any ideas?
Take a look at jQuery.get params.
In your situation, it would be something like:
$(".dateDropdown>li>a").each(function(index,elem){
$(elem).click(function(){
alert('Pressed');
$.get('url', {search:'foo', year: $(this).text() }).done( function(){ alert('Done!')} )
})
})
Change the script to
<script>
$(document).ready(function () {
$(".dateDropdown>li>a").each(function() {
$(this).click(function() {
alert("pressed");
$year=$(this).html();
$.ajax({
method: 'post',
url: "query.php",
data: 'year='+$year,
callback: alert("sent")
success: function(e){
$('html').html(e);
}
});
;})
;})
;}
</script>
copy the contents of index.php to query.php
and make the content of index.php
<html>
<?php include 'query.php'; ?>
</html>

Ajax / Jquery refresh page after variables are passed

Okay so am using Ajax to send a JS variable from index.php to page2.php . Once it is set to page2.php, the database is edited while the user has been on index.php the entire time. However, I need the index.php to reload or refresh once page2.php has finished updating the database in the background. To give you a better clue, I will include some of my code.
On Index.PHP is :
<a href='#' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
and
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
});
}
So basically when they click the button that says "Update" it sends the ID of the button the page2.php and page2.php from there updates the changes the database using that info. However, the URL the user is on is:
http://website.com/index.php#
and the database has not updated for them and they have to see the annoying hash symbol in the URL. I have googled how to refresh the page in JS, and found things that either do not work or do work , but result in the variables not being sent to the PHP file. I just need it so that after it is sent to the php file, and preferably after the php file is finished, the index.php page refreshes and without the # at the end.
e.preventDefault() is the answer but if I may suggest:
Get rid of that inline function and add the event handler with jQuery.
$(function () {
$('.dbchange').click (function (e) {
e.preventDefault();
var id = this.id;
$.ajax({
type: "POST",
url: 'page2.php',
data: {NewID: id},
success: function(data) {
window.location.reload();
}
});
});
});
Remove # then replace with javascript:void(0):
<a href='javascript:void(0)' class='dbchange' onclick='dbchange(this)' id='".$ID'>Update</a>
JS:
function dbchange(obj) {
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: 'page2.php',
data: "NewID=" + id,
success: function() {
window.location.reload();
}
});
}

Update div content using PHP and Javascript variables

I'm new to Ajax and need some help with this.
The idea is simple, I have a list of directories within the div 'list' and when I click on one of the directories, the div 'content' must list the content of this directory with a php function.
This is my html code:
<div id="list">
<ul>
<li id="directory_1" class="test">directory_1</li>
<li id="directory_2" class="test">directory_2</li>
<li id="directory_3" class="test">directory_3</li>
<li id="directory_4" class="test">directory_4</li>
</ul>
</div>
<div id="content">
<!-- Here you can see the folder content-->
</div>
This my jQuery + Ajax:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
It works, I arrive to list.php. And on PHP I have a function that lists directory content.
So how can I refresh 'content div' with the php function?
So if I click on directory_1 it will show /var/www/pg/directory_1 folders, and then if I click on directory_2 it will clear the 'content' div and will then list out the directory_2 folders.
Here is a jsfidde without the PHP code:
http://jsfiddle.net/e5v1dgpc/
Sorry for my English, if someone has a question I will try to clarify.
You could do something like this:
jQuery('#content').html('');
Which will just set everything inside the html to be blank.
Or I think you could use .empty() - http://api.jquery.com/empty/
If you called it at the start of your function then it should clear the div before repopulating it.
$(".test").click(function(){
var name = $(this).attr("id");
$( "#content" ).empty();
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
In order to set the target of your ajax you could do something like this with a success condition. You'd need to change it to display whatever content you want.
$.ajax({
url: 'list.php',
type: 'POST',
success: function(html) {
var divSuccess = $('#content', $(html)).addClass('updated');
$('#content').html(divSuccess);
}
});
This link might also be useful to you - jquery ajax load certain div
Instead of Emptying the 'content' div initially, you can empty it
OnSuccess of the Ajax post, as below:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
success: function(){
$( "#content" ).empty();
}
});
});
Hope this is what you are looking for..

Categories

Resources