fill articlenumber automatically after writing articlename - javascript

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

Related

JavaScript to PHP form, based on user input

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*/
}
});

Node js setup an Anchor [duplicate]

I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid() can check for "undefined" or other things you don't want to handle.
Also, make sure you use $(document).ready() appropriately, of course.
[RFC 2396][1] section 4.1:
When a URI reference is used to perform a retrieval action on the
identified resource, the optional fragment identifier, separated from
the URI by a crosshatch ("#") character, consists of additional
reference information to be interpreted by the user agent after the
retrieval action has been successfully completed. As such, it is not
part of a URI, but is often used in conjunction with a URI.
(emphasis added)
[1]: https://www.rfc-editor.org/rfc/rfc2396#section-4
That's because the browser doesn't transmit that part to the server, sorry.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX).
Regards
Artur
You may see also how to play with back button and browser history
at Malcan
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Possible solution for GET requests:
New Link format: http://example.com/yourDirectory?hash=video01
Call this function toward top of controller or http://example.com/yourDirectory/index.php:
function redirect()
{
if (!empty($_GET['hash'])) {
/** Sanitize & Validate $_GET['hash']
If valid return string
If invalid: return empty or false
******************************************************/
$validHash = sanitizeAndValidateHashFunction($_GET['hash']);
if (!empty($validHash)) {
$url = './#' . $validHash;
} else {
$url = '/your404page.php';
}
header("Location: $url");
}
}

How to get a specific value from JavaScript to C# coding?

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
}
});

submitting form through javascript and passing a variable with it

I want to submit a form and add a javascript variable with it. I tried using AJAX but that didn't work properly because the form is cut in two parts on the same page. I'm now using a <button onclick='submit_form()'>send</button> which calls on the following function:
function submit_form()
{
document.getElementById("form2").submit();
}
however I need to pass on a javascript variable current_score I have it declared and it has a value I just don't know how to add this to my submit function I tried using a return within the function itself and writing a function for it but neither worked :) help and hints are greatly appreciated.
The idea is that people receive a score fill a form and send it to a database, The ajax script part was to try and pass the values on to the next page that will submit the data
Your question is not very clear. The simple way would be to append a get parameter to the URL you are requesting. The following example will append a hidden input element to your form:
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "theName";
hidden.value = current_score;
var f = document.getElementById("form2");
f.appendChild(hidden);
f.submit();
You could store the information in window.variable also

I replace HTML using javascript, but that contains a form, want to keep value of that form

I have a page that I have a page I pull from the server every x seconds using some ajax, and then I replace some HTML on the site with the new HTML pulled from the server. The problem has always been that there is a form in that HTML. I want to know is there a way to preserve the value of the form (that the user has entered) when replacing the html in javascript.
Use two callback functions (you should use $.ajax), in the callback before sending (beforeSend(x){ /your code here/; }) you save the parameters (to an array or hashtable): saved = $(element).val(); then in the second callback (use success(x){}) you write them back in. using $(element).val(saved);
var save = document.getElementById('userForm').value;
//replace HTML
document.getElementById('userForm').value = save;
Two ways,
Send and then replace the value in the HTML on the server
Using JavaScript, save it in a session: http://www.webreference.com/authoring/languages/html/HTML5-Client-Side/
I'd say the best solution would be to combine the two and save a session on the server, then load it each time you load the HTML.
-Sunjay03

Categories

Resources