How To trigger a php query using a link - javascript

i have a page, in where by i can want to collect and store the amount of page views, i have a php query that stores my page views onclick of a button,
if(isset($_POST['submit'])){
mysql_select_db($database_epl, $epl);
$query_lin = sprintf("SELECT * FROM topic WHERE id = %s ORDER BY `Date` DESC", GetSQLValueString($colname_lin, "int"));
$topicId = $_GET['id']; // you need to change 'id' to the name of your ID-parameter in the URL
$viewsIncrementQuery = "UPDATE `topic` SET `Views` = `Views` + 1 WHERE `id` = " . $topicId;
$incremented = mysql_query($viewsIncrementQuery, $epl) or die(mysql_error());
// run/execute mysql query
but now i want to be able to call that query using links, (on click of a link)
How can i go about this

You can add a onclick event to the link and have it set a form's action attribute and then trigger a submit
html
<form method="post" id="myForm">
<input type="text" name="id" />
<input type="button" name="submit" value="submit">
</form>
Click to submit
Javascript
function submitForm(element){
var action = element.href;
var form = document.getElementById("myForm");
form.action = action;
form.submit();
}
Your data would then be in the $_POST global array, if you want it in the $_GET global then just change the method attribute to get

You need to call this page with an ajax query, like this in JQuery. With this, you'll be able to transmit parameters as GET or POST, and receive them in your page, where you will do your update query.

Pass a parameter with your link:
http://example.com/yourpage.php?send=123
in yourpage.php
var_dump($_GET['send']);
returns
string(3) => 123
EDIT:
in your html output introduce a parameter for your link:
link
in yourpage.php
if($_GET['updateview'] == 1)
{
//your sql query etc. from the question.
}

Related

How to change a HTML table data value after form submission

I have a form.
<form action="form.php" method="POST" name="form1" id="f1">
On this form is an input for a name.
<input type="text" class="form-control" id="n1" placeholder="Name" required>
The user inputs their name and clicks submit, the form.php then kicks in and this name is emailed to an email address.
$name = $_POST['n1'];
If this is successful the user is redirected to another page via;
header("Location: /anotherpage.html");
Up to this point everything works fine.
On this page is a HTML table with a table data cell;
<td id="table1"></td>
Q. What I am trying to do is when the user is redirected to this page the name they submit appears in the tables data cell.
I have tried a couple of things with no success.
On the HTML side;
value="<?php echo $name;?>" & value="<?php echo $_POST['n1'];?>" within the td tag.
<?php echo $name;?> & <?php echo $_POST['n1'];?> between the td tags.
& on the PHP side after the redirect header;
getElementById('n1').value = $name;
getElementById('n1').value = $_POST['n1'];
Is there a way of doing this?
Look forward to hearing from anyone
Kind Regards
You can send the name over the url using the header using PHP...
// check the submission of your form using the name set in the submit button...
if(isset($_POST['submit'])){
// DO NOT SKIP ON SANITIZING YOUR INPUTS!!!!!
// This example is very basic, I am not showing how to sanitize inputs
$fname = filter_var(strip_tags($_POST['fname'], FILTER_SANITIZE_STRING));
$lname = filter_var(strip_tags($_POST['lname'], FILTER_SANITIZE_STRING));
// do your email stuff
// after you have done all your other code, send the name
// key/value pair over the url using the header...
header("Location: someotherpage.html?fname=".fname ."&lname=".lname);
}
Once you have sent the values over the url to the someotherpage.html page you can use URLSearchParams to search the url for key parameters to get their paired value/s. window.location.search => The query string portion of the URL. This includes the question mark, and everything following. Use .get() to get the url's parameters using their key. Then you can assign them using javascript with the dataset attribute => element.dataset.fname = firstName.
let parameters = new URLSearchParams(window.location.search);
let firstName = parameters.get('fname');
let lastName = parameters.get('lname');
let div = document.getElementById('data');
div.dataset.fname = `${firstName} ${lastName}`;
Returns the following on someotherpage.html :

How to populate INPUT fields after submitting when user goes back

I have 2 forms for a shopping cart. When they go back I would like the input fields to be filled with info they originally put in before submitting.
1st uses basic form fields to submit billing and shipping info.
2nd is used for CC info. What I would like to do is in that second form have a BACK BTN that will populate all the fields from the first form with the data they entered.
I have a PHP variable $response with an array returning values, but I don't believe they are all included. It brings back a token from PayPal. I think that might be purposely for security reasons. Perhaps I can store them locally in some JS variables?
I tried the below with no results:
<input name="BILLTOFIRSTNAME" id="billtofirstname_id" value="<?php echo $response['BILLTOFIRSTNAME'];?>"/>
use this in your first page -
session_start();
$data = array("input1"=>"value1","input2"=>"value2");
// store any data in this array
$_SESSION['data'] = $data;
Now if user returns to this page -
if(isset($_SESSION['data'])){
// check if data is available
$value1 = $_SESSION['data']['input1'];
}
else{
$value1 = '';
}
In your input's html add this -
<input name="input1" value="<?php echo $value1?>" />
Here you can use local storage variable
<button onclick="store()" type="button">first form submit</button>
<script type="text/javascript">
function store(){
var billtofirstname_id= document.getElementById("billtofirstname_id");
localStorage.setItem("billtofirstname_id", billtofirstname_id.value);
}
</script>
<button onclick="back()" type="button"> Second form back button</button>
<script type="text/javascript">
function back(){
document.getElementById('Id').value=localStorage.getItem("billtofirstname_id");
}
</script>

How to access parameters that were passed to next page

As part of my requirement i constructed the href link with a variable associated with it as follows
<h5> ', $NAME, '</h5>
Upon click, page is being redirected correctly to single.php and even $ID value can be seen on the browser.
But I dont know how to extract ID parameter in single.php
Can any body please tell me how can i access $ID value in single.php page
<h5> ', $NAME, '</h5>
<?php echo $_REQUEST['id']; ?>
you can use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.
Session:
//On page 1
$_SESSION['varname'] = $var_value;
//On page 2
$var_value = $_SESSION['varname'];
Remember to run the session_start() statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.
Cookie:
//One page 1
$_COOKIE['varname'] = $var_value;
//On page 2
$var_value = $_COOKIE['varname'];
GET and POST
You can either add the variable in the link to the next page:
Page2
This will create a GET variable, or include a hidden field in a form that submits to page two:
<form method="get" action="page2.php">
<input type="hidden" name="varname" value="var_value">
<input type="submit">
</form>
And then on page two
//Using GET
$var_value = $_GET['varname'];
//Using POST
$var_value = $_POST['varname'];
//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];
Just change the method for the form to post if you want to do it via post. Both are equally insecure, although GET is easier to hack.
Supposing the $ID is set to 2, your URL is:
http://working.artefacts.co.in/single.php?2
So, in your single.php page you have to write:
$id = $_SERVER['QUERY_STRING'];
', $NAME, '
PHP $_GET can also be used to collect form data after submitting an HTML form with method="get".
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with parameters:
Test $GET
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET.

Automatically submit a form

I am trying to get a form to submit automatically, which feeds a username and password to another form.
If I remove the javascript and just have the form display on the screen, and manually click the Submit button, the result is I get automatically logged in on the resulting page. This is the result I want.
If I leave the javascript in place, it actually doesn't automatically log me in but it does pass across the username and password pre-filled on the resulting page, then I have to click Submit on the resulting page.
How can I make it automatically submit the form to work the same way as a user actually hitting the submit button? Also I understand that this may not be the most secure way to pass a username and password across, but this is for a special use case.
Note: MyForm is a php page, and I am submitting to an aspx page.
Here is code of what my form would look like:
<form id='myForm' method='post' action='https://blah.com/Login.aspx'>";
<p>Username: <input value='usernameHere' name='Username' type='text' id='Username' data-index='0' maxlength='255' placeholder='Username' class='loginUsername' />";
<p>Password: <input value='passwordHere' name='Password' type='password' id='Password' placeholder='Password' />";
<p><input type='submit' name='btnSignIn' value='Sign In' id='btnSignIn' />
</form>
<script type="text/javascript">
document.getElementById('myForm').submit();
</script>
Thank you.
I suspect there are other issues at play, as using JS to submit the form should replicate a native browser submit.
You can try simulating clicking the 'submit' button via JavaScript:
JavaScript:
document.getElementById('btnSignIn').click();
jQuery:
$('#btnSignIn').click();
You can use onload method for javascript
function submitForm() {
// **NOTE** set form values first
document.getElementById('myForm').submit();
}
window.onload = submitForm;
Or with jQuery if you want:
$(function(){
submitForm();
});
or with tag attribute
he typical options is using the onload event:
<body onload="javascript:submitForm()">
.
.
As the problem is supposed "post a form through php" . It may be achived by using PHP€™s functions fsockopen() and fputs() to send properly formatted data to a remote server. Here is a sample of code :
<?php
//create array of data to be posted
$post_data['Username'] = 'XYZ';
$post_data['Password'] = '********';
$post_data['btnSignIn']="Sign In";
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
//we also need to add a question mark at the beginning of the string
$post_string = '?' . $post_string;
//we are going to need the length of the data string
$data_length = strlen($post_string);
//let's open the connection
$connection = fsockopen('https://blah.com', 80);
//sending the data
fputs($connection, "POST /Login.aspx HTTP/1.1\r\n");
fputs($connection, "Host: https://blah.com \r\n");
fputs($connection,
"Content-Type: application/x-www-form-urlencoded\r\n");
fputs($connection, "Content-Length: $data_length\r\n");
fputs($connection, "Connection: close\r\n\r\n");
fputs($connection, $post_string);
//closing the connection
fclose($connection);
?>
The above codes do post your form now to get redirect to that page , use simply
header('location :https://blah.com/Login.aspx ');

store dynamically created elements' value to database PHP MySql

newbie here.. I have a form where a user can click a button to add an input text element. I did this using JQuery.
What I want to accomplish is to save the values of the dynamically added textboxes to the database.
I have the following code below but storing to database is not working as it should be.
HTML Code:
<form id='myform' action='save.php' method='POST'>
<input type='button' value='Add Another User' id='auser'>
<input type='text' id='user' name='user'>
<input type='submit' value='Save User/s' name='submit'>
</form>
JQUERY code:
$('#auser').on('click', function() {
$('#myform').append("<input type='text' id='user' name='user'>");
});
PHP Code(success.php):
<?php
if (isset($_POST['submit'])){
$username = $_POST['user'];
$qry=$con->prepare('INSERT INTO userslist (username) VALUES (?)')
$qry->execute(array($username));
}
?>
thanks in advance for any help..
Aside from the typos mentioned in the comments above, you'll need to create a grouping name in your HTML form inputs on the user field. So you'll need to change it into:
<input type='text' class='user' name='user[]'>
// ^
Sidenote: I'd suggest just use a class instead.
After that, so you'll also change the JS that spawns multiple textbox fields:
$('#auser').on('click', function() {
$("<input typ='text' id='class' name='user[]'><br/>").insertBefore('.user').last();
// ^ need to add those too
});
After that, when you submit the page (the PHP), you'd get an array instead of one value:
$usernames = $_POST['user']; // this is now an array of usernames
Then in your query, now that its dynamic, you'll need to create the query dynamically too using those PDO placeholders. In the end you'll need these:
if(isset($_POST['submit'])) {
$usernames = $_POST['user'];
$query = 'INSERT INTO userslist (username) VALUES '; // base query
// dynamically build placeholders
$placeholders = implode(',', array_fill(0, count($usernames), '(?)'));
$final_query = $query . $placeholders;
// the final query would look like
// INSERT INTO userslist (username) VALUES (?),(?),(?)
$qry = $con->prepare($final_query); // prepare
$qry->execute($usernames); // bind the user names
}
Sample Demo
Change to this:
$('#auser').on('click', function() {
$('#myform').append("<input type='text' class='user' name='user'>");
}); //-------------------------------------^^^^^^^---change the attribute to class
What happens with ids is when browser finds an element with id then it does not look for next element in the page.
So to overcome this issue you should either use unique ids for every element or just change the attribute to class as suggested in the answer.

Categories

Resources