Where are the JavaScript field definitions? - javascript

I have a PHP form that includes javascript js_qty.js. Js_qty_.js has this function called xhrGetValue.
I am in my NetBeans IDE and it shows the field definitions for f.job_id, f.item_id, etc. I have looked in the JavaScript and the HTML portion of the PHP and I cannot find the field definitions.
Where else could I look to find the field definitions?
function xhrGetValue(field) {
//eval('document.forms[0].'+field+'.value=document.forms[0].'+field+'_value.value');
var r='GetValue';
var url = "job_qty_xhrr.php"; // The server-side script
var f=document.forms[0];
var param = 'p_id='+f.p_id.value+'&job_id='+f.job_id.value+'&r='+r+'&field='+field+'&item_id='+f.item_id.value+'&sub_id='+f.sub_id.value+'&qty_id='+f.qty_id.value;
http.open("GET", url+'?'+param, true);
http.onreadystatechange = handleHRGetValue
http.send(null);
}

var f=document.forms[0];
Tells you p_id and job_id are coming from the first form in your document (page). Check the html again or check to see if the fields are being generated by javascript.

Related

How send string parameter using Post Method from the view to the controller ASP.NET [duplicate]

Here is a line of code in my Controller class:
return JavaScript(String.Format("window.top.location.href='{0}';", Url.Action("MyAction", "MyController")))
Is there a way to make it use the verb=post version of MyAction?
You can't use POST by simply navigating to a different URL. (Which is what you'd do by changing location.href.)
Using POST only makes sense when submitting some data. It's not clear from your code what data would actually be POSTed.
If you really want to initiate a POST via javascript try using it to submit a form.
I came across the same problem myself and solved it using a data- attribute and some jQuery. The benefit of doing it this way is that you still get the correct URL when you hover over the link, even though it does a POST. Note that the Html.BeginForm contains the default action in case the user hits the enter key.
HTML (ASP.NET MVC3 Razor)
#using (Html.BeginForm("Quick", "Search"))
{
<input type="text" name="SearchText" />
Search
Advanced
}
jQuery
$("a[data-form-method='post']").click(function (event) {
event.preventDefault();
var element = $(this);
var action = element.attr("href");
element.closest("form").each(function () {
var form = $(this);
form.attr("action", action);
form.submit();
});
});
Continuing off of Matt Lacey's answer, your action could return a bit of Javascript that does this:
Use jquery to add a new form to the DOM
Use jquery to submit the newly added form
Something like this: (untested code)
var urlHelper = new UrlHelper(...);
var redirectUrl = urlHelper.Action("MyAction", "MyController");
var redirectScript = String.Format(#"
var formTag = $('<form action=""{0}"" method=""post"" id=""redirectForm""></form>');
$(body).append(formTag);
formTag.submit();"
, redirectUrl
);
return JavaScript(redirectScript);

How to receive HTTP POST parameters on vue.js? [duplicate]

I am trying to read the post request parameters from my HTML. I can read the get request parameters using the following code in JavaScript.
$wnd.location.search
But it does not work for post request. Can anyone tell me how to read the post request parameter values in my HTML using JavaScript?
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:
var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;
Then just access the JavaScript variable in the normal way.
Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.
JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.
Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.
Use sessionStorage!
$(function(){
$('form').submit{
document.sessionStorage["form-data"] = $('this').serialize();
document.location.href = 'another-page.html';
}
});
At another-page.html:
var formData = document.sessionStorage["form-data"];
Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Why not use localStorage or any other way to set the value that you
would like to pass?
That way you have access to it from anywhere!
By anywhere I mean within the given domain/context
If you're working with a Java / REST API, a workaround is easy. In the JSP page you can do the following:
<%
String action = request.getParameter("action");
String postData = request.getParameter("dataInput");
%>
<script>
var doAction = "<% out.print(action); %>";
var postData = "<% out.print(postData); %>";
window.alert(doAction + " " + postData);
</script>
You can read the post request parameter with jQuery-PostCapture(#ssut/jQuery-PostCapture).
PostCapture plugin is consisted of some tricks.
When you are click the submit button, the onsubmit event will be dispatched.
At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.
I have a simple code to make it:
In your index.php :
<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>
In your main.js :
let my_first_post_param = $("#first_post_data").val();
So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.
POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
$val = json_encode($value); // Escape value
$vars .= "var $field = $val;\n";
}
echo "<script>\n$vars</script>\n";
}
?>
</script>
Or use it to put them in an dictionary that a function could retrieve:
<script>
<?php
if($_POST) {
$vars = array();
foreach($_POST as $field => $value) {
array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
}
echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>
Then in JavaScript:
var myText = post['text'];
// Or use a function instead if you want to do stuff to it first
function Post(variable) {
// do stuff to variable before returning...
var thisVar = post[variable];
return thisVar;
}
This is just an example and shouldn't be used for any sensitive data like a password, etc. The POST method exists for a reason; to send data securely to the backend, so that would defeat the purpose.
But if you just need a bunch of non-sensitive form data to go to your next page without /page?blah=value&bleh=value&blahbleh=value in your url, this would make for a cleaner url and your JavaScript can immediately interact with your POST data.
You can 'json_encode' to first encode your post variables via PHP.
Then create a JS object (array) from the JSON encoded post variables.
Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
One option is to set a cookie in PHP.
For example: a cookie named invalid with the value of $invalid expiring in 1 day:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
Then read it back out in JS (using the JS Cookie plugin):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
You can now access the value from the invalid variable in JavaScript.
It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language.
So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
And therefrom use post['key'] = newVal; etc...
POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.
SITE A: has a form submit to an external URL (site B) using POST
SITE B: will receive the visitor but with only GET variables
$(function(){
$('form').sumbit{
$('this').serialize();
}
});
In jQuery, the above code would give you the URL string with POST parameters in the URL.
It's not impossible to extract the POST parameters.
To use jQuery, you need to include the jQuery library. Use the following for that:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
We can collect the form params submitted using POST with using serialize concept.
Try this:
$('form').serialize();
Just enclose it alert, it displays all the parameters including hidden.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.

How can I access my Javascript Variables in PHP?

I have a file called lightstatuspage.php and within it, I have HTML, JavaScript and PHP code. I have used some variables within the JavaScript part of the code and I am trying to send these variables to the server by passing them to the PHP part of the code. However, this is not working.
I am using $.post("lightstatuspage.php", slider_val); and then in the PHP part, I am calling the variable by doing $_GET['rangeslider_val'];.
What am I doing wrong and what can I do differently to get the variable from JavaScript and send it to the server?
function show_value(x)
{
document.getElementById("slider_value").innerHTML=x;
event.preventDefault();
var slider_val = x;
var query = new Parse.Query(Post);
query.first({
success: function(objects){
objects.set("slider_val", slider_val);
objects.setACL(new Parse.ACL(Parse.User.current()));
return objects.save();
window.location.href = "lightstatuspage.php?rangeslider_val=" + slider_val;
}
})
}
The PHP code is:
<?php
$_GET['rangeslider_val'];
print($rangeslider_val);
?>
First Add Jquery
<script src='https://code.jquery.com/jquery-1.11.3.min.js'></script>
to the end of page before closing body tag.
To send Javascript variable to PHP. the best way is to use Ajax. and add the following code to your javascript.
Do not forget that the below code should be on an event. For example on a button click or something like that
$( document ).ready(function() {
var x = $('#input1').val();
//or var x= 15;
$.post("lightstatuspage.php",
{
'rangeslider_val': x
},
function(data, status){
//alert("Data: " + data + "\nStatus: " + status);
// you can show alert or not
});
});
and in php, you can use:
$value = $_POST['field1'];
now your variable is in $value in php.
P.S:
Backend Page and HTML page should be on same domain or you have to check Cross-Origin Resource Sharing
Second Solution
as the User accepted this solution here would be the code:
$.get("lightstatuspage.php?rangeslider_val=" + slider_val,function(res) {
console.log(res);
});
the second way is only the difference between POST and GET method
Third Solution
if you don't want to use Jquery in your project and you need pure javascript you can use below code
var str = "Send me to PHP";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "lightstatuspage.php?rangeslider_val=" + str, true);
xmlhttp.send();
Change the order of the last 2 lines of your JS function. You are returning from the function before changing the page's location.
you forgot to store variable on print
<?php
$rangeslider_val = $_GET['rangeslider_val'];
print($rangeslider_val);
?>
You call $_GET but you don't assign the value to the variable $rangeslider_val in PHP and you are returning in JavaScript before calling the PHP script. Also you mentioned that you want to use $.post from clentside if you do it this way you have to use PHP $_POST to get it from there.

Javascript - Send Javascript Variable to PHP

I want to send the value of a JavaScript variable (variableToSend) to a PHP variable ($latLong) which then gets posted to MySQL. The JavaScript variable is capturing the value of an HTML textbox outside of a form listed below:
<input type="text" id="latLng" value="Working"/>
The textbox value passes to the Javascript variable just fine (I've tested via an alert with the variable's value):
<script language="JavaScript">
setTimeout(function(){
var variableToSend = document.getElementById("latLng").value;
$.post('html/index.php', {$latLong: "variableToSend"});
}, 10000);
</script>
However, the $.post method is not firing. I'm thinking one of a couple of things were happening. One, the text field was not in a form which is why it didn't pass to the PHP variable. I tested this by throwing the text field back in a form tag, but that didn't work. Second, the $.post method is written incorrectly. Third, the $.post method is not firing at all after the 10 second interval. I'm thinking it's the third case but would like some direction if at all possible.
Any help is greatly appreciated.
You can use a QueryString appended to the script. Another better option would be to use the FormData object.
Here is a sample from MDN:
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"
// HTML file input user's choice...
formData.append("userfile", fileInputElement.files[0]);
// JavaScript file-like object...
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});
formData.append("webmasterfile", blob);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

How do you get URL parameters in a Google Form using Google Apps Script?

So I've got a Google Form where I'd like to pass in a parameter from an email link like this:
https://docs.google.com/URL/forms/d/LONGSTRING/viewform?id=12345
I'd like to be able to grab that id and pass it into the spreadsheet recording results. Now I've got writing to a spreadsheet down, but getting the id is problematic.
I've already tried:
function doGet(e) {
var id = e.parameter.id;
Logger.log(id);
}
and
function doPost(e) {
var id = e.parameter.id;
Logger.log("do post " + id);
}
Both of which throw errors when I view the execution transcript, which I suspect is because they're designed to run within deployed webapps.
Additionally, I've tried using plain old javascript to do something like:
var formUrl = window.location.href;
var formId = formUrl.split('?id=')[1];
which also throws errors when you view the execution transcript .
Any other ideas?? Maybe I can get the information in another way?
I think you can't use your own id, you have to use the id of the Google Form's "Item" object. You can figure out the id by viewing a prefilled form. In the Form edit screen, click "Responses", "Get Pre-filled URL". Fill in the field that you want to use and click Submit. On the new page, you are given a URL in "Share this link to pre-fill the responses" . Examine that url and you can see "get" arguments like ?entry.265525444=mytext . Replace mytext with whatever you want to be in the field.
This will display the field on your form, however. I myself was searching for how to make such a field readonly or invisible when I got here, but I hope this shows you a new direction to try.
I am assuming you are trying to get the form id?
You will need to set up a trigger that will run on form submit.
function onSubmit(){
var form = FormApp.getActiveForm();
var formID = form.getId();
}

Categories

Resources