JavaScript to PHP form, based on user input - javascript

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

Related

Displaying data on next page with jQuery session or another possible way?

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>

How you can save appends to variables an then convert them to php so you can save them in a database?

<html>
<head>
<meta charset="utf-8">
<title>Test page for Query YQL</title>
<link rel="stylesheet" href="http://hail2u.github.io/css/natural.css">
<!--[if lt IE 9]><script src="http://hail2u.github.io/js/html5shiv.min.js"></script><![endif]-->
</head>
<body>
<h1>Test page for Query YQL</h1>
<div id="content"></div>
<input type="button" name="bt1" value="click" onclick="pesquisa()">
<form name="s2">
<input type="text" name="s1">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.query-yql.min.js"></script>
<script type="text/javascript">
function pesquisa(){
$(function () {
var t = $('#content').empty();
var url= document.s2.s1.value;
var statement = 'select * from feed where url="'+url+'"';
$.queryYQL(statement, function (data) {
$('<h2/>').text('Test: select * from feed').appendTo(t);
var r = data.query.results;
var ul = $('<ul/>');
$.each(r.item, function () {
$('<li/>').append(this.title).appendTo(ul);
$('<li/>').append(this.link).appendTo(ul);
<?php
$titulo = "<script>document.write(titulo);</script>";
$site = "<script>document.write(site);</script>";
//echo $titulo;
//echo $site;
?>
});
ul.appendTo(t);
});
});
};
</script>
</body>
</html>
How can you save the this.title and the this.link values into 2 different variables an then call them into php so you can insert the data into a DB?
It's just a simple YQL query to search on rss feeds.
After doing the query, I want the results to be saved in a database, but I can't discover how to do that.
First of all, you have to understand that you are working on a Client-Server architecture.
This means:
Let's say that this file you are showing us is called "TestYQL.php" (because you did not say the name of it). This file is executed by php (server side), which reads line by line the contents of it, and generates another new file from the original. For educational purposes, let's say the generated file is called "GeneratedTestYQL.html". This file no longer has any php code inside, since it is directly html and js flat. It knows nothing about php. So there are no php functions, variables, nothing. This last file is the one that reaches the client, and the code is executed by a web browser like Chrome, Firefox, etc.
In your case, the file "TestYQL.php" all you have of php is what is inside the <? Php ....?> Tags. With php you creates 2 variables, each with a tag inside, but without any purpose since they are not used in any way. So, the generated "GeneratedTestYQL.html" file is the same as the original, but without the lines inside the <? Php ...?>.
This means that: The contents of the variables that you use in PHP can be sent to the browser, because with PHP you will generate the file that will be executed in the browser.
Now, when the file "GeneratedTestYQL.html" arrives, the browser starts to show all the contents of the file, it generates the form in which, when you click the button, executes the function pesquisa() and now starts javascript (JQuery) bringing data of the feeds, and for the first time, these variables "this.title" and "this.link" begin to exist in javascript.
Since there is no such thing as php here, you can NOT access those variables from php.
So, how to save that data in a DB?, well, the common way is to send all the data you want from the browser, to the server, then the server sees what to do with that data. To send data from the browser to the server, you do it by making GET or POST requests to a php file from the server (preferably another file, let's say it will be called "saveFeeds.php").
Data can be sent with a GET request, but it is semantically incorrect since GET means you want to fetch data from the server. So to send that data to the server, you will have to make a POST request from the browser, which is more appropriate.
There are now 2 simple ways to make a POST request. The first and most common of these is from a form in the browser, the other way is using Ajax.
How to do it from a form?
Currently in your code, you have already put a form (That is called "s2"), although currently the same is not necessary, but leave that now.
If you wanted to send the data through a form, you should do 2 things. First and most obvious, create the form; second, the data received from the internet (title and link of feed), send them to the server.
Assuming you fetch data from a single feed per url, and the designated file in charge of receiving the request will be "saveFeeds.php". So, you could create a form like the following after the previous one:
<Form class = "sender" action = "saveFeeds.php" method = "post">
  <Input type = "hidden" name = "title" value = ""> <br>
  <Input type = "hidden" name = "link" value = ""> <br>
  <Input type = "submit">
</ Form>
Then you need to put the feed data inside the form, because, at this moment, you can't send anything. You could add a function like:
Function appendFeedToForm (title, link) {
  Var form = $ (". Sender");
  Form.title.value = title;
  Form.link.value = value;
}
And then call it from inside the $ .each of the result as
AppendFeedToForm(this.title, this.link);
The second case, the easiest way to make a request to the same file using Ajax is with a JQuery shortcut:
$.post("saveFeeds.php", r.item);
If you are interested in validations, you can take a look at the JQuery documentation. The important thing about ajax requests is that you can send all the data you want without having to force you to reload the page. Therefore, you can send as many feeds as you want in the same way you would send one.
Now with the data sent from the client to the server, it is necessary to handle the reception of the data. Currently we were pointing all the data to the file "saveFeeds.php", so, now, finally we can put the content from javascript. To access them, simply in that file, you should check the fields:
$ _POST ['title'] // This names are from input names of form
$ _POST ['link'] // or properties sended through Ajax
So, here, you have tp prepare the connection to your database and save those parameters. Currently you did not mention which database engine you are using, so, for this moment, I'll shorten the answer here.
Note: I was not giving you the best practices to solve your problem, but rather the minimum necessary.

Post hidden field containing javascript variable or function?

I feel like I must be missing something, or I'm just too clueless to search for the right question, so please pardon me (and redirect) if this is a duplicate. My issue is probably much harder than I think it should be.
I have a page with a rather lengthy block of php code (mainly MySQL queries) which generate variables that are eventually passed into JavaScript as strings. The data is then used to create some interactive form elements. The end result is a textarea field which contains a JS string which I'd like to carry into to a new page. I will also be POSTing php variables to that new page.
Sample code:
<?php //Get data from MySQL, define variables, etc.?>
<script> //Move php strings into JavaScript Strings;
//put JS vars into textareas; etc
var foo = document.getElementById('bar').value </script>
<form action="newpage.php" method="post">
<input type="hidden" id="id" name = "name" value="**JAVASCRIPT foo INFO HERE**"/>
<input type = "hidden" id="id2" name = "name2" value = "<?php echo $foo; ?>" />
<input type="submit" name="Submit" value="Submit!" />
Calling JS functions in the right order is a little sticky because they depend on php variables which aren't defined until queries are complete, so I can't do much with an onload function. I'm literate in php. I'm a novice in JavaScript. I'm fairly inept with JQuery and I've never used AJAX. I'd also really rather not use cookies.
It would be great to see an example of what the original and new page code might look like. I know I can receive the php on the new page info via
$foo = $_POST['name2'];
beyond that, I'm lost. Security isn't really a concern, as the form captures information which is in no way sensitive. Help?
If you don't need to use the failure function, you can skip the AJAX method (which is a bit heavier), so I would recommend you make use of the $.post or $.get syntax of jQuery.
Pre-defined syntax: jQuery.post( url [, data ] [, success ] [, dataType ] )
Here is the example for jQuery:
$.post('../controllerMethod', { field1: $("#id").val(), field2 : $("#id2").val()},
function(returnedData){
console.log(returnedData);
});
Otherwise, you could use the AJAX method:
function yourJavaScriptFunction() {
$.ajax({
url: "../controllerMethod", //URL to controller method you are calling.
type: "POST", //Specify if this is a POST or GET method.
dataType: "html",
data: { //Data goes here, make sure the names on the left match the names of the parameters of your method you are calling.
'field1': $("#id").val(), //Use jQuery to get value of 'name', like this.
'field2': $("#id2").val() //Use jQuery to get value of 'name2', like this.
},
success: function (result) {
//Do something here when it succeeds, and there was no redirect.
}
});
}
function init()
{
var str1 = <?php echo varname; ?> //to access the php variable use this code//
document.getElementById('id').value= str1;
}
<body onload="init()">//make sure you call the function init()`
did you try something like this

JS/jQuery passing array/variable/data to PHP in same page?

Im hoping you can point me in the right direction.
I have a php page, that includes some HTML markup and some JS/jQuery routines to build an array of 'user choices' based on the 'user input' (checkboxes..etc).
my question is, how can I pass off this (multidimensional) array to PHP, that is in the same page? (ultimately I want to save this data/array to my PHP session)
While looking around, I read about using another (external) .php script to do,, which is NOT what Im after, I'm hoping to do this to the SAME PAGE I'm in... WITHOUT A REFRESH.
will $.post() do this for me? without a page refresh (if we suppress the event or whatever)...
and -not- using an external .php script?
I understand PHP runs/executes FIRST... then everything else..
I'm not really trying to get PHP to do anything with the data being sent from JS/AJAX.. outside of save it to the SESSION array..
Ajax seems like it will be needed?
To summarize:
1.) PHP and JS are in/on same page (file)
2.) No page refresh
3.) No external PHP script to do 'anything'.
4.) Trying to get (multidimensional) array to PHP session in same page.
5.) I am trying to 'update' the PHP SESSION array each time a user 'clicks' on a checkbox.
I have read a little on using AJAX to post to the same page with the URL var left empty/blank?
edit:
to show the data, I want to pass...heres a snippet of the code.
its an array of objects.. where 1 of the poperties of each object is another array
example:
var somePicks = [];
somePicks.push({casename:caseName, fullname:fullName, trialdate:trialDate, citystate:cityState, plaintiff:plaintiff, itemsordered:itemsOrdered=[{name:itemOrdered, price:itemPrice}]});
when from all the checkboxes.. I update the 'sub-array' (push or splice..etc)
somePicks[i].itemsordered.push({name:itemOrdered, price:itemPrice});
'this' is the array/data I want to get into my PHP session from JS using whatever I can AJAX most likely.
You can sort of do that, but in essence it won't be any different than using an external PHP file. The PHP code gets executed on the server before ever being sent to the browser. You won't be able to update the PHP SESSION array without reconnecting with the server.
If you really want to use post to call the current page (I don't think you can just leave the url blank, but you can provide the current file name), you can just have the PHP handler code at the top of the page. However, this would be the exact same as just putting that handler code in an external file and calling it.
Either way, the page will not refresh and will look exactly the same to the user.
You can use $.ajax function with $(#formid).serializearray (). And use url as ur form action in $.ajax function.
I hope it will work for you
<form id="formId" action="post.php" methor="post">
<input type="checkbox" name="test1" value="testvalue1">TestValue1
<input type="checkbox" name="test2" value="testvalue2">TestValue2
<input type="button" id="buttonSubmit" value="click here" />
</form>
<script>
$("document").ready(function ()
{
$("#buttonSubmit").click(function () }
{
var serializedata=$("#formId").serializeArray();
$.ajax(
{
type:"post",
url:$("#formId").attr("action"),
data:{"data":serializedata},
success:function()
{
alert("yes");
}
});
});
});
</script>
<?php
if(isset($_POST))
{
session_start();
$_SESSION["data"]=$_POST["data"];
}
?>
I suggest to use the .post method of Jquery, to call a PHP file, sending the array and processing in the PHP called.
Can find the jquery documentation about .post() here: http://api.jquery.com/jquery.post/
Edited:
I used this case some time ago:
document.getElementById("promotion_heart_big").onclick = function(e){
$.post("' . URL_SITE . 'admin/querys/front.make_love.php",
{
id_element: ' . $business["promotion"]["id"] . ',
type: \'promotion\',
value: $("#field_heart").val()
},
function(data) {
if (data.result) {
//some long code....
}
}
},
"json"
);
from some preliminary testing..
this does NOT seem to be working, (will do more test tomorrow)
$.ajax({
type : 'POST',
//url : 'sessionSetter.php',
data: {
userPicks : userPicks,
},
success : function(data){
//console.log(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
});
It was mentioned that posting to external .php script -or- posting the same page would produce the same results..
no page refresh
$_SESSION would update for future pages
Does anyone have an y example for that?

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

Categories

Resources