I am working in ASPDotNetStorefront on an XML package (largely irrelivant). Basically I have a form with a bunch of fields and a button that 'submits' the form. I would actually like to have the button convert the values of the fields into a querystring and then perform a GET instead of a POST.
I would imagine that I could do something like this with JavaScript, perhaps jQuery, but I'm not sure how I would do that. Ideally, I would like a simple function I could call.
I should note that I'm using ASP.Net and I only want to convert the actual values of the fields to a query string, not any state information. This is for a search form.
With jQuery:
$.ajax({
url: 'url/Action',
type: 'GET',
data: $('#formId').serialize()
})
using:
jQuery ajax
jQuery serialize
Response.Redirect("Webform2.aspx?Name=" +
this.txtName.Text + "&LastName=" +
this.txtLastName.Text);
in WebForm2.aspx you can do like this
for (int i =0;i < Request.QueryString.Count;i++)
{
Response.Write(Request.QueryString[i]);
}
for jquery you can use AJAX to send data between pages. Here is the sample code
This is the best article i have found Using jQuery for AJAX in ASP.NET : codeproject
example of using AJAX
<div style="width:350px">
<div style="background:#CCC"> Edit</div>
<div id="divView"><asp:literal id="litName" runat="server"/></div>
<div id="divEdit" style="display:none"></div>
</div>
var options = {
method: 'POST',
url: 'ChangeName.aspx',
after: function(response) {
$("div#divView").html(response).show();
$("div#divEdit").empty().hide();
$("a#editName").show();
}
};
//bind to form's onsubmit event
$("form#ChangeName").ajaxForm(options);
Example without AJAX.Simple Javascript with Query String
<script lang=”javascript” type=”text/javascript”>
function testQueryStrings()
{
window.location = “search.aspx?q=abc&type=advanced”;
}
</script>
<input type=”button” id=”btn” value=”Test Query Strings” onclick=”testQueryStrings()” />
for search.aspx
<script lang=”javascript” type=”text/javascript”>
var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split(‘&’);
for (var i=0;i<arr.length;i++){
// splits each of field-value pair
var index = arr[i].indexOf(‘=’);
var key = arr[i].substring(0,index);
var val = arr[i].substring(index+1);
// saves each of field-value pair in an array variable
arrQrStr[key] = val;
}
document.write(“<h1>Search parameter: “+arrQrStr["q"]+”. Extra parameter: “+arrQrStr["type"]+”</h1>”);
You could do this:
<input type="submit" value="get">
With (since you tagged this jQuery):
jQuery('input[type=submit]').click(function () { this.form.method = 'GET'; });
… but forms that might go to bookmark-able data or might make significant changes sound like they would be confusing to the user (and I can't think of any other reason to switch from post to get on the fly in end user controls).
If you always want to GET data, then you should modify the source sent to the browser instead of twiddling the DOM on the fly with JS.
Really, you just need to change the method attribute of your <form> tag in your HTML.
If you don't have direct control over the markup that your .NET component generates, you can always manipulate the <form> tag and set the attribute with JavaScript when the page loads.
Or, you can bind a click event to the form's submit button, and cancel the event (by returning false for example), and do a GET yourself.
You could just se <form method="GET"> instead of <form method="POST">. No Javascript needed (unless you do not want to refresh the page).
Related
Is it possible to catch the URL generated from a form when firing its 'submit' event?
I know I can generate the URL from data
I'm not talking about form's action URL
I mean the ?field=value&other-input-name=value& ... part
Scenario:
We have a form and a JavaScript script which sends an Ajax request to a PHP script.
I usually do like this:
Register for the form's submit event
Prevent the default behavior
Construct a URL from data
Open an HTTP request with the constructed URL
Now, I was wondering, when firing 'submit' normally (on non-Ajax requests) the URL gets constructed by the form, which then uses that URL to send data to the PHP counterpart.
How can I 'catch' that URL? There aren't any clues from the event itself which doesn't seem to store it, or at least I haven't been able to find it.
It must be somewhere!
This is possible and easy with the objects URLSearchParams and FormData.
FormData is an object representation of a form, for using with the fetch API. It can be constructed from an existing element like this:
let form = document.forms[0];
let formData = new FormData(form);
Then comes the URLSearchParams object, which can be used to build up query strings:
let search = new URLSearchParams(formData);
and now all you need to do is call the toString function on the search object:
let queryString = search.toString();
Done!
If you mean getting the form's action URL, that URL can be retrieved like this:
document.getElementById("form-id").action
If you are using jQuery and assuming you are doing an Ajax request, it would be like this:
var el = $('#form-id');
$.ajax({
type: el.attr('method'),
url: el.attr('action'),
data: el.serialize(),
context: this
}).done(callback);
To put it simply, you can't. The best you can do is to collect the form field values yourself, or using jQuery's .serialize() function, which returns those values exactly as you'd expect:
name=value&name2=value2
As already stated, you cannot get the generated URL containing the form values that the browser generates, but it is very easy to construct it yourself.
If you are using jQuery then use serialize(). If not, refer to the post Getting all form values by JavaScript.
var targetForm = $('#myForm');
var urlWithParams = targetForm.attr('action') + "?" + targetForm.serialize();
alert(urlWithParams);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="/search/" id="myForm" method="get">
<input name="param1" type="hidden" value="1">
<input name="param2" type="hidden" value="some text">
</form>
You can use javascript to generate it:
<script>
function test(frm) {
var elements = frm.elements;
var url = "?";
for(var i=0;i<elements.length;i++) {
var element = elements[i];
if (i > 0) url += "&";
url += element.name;
url += "=";
if (element.getAttribute("type") == "checkbox") {
url += element.checked;
} else {
url += element.value;
}
}
console.log(url);
return false;
}
</script>
<form onsubmit='return test(this);'>
<input name=field1 value='123'>
<input type=checkbox name=field2 checked>
<input type=submit>
</form>
I have an HTML form that I am trying to convert to submitting using the Jquery load() function. I have it working for a single field, but I have spent hours trying to get it to work for multiple fields, including some checkboxes.
I have looked at many examples and there seems to be about three of four ways of approaching this:
Jquery .load()
jquery .ajax()
jquery .submit()
and some others. I am not sure what the merits of each approach is but the first example I was following used the .load(), so that is what I have persisted with. The overall object is to submit some search criterion and return the database search results.
What I have at present:
<code>
// react to click on Search Button
$("#SearchButt").click(function(e){
var Options = '\"'+$("#SearchText").val()+'\"' ;
var TitleChk = $("#TitleChk").prop('checked');
if (TitleChk) Options += ', \"TitleChk\": \"1\"';
// load returned data into results element
$("#results").load("search.php", {'SearchText': Options});
return false; //prevent going to href link
});
</code>
What I get is the second parameter appended to the first.
Is there a way to get each parameter sent as a separate POST item or do I have to pull it apart at the PHP end?
It would seem as if you're stumbling over the wrapper, let's go ahead and just use the raw $.ajax() and this will become more clear.
$("#SearchButt").click(function(e){
var Options = {};
Options.text = $('#SearchText').val();
Options.title = $('#Titlechk').prop('checked')) ? 1: 0; //ternary with a default of 0
$.ajax({
url: 'search.php',
type: 'POST',
data: Options
}).done(function(data){
$('#results').html(data); //inject the result container with the server response HTML.
});
return false;
});
Now in the server side, we know that the $_POST has been populated with 2 key value pairs, which are text and title respectively.
I have a multi page form.
Page One has a few fields that get passed into the second form, via GET method, and it auto fills the first four fields of the second part of the form.
Page two has a few more questions, and when you submit it, it submits into our CRM(vanillaSoft), and leads to a thank you page.
My current issue:
I want to be able to take an affiliate link, such as:
http://something.com/step-one.html?AFFILIATE_ID=#affid#&SUB_ID=#s1#
I need to dynamically populate the AFFILIATE_ID parameter with a unique transaction ID, and the SUB_ID with a unique ID as well.
I currently have two fields on my first page with hidden fields, ex:
<input type="hidden" name="SUB_ID">
<input type="hidden" name="AFFILIATE_ID">
But that isn't working. I need this date to be sent into the CRM I use.
Any advice?
Thanks!!!
Your current setup will work if you set your form submit method to GET. You probably have it set to POST.
Setting your form method to GET will put those hidden fields in the URL, like you are expecting.
On the last form, set that one to POST (to POST to the server).
You can grab the Query string with JavaScript, like this:
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();
How can I get query string values in JavaScript?
You could also send both POST and GET methods. But POST can be done only on server side, where JavaScript is Client-side scripting language.
<form method="POST" action="form.php?a=1&b=2&c=3">
PHP -> Send both POST and GET in a form
How to read the post request parameters using javascript
As a novice js and jqplot programmer, I need guidance on passing an array of value from php to an external javascript for plotting (using jqplot). I am confused about the order and how html, php & external js, jqplot is called. A short sample code structure will be very helpful to follow. We may use the following sample codes as guide. Thanks
$(document).ready(function(){
var plot1 = $.jqplot ('chart1',[[3,7,9,1,4,6,8,2,5]],{title: 'Plot'});
});
Instead of the fixed data points above, I want them to dynamically loaded via an array from the following php script.
<?php
$Start_Value = $_POST['Start'];
$End_Value = $_POST['End'];
for($i=$Start_Value;$i<=$End_Value;$i+++)
$Plot_Val[$i] = $i + 2;
json_encode($Plot_Val);
?>
You have several options. Here are the 2 easiest:
Just 'paste' the array from PHP as a JavaScript global variable.
Add <script>var myData = <%= json_encode($Plot_Val); %>;</script> at the top of your page and then use myData in place of the data array.
Even better option is to use Ajax to call the PHP page from JavaScript and get the results , separating front-end and back-end code.
Best way is to use AJAX, something like this in JS:
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
Update: To get your values from a form, you cannot put form action to js, but rather use js to get the values from a form. So the form itself shouldn't do a POST request, but rather the js should take the values from a form and send the POST.
Something like this:
<form>
<input type="text" id="start">
<input type="text" id="end">
<button id="submitButton">Submit Me!</button>
</form>
JS, we will wrap the above AJAX code into a function:
function submitValues(startValue, endValue) {
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
}
$(document).on('click', '#submitButton', function(){
var start = Number($('#start').val());
var end = Number($('#end').val());
//I guess you need numbers instead of text, that's why they are wrapped inside Number()
submitValues(start, end);
});
This should work.
Keep in mind that I have no idea what your form looks like, this is just a dummy example, but it should be similar enough. You get the form values with the jQuery's .val() method and then give those values to the ajax function.
can we pass any info., say a string between html pages using javascript. No forms, input fields I am using just want to pas some info in hyperlink.
What's your use-case?
There are lotta ways to do it. Say...
Storing the data in a session cookie (Assuming that you're accessing 2 pages from the same domain.)
Passing data in query string?
For example,
<input id="btnClickMe" onclick="btnClickMe_onClick()" type="button" />
...
<script type="text/javascript">
function btnClickMe_onClick() {
var data = "foo";
var urlOfNewPage = "http://www.test.com/testPage?data=" + data;
// Redirect user to the new URL
}
</script>
By the expression "info in hyperlink" i guess you want to let user inititate communication by clicking on it.
This could work:
Click here
<script>
extra_data = "key1=value1&key2=value2";
document.getElementById("mylink").href = "http://example.com/?" + extra_data;
<script>
Yes. There are many simple ways to do this if all you need to do is pass a short string. You could include a string in a link after a '#' and have that read by Javascript on the next page (looking at location.hash).
Without knowing more, its hard to narrow the approach down to suit your needs.
Simple Example:
one.html
...
Pass data
...
two.html
<script>
var passedData = location.hash.replace('#','');
alert('You passed this data: ' + passedData);
</script>