On form change send to url with jQuery - javascript

I want to add an action to the form on change so that when you select an option in the form you go to the url I have set in my JS with that parameter selected in the option.
In the below code I have two alerts, these both get the desired url. And they even take me to a page where the url seems to be ok, but the content doesn't seem to load.
If my url is: http://www.example.com/index.php?a=108&tg=2 in the browser, after I select the form it functions as if I only have http://www.example.com/index.php.
See fiddle
<div id="myID">108</div>
<form class="aclass" target="_blank" method="post">
<select>
<option value="1">aaa</option>
<option value="2">bbb</option>
</select>
</form>
<script>
var pageurl = window.location.protocol + "//" + window.location.host + window.location.pathname;
var myID = jQuery('#myID').html() || '';
var myURL = '?a=' + myID + '&tg=';
jQuery('.aclass select').change(function () {
var opVal = jQuery(this).val() || 0;
var finalURL = pageurl + myURL + opVal;
alert(finalURL);
jQuery(this).closest(".aclass").attr("action", finalURL);
alert(jQuery(this).closest(".aclass").attr('action'));
this.form.submit();
});
</script>
What am I doing wrong here how can I actually get to have http://www.example.com/index.php?a=108&tg=2 from my form?

If you need to submit the form using POST, then the actual querystring as they're processed as GET variables. You can create hidden input fields and add them to the form prior to submission to receive those variables as POST variables.

var pageurl = <?php echo $_SERVER['PHP_SELF']; ?>;
var myID = jQuery('#myID').html() || '';
var myURL = '?a=' + myID + '&tg=';
jQuery('.aclass select').change(function () {
var opVal = jQuery(this).val() || 0;
alert(opVal);
var finalURL = pageurl + myURL + opVal;
alert(finalURL);
jQuery(this).closest(".aclass").attr("action", finalURL);
alert(jQuery(this).closest(".aclass").attr('action'));
this.form.submit();
});
Please try this

Related

How to get a post ID php using js

here I want to display the data id based on the click button using js
my code:
var idPost = document.getElementsByClassName("getID")[0];
idPost.onclick = function() {
var GetID = window.location.protocol + "//"
+ window.location.host
+ window.location.pathname
+ '?id=<?php echo $id;?>';
window.history.pushState({ path: GetID }, '', GetID );
}
why my code isn't working?
maybe someone here can help my problem
This may will help you:
EDIT
location.href reloads page to indicated url
var idPost = document.getElementsByClassName("getID")[0];
idPost.onclick = function() {
let id = "<?php echo $id; ?>";
location.href = `?id=${id}`;
}

Javascript window.location redirect with url rewriting, no querystring

I have endlessly googled for about an hour, so please forgive me if this has been asked before.
I am using pure Javascript and do not wish to use jQuery.
PREAMBLE
I have an HTML form with 3 select boxes that control a search of items. When one is updated, a simple function reads each of the values in the select boxes and produces a URL that matches our URL rewriting standard.
http://www.example.com/search/select1/data1/select2/data2/select3/data3/
This is then used in a
history.pushState
to update the browser's url address so a user can bookmark the page right away. This works fine.
PROBLEM
When the user presses the button of the form, what I want is the function to read all the select box values, generate the URL as before but also load this specific URL so that the underlying database code can return the results for that search on the page.
However, when I use
window.location.href
it loads the page, but also sends the querystring from the form submission. This mucks up the database code because, essentially, it's getting all the data twice.
EXAMPLE
I choose 'A' from select1, 'D' from select2 and 'E' from select3.
This results:
http://www.example.com/search/select1/A/select2/D/select3/E/?select1=A&select2=D&select3=E
SO...
Is it possible to generate the URL in the correct rewritten format, then load the page without the querystring?
JAVASCRIPT
function changepage(loadpage)
{
var theform
theform = document.getElementById("searchform");
var pageurl
pageurl = 'http://www.example.com/search/'
var select1 = theform.select1.value;
var select2 = theform.select2.value;
var select3 = theform.select3.value;
if(select1 != '')
{
pageurl = pageurl + 'select1/' + select1 + '/';
}
if(select2 != '')
{
pageurl = pageurl + 'select2/' + select2 + '/';
}
if(select3 != '')
{
pageurl = pageurl + 'select3/' + select3 + '/';
}
history.pushState('data', '', pageurl);
if(loadpage=='yes')
{
window.location.href = pageurl;
}
}
HTML
<form method="post" action="form.asp">
<select id="select1"><option>A</option><option>B</option></select>
<select id="select2"><option>C</option><option>D</option></select>
<select id="select3"><option>E</option><option>F</option></select>
<button onClick="changepage('yes');">
</form>

Doesn't keep previously selected value in select box when page is reloaded

I have a drop-down within my webpage (code below):
<select id="SelectedNumber" >
<option label="choose one"></option>
<option value ="1.aspx">1</option>
<option value ="2.aspx">2</option>
<option value ="3.aspx">3</option>
<option value ="4.aspx">4</option>
</select>
This calls this function when the value is changed and reloads a new URL (code below:)
$(function(){
// bind change event to select
$('#SelectNumber').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = window.location.protocol + "//" + window.location.host + "/" + url; // redirect
}
return false;
});
});
Now my problem is when the page is reloaded I want it to remember the option which was selected, not the option which is first in the dropdown. Any suggestions would be great.
Thanks
Try this:
// load last selected URL from local storage
var selectedURL = localStorage.selectedURL;
// add a "selected" attribute to the element if there is a saved state
if(selectedURL)
$("#SelectedNumber option[value='" + selectedURL + "']").attr("selected", "selected");
// bind change event to select
$('#SelectedNumber').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
// save selected url to local storage
localStorage.selectedURL = url;
window.location = window.location.protocol + "//" + window.location.host + "/" + url; // redirect
}
return false;
});
try jquery cookie plugin like this:
$( document ).ready(init) ;
function init() {
// restore value if present
var cookieValue = $.cookie("comboValue");
if (cookieValue) {
$('#SelectedNumber').val(cookieValue);
}
// bind change event to select
$('#SelectedNumber').bind('change', function () {
var index = $(this).val(); // get selected value
// Store the combo index value into a cookie
$.cookie("comboValue", index);
if (url) {
// window.location = window.location.protocol + "//" + window.location.host + "/" + url; // redirect
// forcing reload in order to simulate navigation to another page.
location.reload();
}
return false;
});
}
Also noticed some 'id' mismatches like SelectNumber and SelectNumber, you have to correct in your code.

Know which Form is submitted

I have eight Forms in a page (Form0, Form1, Form2 and so on). When a form is submitted, data is handed by JS and send to ReassignPreg.php, which search data in DB and send it back with json. Then the proper divs on the page are updated.
The code below is doing its job. But I have eigh copies of almost the same code, one for each Form (I only copy two of them for brevity). Newbie and amateur as I am, I wander which would be the way for synthesize this code (get Form name, and then pass that to only one function).
<script type="text/javascript">
$(document).ready(function(){
$("#Form0").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});
});
$(document).ready(function(){
$("#Form1").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox10").html(imagen)
$("#PregBox11").html(obj.Clase)
$("#PregBox12").html(obj.Dificultad)
$("#PregBox13").html(obj.Tipo)
});
return false;
});
});
</script>
A little more modularity helps a lot
$(document).ready(function () {
$("[id^=Form]").on('submit', function (e) {
e.preventDefault();
var _form = this.id.slice(-1); // 0, 1, etc
var cadena = $(this).serialize() + '&form=' + _form;
$.get('ReassignPreg.php?cadena=' + cadena, function (row) {
var image = $('<img />', {
src : "../ImageFolder/" + row.File + ".png",
width : 530
});
$("#PregBox"+_form+"0").html(image);
$("#PregBox"+_form+"1").html(row.Clase);
$("#PregBox"+_form+"2").html(row.Dificultad);
$("#PregBox"+_form+"3").html(row.Tipo);
}, 'json');
});
});
now you'll have a form key on the server containing the number of the form, for instance in PHP you'd get that with $_GET['form'] etc.
you could add an hidden field to each form with an ID/name and use that to identify the form submitting
You may need to assing classes to your PregBox elements and then target them accordingly to the form's ID.
$('form').submit(function(){ // listen to all form submissions.
var formID = $(this).prop('id'); // get the form ID here and do what you like with it.
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});

jQuery $.get() is not executed on form submission

When a form is submitted, I want to asynchronously invoke an email-sending script order.php with some $_GET parameters.
The jQuery $.get() function doesn't execute and there are no errors displayed in console.
HTML markup:
<form name="submit" id="orderconfirm" action="somefile.php">
<input type="hidden" name="orderkey" id="orderkey" value="somekey"/>
<input type="text" name="email" id="orderemail"/>
<input type="submit" value="submit"/>
</form>
jQuery script:
$(document).ready(function() {
$('#orderconfirm').submit(function() {
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
});
It's really strange because a similar script (also $.get() with a simple URL) works just fine. I'm also sure that the order.php script works fine and the path is correct. The problem is that somehow $.get(url) is not executed and no request is sent.
The submit handler works fine too - for example an alert worked.
Any ideas?
Prevent default browser action by using preventDefault()
$(document).ready(function() {
$('#orderconfirm').submit(function(event) {
event.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
});
Documentation
Also you can use return false; to restrict the form submission
$(document).ready(function() {
$('#orderconfirm').submit(function(event) {
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
return false;
});
});
To submit the form after $.get try this,
$(document).ready(function() {
$('#orderconfirm').submit(function(event) {
event.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url,function(){$('#orderconfirm').submit()});
});
});
Documentation
Because you don't prevent default browser behavior. Add event.preventDefault method:
$('#orderconfirm').submit(function(event) {
event.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
try this
$('#orderconfirm').submit(function(e) {
e.preventDefault();
})
and use valid $.get
$.get( "order.php", {'key':key,'mail': email});
$(document).ready(function() {
$('#orderconfirm').submit(function(e) {
e.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
});
the problem happens with the default behavour from browser on form submission. you need to prevent the default from being executed.
optionally you can even change the type of button from 'submit' and try.
Use return false or e.preventDefault() like,
$('#orderconfirm').submit(function(e) {
e.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
You have two ways to fix this.
1.Use e.preventDefault(); to prevent browser's default behavior from submitting the form.
$('#orderconfirm').submit(function(e) { // 'e' here is new
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
e.preventDefault(); // and this line is new
});
2. Or just change the submit type to button.
<input type="button" value="submit"/>
By the way, you can get values as parameters instead of string. jQuery.get()
$('#orderconfirm').submit(function(e) {
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var page = 'order.php';
$.get(page, {mail: email, key: key}); // this line
e.preventDefault();
});
Try this
$.get( "order.php", { key: key , mail: email } );

Categories

Resources