After creating everything by the JavaScript dynamically I want to move a single specific value into my C# code; I don't want everything, I have written in the code that which variable I want to be moved into my C# code:
<script>
var test="i want this variable into my c#";
var only for javascript="i don't want this to be travel when i click on submit button";
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type', "submit");
s.setAttribute('value', "submit");
</script>
To get a client variable "into c#", you need to make it part of a request to the server where c# is running. This can be as simple as appending it to a URL, or you may create a new field, or you may populate an existing field and send it.
// a variable
var test = "a value to be sent to the server";
// put the value into a hidden field
document.getElementById("hdnValue").value = test;
// submit the form containing the hidden field
document.getElementById("form1").submit();
Since we are talking about c#, I assume the server is ASP.Net, either web forms or MVC. For MVC, ensure that there is a controller method that takes a corresponding parameter. For web forms, you may include <input type="hidden" runat="server" clientidmode="static" id="hdnValue" />. The page will then have access to this value in the code behind.
i want to travel a single specific value into my c# code ... i don't
want everything
An alternate (and possibly more elegant) way of sending a single value to the server is to POST the value asynchronously using AJAX. I would suggest using jQuery to make this easier, but it can also be done in plain JavaScript.
Here's a jQuery example of an AJAX post:
$.ajax({
url: "http://yourserverurl/",
type: "POST",
data: { test: "a value to be sent to the server" },
success: function(data){
// an optional javascript function to call when the operation completes successfully
}
});
Related
here my simple form:
<form id="myform">
Name:<input type="text" name="name"><br>
Email:<input type="text" name="email">
<a class="btn btn-primary" id="click_btn">Submit</a>
</form>
I want to submit the form with Ajax, that bit is okay so far, and submitting.
Here is my jquery code:
$(document).ready(function() {
$('#click_btn').on('click', function() {
$.ajax({
url: $('myform').attr('action'),
data: $('myform').serialize(),
method: 'post',
success: function(data) {
//success meseg then redirct
alert('success');
var data = $('#myform').serializeArray();
var dataObj = {};
$(data).each(function(i, field) {
dataObj[field.name] = field.value;
window.location.href = 'next_page.php';
});
}
})
});
})
next_page.php is where I want to access, example:
<?php echo document.write(dataObj["email"]); ?>
I want to access these form values that I have submitted on next page after the form is submitted. I have created a data object with all the values using jQuery after submit, but still, I cannot access on the next page. Is there any concept related to the session in jquery for storing that array.
I think you're getting a couple of concepts confused here; I don't mean that in a condescending way, just trying to be helpful.
jQuery, and all JavaScript, exists only on the client-side (for practical purposes - there are exceptions where some client-side code might be rendered or compiled on the server-side for whatever reason but that's another matter). PHP, like any other server-side language, exists on the server-side. These two can't directly access each other's scope - which is why AJAX is useful to transfer data between the front and back ends.
Basically what you appear to be doing here is loading the data in the client-side, but not submitting anything to the server-side. You aren't actually doing any AJAX queries. When you redirect the user via window.location.href =..., no data is actually being transmitted - it simply instructs the browser to issue a new GET request to next_page.php (or wherever you instruct it to go).
There are a couple of options to do what you're trying to achieve:
Actually submit an AJAX query, using the methods outlined here http://api.jquery.com/jquery.ajax/. You can then use next_page.php to grab the data and store it in a session and recall it when the user arrives on the page.
Store the data in a client-side cookie.
Use the standard HTML <form method="next_page.php"...><input type="submit"> to cause the browser to forward the form data to the next_page.php script.
A number of other options but I think those are the simplest.
You can totally use sessionStorage ! (Here is documentation)
If user direct to next page in same tab, sessionStorage can easily save you data and reuse in next page.
// set in page A
window.sessionStorage.setItem('youdata', 'youdata');
// or window.sessionStorage['youdata'] = 'youdata';
// get in page B
var youdata = window.sessionStorage.getItem('youdata');
// or var youdata = window.sessionStorage['youdata'];
That's it! very simple!
If you'll open a new tab, you can use localStorage. (Here is documentation)
The usage of localStorage is like the way of sessionStorage.
While do saving information for other pages, these two method only need browsers' support.
<?php echo document.write(dataObj["email"]); ?>
This is unreasoned! echo is a PHP command, but document.write is a JavaScript command.
If the secound page is PHP, why not send data with a simple POST submit from HTML Form?
You can also use localStorage:
var data = '123';
localStorage['stuff'] = data;
Use localStorage.clear(); to remove all data if you want to write it again or for specific item use localStorage.removeItem('stuff');
List of some possible solutions are as follows:
1. Post the data using AJAX request and the get it in next page by doing DB call (Advisable)
2. Using Local storage you can store the data in the browser to push it to next_page.php https://www.w3schools.com/Html/html5_webstorage.asp
2a. In the first page
<script>
localStorage.setItem("name", "John");
localStorage.setItem("email", "John#test.com");
</script>
2b. In second Page
<script>
var name = localStorage.getItem("name");
var emaeil = localStorage.getItem("email");
</script>
3. Using browser session storage https://www.w3schools.com/jsref/prop_win_sessionstorage.asp
3a. In the first page
<script>
sessionStorage.setItem("name", "John");
sessionStorage.setItem("email", "John#test.com");
</script>
3b. In second Page
<script>
var name = sessionStorage.getItem("name");
var emaeil = sessionStorage.getItem("email");
</script>
I have a HTML <form> and im creating it with php. It contains three <input> fields.
The second <input> field should be filled automatically, when the first one is filled. A HTTP request is triggered over an API. The request works fine and puts out the article number. I tested it already.
The problem is, that it has to run the request and fill the field, whenever the other field is filled.
I have tried it with jQuery:
<script>
$(document).ready(function(){
$("input[name*='artNr1']").click(function(){
.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
});
<script>
Any help is appreciated.
Form screenshot
I think you forgot to insert the $ (dollar sign) before .get()
Your code should be like this :
<script>
$(document).ready(function(){
$("input[name*='artNr1']").click(function(){
$.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
});
<script>
jquery provides the change() method to listen to change events, e.g. on <input> fields. You can replace the click() handler with it.
$("input[name*='artNr1']").change(function(){
$.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
The problem with your code is, that you call jquery.get() with the PHP variable $_POST['artName1']. This shows two flaws:
If the replacement with that PHP value works, it is evaluated on server side and therefore never replaced with the current value from the <input>, that is present on client side
You seem to expect the value to be transferred via POST, but you use jquery.get() to transfer it via GET.
To address the first flaw, you need to use the value from the first <input> instead of the value that was evaluated from PHP.
$("input[name*='artNr1']").change(function(){
var articleNumber = $(this).val();
//TODO: $.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
Because you are currently in the onChange handler of the first <input> field, it is available as the this context in that function. With jquery.val() you can access its current value.
To address the second flaw, you can use two different ways. Either use the jquery.post()mehtod to send your data as POST to PHP:
$("input[name*='artNr1']").change(function(){
var articleNumber = $(this).val();
$.post("artikelnamen_suchen.php", {
'artName1': articleNumber
}).success(function(result){
//Work with the result here
});
});
Or provide the information as GET and access it in PHP as a $_GET field instead of $_POST:
In javascript:
$("input[name*='artNr1']").change(function(){
var articleNumber = $(this).val();
$.get("artikelnamen_suchen.php?artName1=" + articleNumber)
.success(function(result){
//Work with the result here
});
});
In php
$articleNumber = $_GET['artName1'];
... //Use $articleName instead of $_POST['artName1'] in your PHP code.
After that you can work with result to replace the value in your second input. But thats another question... :-D
I have a simple form on my homepage (index.php), that takes one user input.
<form action="/run.php" method="POST" target="_blank"
<input type="text" name="userinput">
<button type="submit">Run!</button>
</form>
That input is then passed to run.php where the content is displayed and inserted into a MySQL database.
However, I need to run JavaScript functions on that user input, and then input the results (from the JavaScript function) into the database (so passing the value from JavaScript to PHP).
I originally had the JavaScript in the run.php, which worked for calculating and displaying the value, but I was unable to pass the value to PHP to insert into the database.
From what I've read, you can't pass JavaScript values to PHP on the same page, as it requires some sort of POST or GET, so I'm attempting to run the JavaScript functions on the homepage index.php and then use a hidden input field to POST the value to the run.php file.
<input id='hidden_input' type='hidden' name='final-calc' value='random(userinput)' />
Where the function is a JavaScript Promise:
function random(userinput) {
....
.then(function(userinput) { // Function needs to use the userinput from the form
// calculations
return X //(X being any random value)
}
}
The two problems I'm running into is that:
I can only get the userinput value after the user enters a value and submits the form, so I don't believe I can pass that userinput value into the JavaScript function and still POST the returned value?
The JavaScript function is an asynchronous Promise, but apparently, this might not have an effect - so it may not be a problem.
The key here is AJAX. You have to retrieve the userinput using plain JS, make any calculations needed and then send the results to your PHP script. I left a fiddle: https://jsfiddle.net/k5xd54eu/1/
<input type="text" id="userinput" name="userinput"/>
<button onclick="inputhandler();">TEST</button>
<script>
function inputhandler() {
var text = document.getElementById('userinput').value;
alert(text);
/*DRAGONS BE HERE*/
/*THEN*/
/*USE AJAX HERE TO PASS THE RESULTS TO PHP SCRIPT*/
}
</script>
I'm not explaining how to implement the AJAX call to send the results, mainly because it's a matter of taste too. For example you can use plain JS or a library such as jQuery (which is my personal preference, since it's very clean and easy). Take a look here:
http://api.jquery.com/jquery.ajax/
and here:
https://www.w3schools.com/jquery/jquery_ajax_intro.asp
for more information.
EDIT: Since I've mentioned AJAX, it would be more correct to include some code. So this is what I generally use for simple POSTs (it's based on the jQuery library so be careful to include it):
var url = 'ajaxhandler.php';
var stuff = '1234abcd';
$.ajax({
type: "POST",
url: url,
data: {stuff: stuff},
success: function (data) {
/*Do things on successful POST*/
}
});
I have a situation where I want to hit a button in the GSP (actionSubmit) and update a div when I finish the call (which includes a call to a javascript function). I want to ultimate end up in the controller rendering the searchResults parameter and the div with the results (which is currently working).
Problem is, I need to (presumably) wrap my actionSubmit in a remoteForm. But how do I:
1) Run the javascript method already existent in the onClick
2) Render the page in the controller.
If I try both wrapped in a controller, I finish the remoteForm action and the javascript action "hangs" and never finishes.
Any ideas?
List.gsp
<g:actionSubmit type="button" value="Ping All" onclick="getIds('contactList');"/>
function getIds(checkList)
{
var idList = new Array();
jQuery("input[name=" + checkList + "]:checked").each
(
function() {
idList.push(jQuery(this).val());
}
);
$.ajax({
url: "pingAll",
type:"GET",
data:{ids:JSON.stringify(idList)}
});
}
controller:
def pingAll() {
String ids = params.ids
if(ids == "[]") {
render(template:'searchResults', model:[searchResults:""])
return
}
def idArray = contactService.formatIDString(ids)
idArray.each {
def contactInstance = Contact.get(Integer.parseInt(it))
emailPingService.ping(contactInstance)
}
/**
* Added this on 3/13. Commented out line was initial code.
*/
def searchResults = contactSearchService.refactorSearchResults(contactSearchService.searchResults)
render(template:'searchResults', model:[searchResults:searchResults, total:searchResults.size()])
}
You have a couple options:
1) You can avoid using the Grails remote tags (formRemote, remoteField, etc.), and I really encourage you to explore and understand how they work. The Grails remote tags are generally not very flexible. The best way to learn how they work is to just write some sample tags using the examples from the Grails online docs and then look at the rendered page in a web browser. All the tags do generally speaking are output basic html with the attributes you define in your Grails tags. Open up your favorite HTML source view (i.e. Firebug) and see what Grails outputs for the rendered HTML.
The reason I say this is because, the code you've written so far somewhat accomplishes what I've stated above, without using any GSP tags.
g:actionSubmit submits the form you are working in using the controller action you define (which you haven't here, so it runs the action named in your value attribute). However, you also have an onClick on your actionSubmit that is running an AJAX call that also submits data to your pingAll action. Without seeing the rest of your code and what else is involved in your form, you are submitting your form twice!
You can simply just not write actionSubmit, and simply do an input of type button (not submit) with an onClick. Then in your javascript function that runs, define a jQuery success option for your AJAX call
$.ajax({
url: "pingAll",
type:"GET",
data:{ids:JSON.stringify(idList)},
success:function(data) {
$('#your-updatedDiv-id-here').html(data);
}
});
2) If you want to use the GSP tags, I think you are using the wrong one. Without knowing the full extent of your usage and form data involved, it looks like g:formRemote, g:submitToRemote, and g:remoteFunction could serve your purposes. All have attributes you can define to call javascript before the remote call, as well as defining a div to update and various event handlers.
I have an html text-area which uses ajax-autocomplete where it populates the dropdown as i start typing. When I select an entry from the dropdown it will set some field to the id of that object.
Once I get the id of the object is there a way I could do something like this?
<% #myObjects.find(1) do |myObj| %>
<h1><%= myObj.attr1 %><h1>
<h2><%= myObj.attr1 %><h2>
<% end %>
Right now, when I get the id of the object I am using jquery's attr() function to set the values which exposes my javascript logic which I don't really like. Is there a way I can activate the field? Or, hide the fields and where the id is populated show the field and let ruby do its magic with myObjects.find?
UPDATE:
Right now the way I am populating the fields in the view like this:
$(function() {
// Executes a callback detecting changes with a frequency of 1 second
$("#id_element_placeholder").observe_field(1, function(){
//alert('Change observed! new value: ' + this.value );
$.ajax({
type: "GET",
dataType: "json",
url: "/myobj/get/" + this.value,
success: function(data){
$('#last_name').attr('value', data.myobj.last_name);
$('#first_name').attr('value', data.myobj.first_name);
}
});
});
});
Is there a way around exposing the above javascript code?
There is nothing wrong with your javascript and you seem to be confused between client side and server side technologies. Ruby cannot directly update your page once it has been sent to your user. It is on your web server and your page has been sent to the clients browser. It can however send javascript in response to a further request made by your application from the clients browser to do exactly that, just as you are doing.
You could send a new html snippet to your browser and replace the entire node but really there is no point. What you are doing is the same as everybody else who uses javascript.
Answer is simple, you can't :)
What you are doing is ok, using AJAX for such things is the way to have such a things done.
If you are concerned about exposures don't look at javascript, look at what the server side code allow a user to do with get/post methods ;)