How to use Post method without a Form - php

I am that kind that spends more time looking for bugs in web projects and correct them, but I still have one question about the use of the GET and POST method
To summarize , I often use the GET method for queries that may be coming from links or simple buttons example :
Click me
and for forms (signup,login, or comment) I use the post method. but the question is:
sometimes (Multi-steps signup for e.g), I may need to pass the info collected from the form in page 1 to a page 2 (where the user can find a captcha for e.g). in order to send them to the database if the captcha test is Okey. But the question is , how to pass those info to a next page via a POST method without using a hidden form?
Do I need to recreate a POST method from scratch with a socket?
thank you

You can use JavaScript (jQuery):
First u need to load jQuery ( using google as host or you download it):
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
Then...
<script type="text/javascript">
$(document).ready(function() {
$('#Link').click(function() {
$.post("example.php", { n: "203000"} );
});
});
</script>
<a id="Link" href="#">Click me</a>
Edit:
after that save it in the SESSION in example.php
$ _SESSION['N'] = (int) $_POST['n'];
When this value will be stored on the server side. And tied to the client session, until he closes browser or that it set the time for that session on the server side runs out.
Edit2:
There is also another possibility to post requst, yes ..
But I do not like this method myself ...
And here is the form used, something the OP did not want.
<form name="myform" action="example.php" method="POST">
<input type="hidden" name="n" value="203000">
<a id="Link" onclick="document.myform.submit()" href="#">Click me</a>
</form>

Use sessions to store the data until you submit them:
http://de.php.net/manual/en/intro.session.php.
Using sessions has a big advantage,
once you have verified the data you can store it.
Always keep in mind that users may manipulate POST requests!

If the problem is to pass info between pages like in a multi-step form you should use session (if you are using PHP).
By the way for send a POST request without form you need to use CURL like in this example

The statement is a HTML language statement used by a browser to initiate a POST/GET data relation. The Browser is the execution environment.
You can use other languages (and their execution environment) like Java, Java Script, C#, etc. to initiate HTTP POST/GET data relations.

Sorry if I'm not understanding you correctly, but from what I'm reading, you want to access form data entered on page 1 (using a form with a post method) on page 2? If so, use the $_POST autoglobal array. For example, $nameOnPage2 = $_POST['nameFromPage1']. You don't have to create a form on the second page for this.

Related

Is it because $_GET is global or the form submitting to itself or else?

I am trying to understand one simple thing in PHP form handling.I am new to it and I have a sample code:
<form name="frm" method="post" action="">
Item Name:<input type="text" name="itmName" id="itmName"/><br/><br/>
<input type="submit" name="sbmit" value="Add Record"/>
</form>
<?php
if(isset($_GET['m']))
{
echo '<script type="text/javascript">alert("'.$_GET['m'].'");</script>';
}
if(isset($_POST['sbmit']))
{
header("location:1.php?m=10");
}
?>
Irrespective of what data I send to the server, my focus is on the if(isset($_GET['m'])) part of the code. Everytime I submit the form, the 'if' is always evaluated to true and as a result the alert box appears.Is it because $_GET is holding the previous value set by header("location:1.php?m=10"); or is it because the form is submitting to itself or else?Googling didn't provide much help. I need better understanding over this.With Thanks
Since you are not specifying an action, it is going to get defaulted to the current pages url, in this case "1.php?m=10" (if that is what it was as you say). Even though the form is getting submitted via POST, the query string is still passed and still accessible.
To prevent it from being set, all you need to do is specific your form action
1°) when you submit your form, the post method send "itmName" and "sbmit" to the same page (because you didn't write anything in "action=").
2°) if the page received the post var 'sbmit', and i does, you ask to the server to redirect the page to the same page (i guess) with a get variable (m=10)
3°) you ordered your page to send an alert if it recieves something in the 'm' get variable.
So in only one shot, your sever does thoses 3 steps. That's why every time the alert is sent.
You are right, the form is client side.
When the submit button is cliked, the post datas are send to the server. Now in server side, the first thing the server see is "if(isset($_POST['sbmit']))" which orders a redirection but in php not in javascript, so we stay server side with the load of a new page that first need to be interpreted by the server because it contains a get variable.
This Get variable is detected by the server and automatically is turning "if(isset($_GET['m']))" on true. Now it writes the javascript tag that will be interpreted client side with the launch of the alert.

Use the form values in the php without submitting and without sending query string to other page

All the above code I saved in a page called dum.php
$(document).ready(function(){
$(".sameclass").click(function (e) {
e.preventDefault();
var QS = $(this).attr('href').split('?');
if(QS.length>0){
var val = QS[1].split('=');
if(val.length>0){
$("#edit_prdct").hide().slideDown('slow');
//Below am adding a value to the hidden text filed
document.getElementById('prd_id').value=val[1];
}
}
});
});
I had some products which i want to edit their info EDIT are the hyperlinks with the query string value
<DIV id="list_prdct">
<a href="dum.php?id=1" class=sameclass>EDIT</A><BR><DIV id="edit_prdct">
<a href="dum.php?id=2" class=sameclass>EDIT</A><BR><DIV id="edit_prdct">
<a href="dum.php?id=3" class=sameclass>EDIT</A><BR><DIV id="edit_prdct">
<a href="dum.php?id=4" class=sameclass>EDIT</A><BR><DIV id="edit_prdct">
</DIV>
In the below div I used a hidden field and I want to used its values in the mysql query in the where condition and I will display a form related to that value
<DIV id="edit_prdct">
<?PHP
$prdid"<input type=hidden id='prd_id' value=''>";
// Here I want to use that value of the hidden field as the condition in the mysql query
?>
I am not sure if I got your question correctly, however, this is my try.
Every system has 3 parts: input, processing and output.
Here, your PHP logic is the processing part. It runs on the server and understands only Php. It doesnot know about your HTML, CSS, JavaScript, etc.
Input is provided through HTML and Javascript(JQuery) using a web browser. When you click a link, or submit a form, or make an Ajax call, then browser basically sends an input to the web server (its called a HTTP Request)
Output is again HTML, CSS and Javascript. The statements you echo or print including the ones outside <?php ?> tag, are all output. These are understood by a web browser and not by the server.
To send any data from client side (the web browser) to the server, you need to use HTTP requests. This can be done in 3 ways:
Synchronous Request(href redirects, form submission, sync. Ajax calls, etc)
Asynchronous Request (Ajax Calls).
URL redirections (its a form of way 1 above!!)
All the ways above typically use either the GET method (query strings) or the POST method.
If you dont want to use Ajax or form submission, you are left with only third option, that is, call the resource links directly. For example, redirecting the user to some URL like:
http://www.example.com/products/134
where 134 is a prod_id.
Then on the server side, you will have to retrieve the URL and extract out prod_id from it. This is a tedious task. Fortunately we have some good frameworks to do that, like CodeIgniter, etc. But this is not the way to send data to the server in case you need to fetch data for a list of prod_id.
So, No, there is no other way to get data from server. Perhaps you need to remodel your problem and understand that Php server can't know about your prod_id magically, you need to send it through one of the methods of HTTP request

onClick add to database

I have the below code, and I'm not sure if it even works. Basically, I want to do a like system, whereby when I click on the link, it adds a +1 to the user's likes.
I've tried so hard to read up but I just don't get anything, and I found a code similar below.
When I clicked on the link, it does process my insert.php page, but I don't know how to get the variable values...
What should I do? I'm not sure if the code structure below is correct...
Thanks!
<script>
function insertSalary()
{
var salary = $("#salary").val();
$.post('insert.php', {salary: salary}, function(data)
{
$("#current-salary").html(data);
});
}
</script>
<div id="current-salary">
<a id="salary" onClick="insertSalary();">+1</a>
</div>
The variable will be in your php script as $_POST['salary']
The value of salary is passed as part of the post method in jquery.
So you can do:
$.post('script.php', {salary: 100}, function(data){...});
and this will pass the value 100 to your php script as the salary value.
In php the $_POST and $_GET hashes contain the data that you pass with a given request. In jquery $.post, $.get $.ajax create requests and take data hashes to build the data you want to pass with the request.
While this may work, I would recommend separating your logic from your website by putting the javascript in an external file and then link your HTML page to it.
I would also advise against declarative event binding which you have done by specifying onClick="insertSalary()".
jQuery provides a method to pro-grammatically assign functions to events using the on method. So for your code, you could use:
$('#current-salary').on('click', insertSalary());

Using hidden "form" to pass variables

Just learning about passing variables from page to page in php, and trying to find the best way to do so for me, as I have to pass ~10 variables between 5 pages. On the first page, does it make sense to have a form:
<form method="post">
<input type="hidden" name="test" value="<?php $test ?>" />
</form>
Then on the next page could I receive this variable using POST? I would not like to have an ACTUAL form, just use it as a storage area for my variables. Also, what do I use for action= if the second page is called second.php.
Any help is appreciated, thanks
Short Answer: Forms only work when submitted. You probably want to use sessions.
Longer Answer:
It does not make sense to have a form without user input. That's what it exists for.
the action= attribute on a form reflects where the form would be submitted. If the processing page is second.php then the action= attribute should point there.
Sessions are not the only possibility. PHP can also set cookies, and if the server doesn't care about the data (only being used as a medium), you can use HTML5's localStorage.
Really, if you need to be passing 10 variables through all five pages, you're probably better off using sessions. You can store all of them as part of the $_SESSION variable and access them from any page as long as the session is kept alive.
You can't use $_POST variables to store data in a user's session.
You should use:
Sessions
Cookies
HTML5 storage
It depends on what you want to do, you have various options:
1. Using a form and post as you outlined. In this case, on page 1 your action="second.php"
2. Passing the data via URL using GET
3. Sessions, as stated by the previous two posts
4. Cookies
If I understand your question correctly you could try the following to POST your values without having the form appear on the page or actually be on the page at all. You need to have the jQuery library referenced in order to use this code.
function hiddenPost(param1) {
$('<form />')
.hide()
.attr({ method: "post" })
.attr({ action: "http://my-URL-here.com/SomePage.php" })
.append($('<input />')
.attr("type", "hidden")
.attr({ "name": "post_data" })
.val(param1)
)
.append('<input type="submit" />')
.appendTo($("body"))
.submit();
}
You can retrieve the POST values on the page you POST to in the same manner as if it was a regular POST with a form tag.
For PHP:
var postData = $_POST["post_data"];
Hope that helps.

AJAX and JS for LIKE Button

I'm trying to learn how make an AJAX script
for a LIKE button, on my website. I have the following questions:
if i'm sending 1 variable.... id.. I do this
data: "action=vote_up&id="+(this).attr("id")",
is this syntactically correct if i'm sending two variables id and id1 ?
data: "action=vote_up&id="+(this).attr("id")&id1="+(this).attr("id1")",
2) What goes into the href attribute? The php page or the AJAX?
<img scr="like.png">
3) which is run first.. The php page or the AJAX.
4) Is it mandatory for me to use jQuery or Pure Javascript for running AJAX
thanks for your time and patience. I most appreciate it.
1) Yes, you could simple undestand it as a PHP-Get request to a script, so multiple vars are possible, like Adam mentioned.
2) For backwards compatibility you should just link to a PHP/whatever-Script that provides the same functionality but doesn't rely on javascript (Not everyone has js enabled). In your javascript you just disable the defult click actione ( see: http://api.jquery.com/event.preventDefault/ ) otherwise it you only want to allow the like funktionality if js is enabled than you could just link to the page anchor '#'.
3) The page runs first. It is progressed by the server and than sent to your browser. In the browser the recieved javascript will start its action.
4) Everything you are using in jquery is based on simple javascript functions, but jquery is much more comfortable ;) The equivalent to the ajax method of jquery is XMLHttpRequest ( http://www.w3schools.com/xml/xml_http.asp )
Here is a idea, hope it helps.
If handle_vote.php is the URL responsible for the handle the up vote, you must do two things:
the a href is the URL with the query string for the up vote, your data, is this case. It must be generated for you server application. It will be used in case of no javascript.
you should put you event to handle the up vote in the a onclick event, to send the ajax request, and use the preventDefault jQuery function to avoid the default event. In this case, a href will never be used, the js will suppress the link click.
A code sample will be almost like this, in you php page:
<a class="like" href="handle_vote.php?action=vote_up&id=<?php echo $post_id; ?>"><img src="like.png"></a>
And it as your jQuery script:
$(function() {
$('a.like').on('click', function(e) {
e.preventDefault();
$.get($(this).attr("href"));
});
});
You can personalize as you like, it is only the idea of how to do it.
<img scr="like.png"> put onclick event on that link, and make AJAX request` to increment count, on success response update count clicks on button. And you forgot about one thing, you should save the state of that button. Because one user can go to your site and click 1000 times on it.

Categories