calling a php object method on clicking a button? - php

I've been working on php application and I've used a OO programming so far to develop it . I have declared a class like this
<?php
class User
{
public function Add_element()
{
//adds some element
}
public function Delete_Element($element_ID)
{
//delete the element with that ID
}
}
?>
I've created an object of user class (for example $user = new User()) in my index.php file which includes my view.index.php and the view.index file is organized as follow
<html>
<header></header>
<body>
<input type="button" id="ID" value='Delete Element' >
</body>
<html>
I know this question may seem repetitious but I want to know how can I call the $user->Delete_element($ID) method upon clicking the button .

You could do something along these lines:
First of all use a form:
<form method="POST" action="delete.php">
<input type="hidden" name="element_id" value="id">
<input type="button" name="delete" value="Delete element">
</form>
And create the following php script:
if(isset($_POST['element_id']))
{
$element_id = intval($_POST['element_id']);
$user->deleteElement($element_id);
}
OR use ajax, which is a bit more complicated.
Edit:
If you do not want to refresh the page you should use AJAX. Start off by including jQuery, which makes this a lot easier. Now you need something like this:
$("form").submit(function(e){
var data = {};
data.element_id = $(this).find("[name='element_id']").val();
$.POST("delete.php", data).done(function(response){
alert(response);
});
e.preventDefault();
});

edit your html file (change the "input" tag to an html form):
<form action="Delete_Element.php" method="POST">
<input type="button" name="ID" value='123456789' >
</form>
create a new php page called "Delete_Element.php":
<?php
if ( isset($_POST["ID"]) )
{
/* init the "user" object, assuming it is init to: $myUser */
//this line invokes your method, given the posed IP param. .
$myUser->Delete_Element($_POST["ID"]);
}

Related

jquery: how to open an url in new tab with passing post data to that url

I have a php file localhost/~user/sample.php file which gets data from post method.
<?php
$you = $_POST["ids"];
$start= $_POST["start"];
echo $you."--".$start;
I want to write a jquery code which will open the url "localhost/~user/sample.php" in a separate window on button click inside my html page and also pass the arguments required for it.
I can use get method in php, but the number of variables are more
I would probably go for using a form, like so:
<form action="sample.php" method="post" target="_blank">
<input type="hidden" name="name1" />
<input type="hidden" name="name2" />
...
<input type="hidden" name="name20" />
<input type="submit" value="Go to page">
</form>
This is the most cross-browser JS-failsafe basic html version way of achieving this task that I can think of...
If you need to dynamically add form fields to the form, I believe you will find this question: Jquery - Create hidden form element on the fly handy. Copying the modified answer:
$('<input type="hidden" name="myfieldname" value="myvalue">').appendTo('form');
One way would be to dynamically create a hidden form and then submit it, make sure you encode the input:
var params = [['someKey0', 'someValue0'], ['someKey1', 'someValue1'], ['someKey2', 'someValue2'], ['someKey3', 'someValue3']];
var inputs = $.map(params,function(e,i){
return '<input type="hidden" name="'+e[0]+'" value="'+encodeURIComponent(e[1])+'"/>';
});
var form ='<form action="sample.php" id="hidden-form" method="post" target="_blank">'+inputs.join('')+'</form>';
$('#hidden-div').html(form);
$('#hidden-form').submit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hidden-div"></div>
Try this....
<form id="myForm" action="sample.php" method="post">
<?php
echo '<input type="hidden" name="'.htmlentities($you).'" value="'.htmlentities($start).'">';
?>
</form>
<script type="text/javascript">
document.getElementById('myForm').submit();
</script>
if you send request with javascript to any php page; it sends a request and gets the respose to the page which has sent request and you continue process your data at your first page. So if you want to open your sample.php and also send your post data within; you must send your data with something like php form.
Submitting forms: http://www.w3schools.com/php/php_forms.asp
If you want to use js post, you can do something like below:
teams.php:
data = { teams : ['Real Madrid','Barcelona','etc']};
var response = null;
$.ajax({
url : 'mypostfile.php',
type : 'POST',
data : data
})
.done(function(resp){ response = resp; //it returned from php echo })
.fail(function(){ console.log('fail'); //post process failed. });
mypostfile.php:
if(isset($_POST['teams'])){
$teams = $_POST['teams'];
echo $teams[0]; //response : Real Madrid
}
Hope it helps.

jquery return value by php echo command

I have these codes:
Contents of main.php:
Javascript
function grab()
{
$("#div_id").load("/test.php");
}
HTML & PHP
<? $original_value = 'Original content'; ?>
<div id='div_id'><?=original_value;?></div>
<form action="javascript:grab($('#div_id').val())">
<input name="submit" type="submit" value="submit">
</form>
also test.php
<?...
$update_value = "Update content";
echo $update_value;?>
the result of test.php will be written into #div_id and the result for div content is:
Original content
Update content
But i like to overwrite original div value and the result should be:
Update content
I mean echo append a new line in #div_id, but i like to overwrite existing #div_id content.
Change the following in your code.
Remove the javascript in your action attribute. It doesn't look right.
<form action="">
<input name="submit" type="submit" value="submit">
</form>
Add the following javascript.
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault(); // Prevents the default submit action.
// Otherwise the page is reloaded.
grab();
});
});
The function grab will be called when the form is submitted. I'm not sure if this is what you want, but you should see the new contents in the div.
UPDATE 1:
I have removed the parameter from grab because the function doesn't need one.
You need to replace the content while the current code appends it, change code to:
$("#div_id").empty().load("/test.php");

Submit button clicking changing the value of it to another thing

maybe very easy!
I'm php coder and I don't have experience in js but I must do this for one of my codes
suppose I have sub1 in page after clicking it must be that sub1 but value now is sub2
<html>
<head>
<title>pharmacy</title>
</head>
<body>
<form method="post" action="pharmacy.php">
<?php
//some code
if(array_key_exists('update',$_POST)){
//somecode
}
?>
<input type="submit" name="update" value="<?php echo if(isset($_GET['update'])) ? 'Show' : 'Update' ?> ">
</form>
</body>
</html>
show as function name does not really make sense here (imo), but you could do:
<input type="submit" name="sub" value="sub1" onclick="show(this)">
and
function show(element) {
element.value = 'sub2';
}
Important:
But that will actually not solve your problem. As soon as you click the button, the form is submitted, meaning the browser initiates a new request and will load a new page. So every change you made the current page is lost anyway.
The question is: What are you trying to do?
It seems to me that you should change the value of the button on the server side. You have to keep track which form was submitted (or how often, I don't know what you are trying to do) and set the value of the button accordingly.
Update:
I see several possibilities to solve this:
You could keep using JavaScript and send and get the data via Ajax. As you have no experience with JavaScript, I would say you have to learn more about JavaScript and Ajax first before you can use it.
You could add a GET parameter in your URL with which you can know which label to show for the button. Example:
<form method="post" action="?update=1">
and
<input type="submit" name="sub" value="<?php echo isset($_GET['update']) ? 'Show' : 'Update' ?> ">
Similar to 2, but use a session variable (and not a GET parameter) to keep track of the state.
Update2:
As you are already having $_POST['update'] you don't need the URL parameter. It could just be:
<html>
<head>
<title>pharmacy</title>
</head>
<body>
<form method="post" action="pharmacy.php">
<input type="submit" name="update" value="<?php echo isset($_POST['update']) ? 'Update' : 'Show'; ?> ">
</form>
</body>
</html>
This should do it
function show(){
document.getElementsByName('sub')[0].value = 'sub2';
return false;
}
Edit: if you don't want it to submit the form, just add a return false, but then you'd need to change your onclick from your submit button to your forms onsubmit;
<html>
<head>
<title>test</title>
<script>
function show()
{
document.getElementById("sub").value= "sub2";
return true;
}
</script>
</head>
<body>
<form method="post">
<input type='submit' id="sub" name='sub' value="sub1" onclick="return show()">
</form>
</body>
</html>

Calling a PHP function from an HTML form in the same file

I'm trying to execute a PHP function in the same page after the user enters a text and presses a submit button.
The first I think of is using forms. When the user submits a form, a PHP function will be executed in the same page. The user will not be directed to another page. The processing will be done and displayed in the same page (without reloading).
Here is what I reach to:
In the test.php file:
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
The PHP code [ test() function ] is in the same file also:
<?php
function test() {
echo $_POST["user"]; // Just an example of processing
}
?>
However, I still getting a problem! Does anyone have an idea?
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
test.php
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
You have a big misunderstanding of how the web works.
Basically, things happen this way:
User (well, the browser) requests test.php from your server
On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
The browser displays the form, the user can interact with it.
The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.
You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.
If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/> in a div below the user box.
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])) { // If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
Use SAJAX or switch to JavaScript
Sajax is an open source tool to make
programming websites using the Ajax
framework — also known as
XMLHTTPRequest or remote scripting —
as easy as possible. Sajax makes it
easy to call PHP, Perl or Python
functions from your webpages via
JavaScript without performing a
browser refresh.
That's now how PHP works. test() will execute when the page is loaded, not when the submit button is clicked.
To do this sort of thing, you have to have the onclick attribute do an AJAX call to a PHP file.
in case you don't want to use Ajax , and want your page to reload .
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>
Take a look at this example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
HTML
<form method = 'post' action = '' id = 'theForm'>
...
</form>
JavaScript
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET super global. An example is below.
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
After the PHP script runs, the success function is called, and any and all output produced by the PHP script will be stored in the variable html.
...
success: function(html) {
alert(html);
}
...
This is the better way that I use to create submit without loading in a form.
You can use some CSS to stylise the iframe the way you want.
A php result will be loaded into the iframe.
<form method="post" action="test.php" target="view">
<input type="text" name="anyname" palceholder="Enter your name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<iframe name="view" frameborder="0" style="width:100%">
</iframe>

Any idea how to build a php string manipulation app using forms?

I want to build an string/text manipulation app that:
An app consists of a form
User inputs text there as a string using
Click a button - which usues $_POST method to manipulate a string using oop method to :
Example method assigned to a button:
public function revers_sentence() {
$this->string = strrev($this->string);
return $this;
}
Then the manipulated string is displayed in the same form.
User can do another manipulation with a converted string
How to assign method to a button to trigger the function and display results in the same form?
Can it be achived in a single php file to send and get a result?
(I want to store my classes in a seperate file)
Any help/idea Appreciated - any wise guy?
edit:
<?php
require_once('mod.php');
$string='';
if (isset($_POST['string']))
$string=$_POST['string'];
if (isset($_POST['DoStuff']))
{
//$string = reverse_1_word($string);
**$string->reverse();**<-------------------------------Fatal error:---------
}
if (isset($_POST['DoOtherStuff']))
{
$string = doOtherStuffWithThisString($string);
}
?>
Fatal error: Call to a member function odwroc() on a non-object on line 14 so how to make every new string an object ?
I would do something like that:
<?php
Class MyString{
private $string='';
function __construct(){
if (isset($_POST['string']))
$this->string=$_POST['string'];
}
function doStuffWithThisString(){
$this->string=$this->string.'!';
}
function doOtherStuffWithThisString(){
$this->string=$this->string.'!!!';
}
function getString(){
return $this->string;
}
}
$myString = new MyString();
if (isset($_POST['DoStuff']))
{
$myString->doStuffWithThisString();
}
if (isset($_POST['DoOtherStuff']))
{
$myString->doOtherStuffWithThisString();
}
?>
<form action="" method="post">
<!-- blank action attribute will post form to the current page-->
<input type="text" value="<?=$string->getString()?>" name="string" />
<!-- <?=$string->getString()?> is the same as <?php echo $string->getString(); ?> -->
<input type="submit" value="Do Stuff" name="DoStuff" />
<input type="submit" value="Do Other Stuff" name="DoOtherStuff" />
</form>
You could have a form like this :
<form action="currentFile.php" method="post">
<input type="text" value="myValue" name="text" />
<input type="submit" value="Reverse !" name="reverse" />
<input type="submit" value="Other manipulation" name="otherManip" />
</form>
When you receive the data, you can do this :
if ( isset($_POST['reverse']) ) {
// User clicked on the reverse button
} elseif ( isset($_POST['otherManip']) ) {
// User clicked on the other button
}
to achive the send and get in a single PHP file you have to set the forms action to the actual site you are on. I do this ba writing <form action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" method="post"> FORMFIELDS AND DATA </form>
To work with the returned values you just have to build an if-statement, that checks for the passed values if (isset($_POST['buttonname'])){ //DO SOMETHING}

Categories