I need to get the value of a post variable from a form and transform this to a PHP variable to use it on the same page without reloading it
Actually I got this :
$(function() {
$("#submit_post").click(function() {
var select = $("select").val();
$.post("process.php",{select:select},function(result){
$('#result').append(result);
});
});
})
And
<form method="post">
<select name="select" id="select">
<option value="1">Test</option>
</select>
<input type="submit" id="submit_post" value="Envoyer" onclick="return false;"/>
</form>
<div id="result"></div>
When I do :
<?php var_dump($_POST["select"]); ?>
I got : null
But on div result I got : 1
...
I need to lake this "1" a php variable
Your code runs fine on my server. Maybe you aren't totally clear on the function of the superglobals.
If the "result" div contains "1" after you press the button, then that means process.php is correctly receiving your POST request and echoing back the value of $_POST["select"]. You will get "NULL" if you try to just navigate your browser to process.php, because when you do so you are making a separate request which doesn't contain any POST variables. The superglobal arrays don't persist between different calls to process.php unless you create that functionality using $_SESSION, a DB, or some kind of text/json/xml storage system. The following changes to your PHP will allow you to click your button and then separately navigate to process.php and see your data:
<?php
session_start();
if ($_POST["select"]) {
$_SESSION["data"] = ($_POST["select"]);
}
var_dump($_SESSION);
?>
Please correct me if I have made the wrong assumptions and this is not helpful.
-Ben
Related
I am building a management system in which the admin can select an item from the database table and update the details. To achieve this I have two forms on two pages. The first form is to select the item from table and pass it's ID to the second page where I will use the ID to fetch the details from the table using php. I want to do this with javascript so it will not refresh the page. My question is how to pass this value? I am using the following code, but it is not working.
HTML
<div id="result"></div>
<form action="update_item.php" id="update" method="post" >
<select name="selected" class="form-control" id="myItem" required>
<option>Select item</option>
<?php
<!-- PHP script to select the item -->
?>
</select>
<button id="submit">Select</button>
</form>
JAVASCRIPT
$(document).ready(function() {
$("#submit").click(function() {
var chat = $('#myItem').val();
if(chat=='')
{
alert("Please select an item!");
}
else{
$.ajax({
type: "POST",
url:"update_item.php",
data:{
data:chat,
},
success: function (msg) {
//alert(msg):
$('#result').html(msg);
},
error: function(){
alert('error');
}
});
}
});
});
PHP
Second page
$item_id = $_POST['data'];
$get_item = "select * from items where item_id='$item_id'";
<--PHP script continues-->
You can add a hidden field and send this input back to your server:
<input type="hidden" name="something" value="<?= $_SERVER['id'] ?>" />
And then access it with via:
$_SERVER['id']
If you are not changing the page between forms you should be able to just create a variable on the client side that stores the necessary data. Since the second form is loading into the same environment, any variables you have from the first form will still exist.
From your example, I'm guessing chat is the data you're trying to use in the second form. Right now it is local to the click function (once that function completes the variable disappears). You could either move the declaration of that variable into the global scope (outside of document.ready), or use it as intended inside the success callback. (From your example it is unclear what you are trying to do with this data)
I have the following HTML code:
<html>
<!-- assume jquery is loaded -->
<body>
<form id="sform" method="get" style="display:none;">
<input type="hidden" name="eid" />
<input type="hidden" name="returnURL" />
<input type="hidden" name="returnID" value="ieid" />
<select id="dropdownlist" name="ieid">
<option selected="selected"></option>
</select>
</form>
</body>
</html>
What happens is the user enters an email address, it checks (server-side with PHP) the credentials and if valid, returns the following JSON object (in this case, assume that the values are valid urls (ie. http://sitehere.com/somethingelse):
{
"get_action" : "geturl",
"eid" : "eidurl",
"return_url" : "returnurl",
"option_url" : "optionurl"
}
This is retrieved when the user hits the login button on the home page. This button triggers a POST request which retrieves the results and parses the JSON into the form above. I then change the values of the form from the original code and the action of the form itself before submitting the form. This is shown below.
$.post('/?c=controller&a=method', {'email' : $('input[name="email"]').val() }, function(data){
var result = $.parseJSON(data);
$('#sform').change_action(result.get_action);
$('input[name="eid"]').change_val(result.eid);
$('input[name="returnURL"]').change_val(result.return_url);
$('select[name="ieid"]').find('option:selected').change_val(result.option_url);
$('#sform').submit();
};
Where change_val() and change_action() are defined like this:
$.fn.change_val = function(v){
return $(this).val(v).trigger("change");
}
$.fn.change_action = function(v){
return $(this).attr('action', v).trigger("change");
}
The reason why I defined these functions was because originally, I had just been calling val('new value'); and the form seemed to not be updating at all. I read that I had to trigger a change when using jQuery to update the form before submitting it.
However, even after triggering a change, it seems like the HTML still isn't updated (at least in Chrome) and the form is not being submitted correctly because none of the values are actually changing.
So, I need to be able to take a parsed result, update the values in the form (with specific id's), and then submit the form so that it re-directs somewhere. Is there a way to do this correctly?
I currently have a simple php/html page with only one form, where the user inputs a number, then the page loads itself (but this time with parameters).
Some key codelines :
<form action="index.php" method="get">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
if (!isset ($_GET["name"])) {
echo "<div> Adding some content related to the input </div>";
}
?>
Now i'm looking forward adding 3 more fields, and split my page for each form.
The user should be free to use the 4 forms separately, I don't want to have the page reload every time. I'm unsure how to design this page - should i rework my page and work with JS ?
I have basic knowledge with PHP, a little with JS. I will be able to google up most things i need but first i need a proper direction :) thanks !
you can use AJAX for this purpose...
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
AJAX is a must if you don't want the page to reload between each interaction.
If you have trouble with it and want to opt for just PHP (with page reloads) you can handle multiple forms on one page easily enough - my preferred method is to set a hidden value in the form called 'action' settings its value & reading this in again when the page loads for example:
<?php if(isset($_POST['action']))
{
$action = $_POST['action'];
switch ($action)
{
case 'hello':
echo 'hello';
break;
case 'bye':
echo 'bye';
break;
}
}
?>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="hello"/>
<input type="submit" value="hello"/>
</form>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="bye"/>
<input type="submit" value="bye"/>
</form>
You could then save and echo out the values for each form each time keeping them updated as the user interacts with each of the forms.
AJAX is the nicer solution however
If you do not want to reload the page every time you submit each form then you should use Ajax for calling your api. You write the separate api in PHP, and then call that api in Jquery's Ajax.
Here the page won't be reloaded. Also you can call the ajax on each of the button click.
I want to make my alert value as a variable in php. This is my code
<html>
<body>
<form action="" method="post">
<select name="kat" id="kat" >
<option></option>
<option>UNANG TAE</option>
<option>PANGALAWANG TAE</option>
</select>
<input type="text" value="" name="baliw">
</form>
<script src="js/jquery.js"></script>
<script>
$('#kat').on('change', function () {
<?php
/*
mysql_connect('localhost','root','');
mysql_select_db('perens');
mysql_query(" INSERT INTO table (sample) VALUES ('".$alert_value."') ");
*/
?>
alert(this.value);
});
</script>
</body>
</html>
There's a comment inside my PHP where I want to make the alert value as a variable but I don't know how.
JavaScript runs on the client side, after the PHP code is executed on the server side. So you cannot work with the JavaScript variables in PHP. However, you can make an Ajax call to a PHP file, posting the JavaScript values. These values can then be stored in a database by the PHP script.
Using jQuery, you can easy send Ajax requests:
http://api.jquery.com/jquery.ajax/
You can then access these values using PHP $_POST and $_GET.
http://api.jquery.com/jquery.ajax/
Take a look at this to use ajax to send javascript variables to php.
You can't do that directly.
The javascript event listener that raises the alert message is executed by the web browser (client side) and the php is executed in the server side before than page is loaded by the web browser (server side).
What you can do is to send the alert message to a PHP script using an AJAX request.
Example:
$('#kat').on('change', function() {
$.ajax({
url: "myscript.php",
type: "post",
data: {
message: this.value
}
});
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Type whatever you want here:
<input type="text" id="kat" />
Now you can capture the messages from a php script like the following one:
<?php
// myscript.php
$alert_message = $_POST['message'];
// !!! Importat, sanitize the input in order to avoid a classic
// SQLInjection
// $alert_message = mySanitizationFunction($_POST['message']);
mysql_connect('localhost','root','');
mysql_select_db('perens');
mysql_query(" INSERT INTO table (sample) VALUES ('".$alert_value."') ");
?>
Remember that it is important to sanitize the input in order to avoid a SQL Injection, I recommend you to use a database abstration layer like PDO or an ORM that can facilitate the input sanitization.
I declare a variable at the beginning of my .js file:
var option="blabla";
On page 1.html I click on a link to page 2.html where I have
<script>document.write(option);</script>
No text is displayed on 2.html. When I refresh the browser while I am on 2.html I get undefined as an output.
What do I have to do to have the text displayed straight after I click the link?
Alternatively, how can I get the following code work to output strUrl on 2.html:
on 1.html I have a link:
<a href="2.html" onclick="function1("item")">
on 2.html I have a div:
<div id="display">document.write(strUrl);</div>
then I have in my .js file:
function1(searchitem)
{
strUrl = 'http://blabla.com/'
+ '?key=' + searchitem;
}
You try to create a Javascript variable on a page and then use it on another page. This is a more-or-less broad problem, since you want to maintain values across pages. First of all, you need to decide where is this value going to be defined and where is it going to be used. If this is more like a server-side variable, then you need to define it on server-side and then generate it into your Javascript code. If you are using PHP, then you can do it like this:
<script type="text/javascript>
var foo = '<?php echo $bar; ?>';
</script>
Naturally, you need to initialize $bar to be able to do that. If the variable should be a client-side variable, then you need to use localStorage, like this on 1.html:
localStorage.setItem("option", "blablabla");
and then load it on 2.html:
localStorage.getItem("option");
Or, if you need to use it both on server-side and client-side, then you can use a cookie for this purpose. Using cookies i slightly more complex, but my answer to another question should get you going.
Let's focus on the cause this did not work for you. A Javascript variable will cease to exist when the page is unloaded, so you will not be able to use its value after that. So, you need to persist it somehow, storing it either on the server or the computer where the browser is being run.
As a side-note, I should mention that you can use Javascript variables accross pages if you load some pages inside iframes of a page, but that is a different scenario.
This is what FORMS and AJAX were invented for. If your server has a PHP processor (virtually ALL of them do), then you can rename your .html files to .php and use a bit of PHP to accomplish your goal.
A web page ending with .PHP works exactly the same as one ending in .html, except that you can now add snippets of PHP code where desired. It is not necessary to have any PHP code, but if you have some it can do stuff.
Method One: FORMs
If you want to switch to page2.html and see a value sent from page1.html, you can use a FORM construct and post the data from page1 to page2:
page1.php
<form action="2.html" method="post">
<input name="option" type="text" />
<input type="submit" name="sub" value="Go" />
</form>
page2.php
<?php
$p1 = $_POST['option'];
?>
<div>On page1 of this website, you typed: <?php echo $p1; ?>. That's what you did.</div>
Note how a <form> uses the name= attribute for the name of the variable that is sent to the other side.
Example Two: The AJAX method
HTML:
<div id=nonForm">
<input id="option" type="text" />
<input type="button" id="myButt" value="Go" />
</div>
<div id="results"></div>
jQuery:
$('#myButt').click(function(){
var opt = $('#option').val();
$.ajax({
type: 'post',
url: 'page2.php',
data: 'option='+opt,
success: function(john){
if (d.length) alert(john); //display result from Page2 in a pop-up box
$('#results').html(john); //Or, display it right on the page
}
});
});
PAGE2.PHP -- The AJAX processor file
<?php
$opt = $_POST['option'];
//Now, you can do something with the data in $opt, and then send back a result
$rtn = 'Hey, you sent: ' .$opt;
echo $rtn;
The primary (and most important) difference between the two methods is that the FORM will change pages on you. The user will be sent from Page1 to Page2, and the screen will flash as this happens.
What's exciting about AJAX is it sends data to Page2, where Page2 can do something with it (for example, a database lookup), and then Page2 sends different data back to Page1. This new data can then be displayed on the page WITHOUT the page refreshing.
Here are a couple of very basic AJAX examples, to get you going:
AJAX request callback using jQuery