How to call php method in javascript? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I already doing research in here.
Many people say ajax is better.
But I want to ask something first because I never use ajax.
I want to delete some row in database if I push yes on the windows.confirm using javascipt.
My HTML button
<button onclick="deleteFunction()">Del</button>
My Javascript function
<script type="text/javascript">
function deleteColumn(id)
{
if (confirm("Are you want to delete?") === true) {
// Do delete method in PHP
} else {
// Cancel delete
}
}
</script>
My delete method in Storage class
class Storage
{
public function delete($condition)
{
// Delete from database with condition
}
}
Do I must use ajax to call PHP method?

It's important to have two concepts clear, execution in server side and execution in client side.
Server side, like php, the code is interpreted in the web server.
Client side, like javascript, the code is interpreted in the browser of the user.
AJAX is really good to make the two sides work "together" without disturbing the user experience.
Using AJAX in this case isn't a must. AJAX is useful when you want to make an action without reloading all your site. If what you want to do is that, try using some jQuery function, like:
$.ajax({
url: "yourPHPfunction.php",
data: {
row: 123
}
}).done(function() {
alert("The row was deleted.")
});
in your js delete() function.
If you don't want to use AJAX, make a GET or POST request (via js) to the PHP file where you had coded the delete function.
It will be good if you take a look to jQuery API documentation here.
But before, to have a background about AJAX, it's good to read that.

This should give you basic flow:
<!-- the form sample -->
<form method="POST" action="your_php.php" onsubmit="return confirm('Are you want to delete?');">
ID: <input type="text" name="id" /><br/>
<input type="submit" name="submit" />
</form>
In PHP:
<?php
class Storage
{
public function delete($id)
{
// should be better if this is another class
$connection = new mysqli('localhost', 'your_db_username', 'db_password', 'database_name');
$stmt = $connection->prepare('DELETE FROM `table` WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
}
}
if(isset($_POST['submit'])) {
$id = $_POST['id'];
$storage = new Storage();
$storage->delete($id);
}
?>

I would answer with a simple phrase :
Look this video : How PHP Works
You will understand yourself, why what you are asking is not possible without AJAX.
Enjoy the video, and see you :)
I hope this answer will help you to figure out why you cannot do what you want to, without using AJAX or similar ;)

The php code need the php interpreter to run.
The browser cannot find the php interpreter to run your code in the javascript. So you must call a php server to help you.It will run your code and return your result.Using ajax is a better idea!

Related

Fetch json data if json still not created [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This is a sample of my form in php:
echo "<form method='GET' action='queries.php'>
<label>name1</label>
<input type='checkbox' name='name1'/>
<label>name2</label>
<input type='checkbox' name='name2'/>
<label>name3</label>
<input type='checkbox' name='name3'/>
<input type='submit' name='sendData' value='Send'/>
</form>";
I take all the values in $_GET and i want to pass them in json to the frontend
$data = isset($_GET) ? $_GET : 0;
if (count($data)>0) {
$res = $data;
echo json_encode($res);
} else {
$noData -> Message = "No data passed";
echo json_encode($noData);
}
The problem is when i try to fetch with any http request the json generated from the form. I always get the $noData json instead of $res.
I need to use the data generated on a subsequent request. What would you suggest me to use to do that?
You need to store the data somewhere more permanent. Maybe in a file, or a database perhaps.
Or, if you only need the data for this user within their current usage session, then you could store it in the PHP Session. It depends on your exact requirements.
But the important thing to learn from this is that web applications are stateless - and therefore information held in ordinary PHP variables does not persist between different HTTP requests. If you want to keep the information submitted by the user, you need to have code to store it (and then more code to retrieve the correct information on a subsequent request).

How to convert PHP function to become called using Ajax [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Edit: I am not directly trying call a PHP function using Javascript. The application routing will help frontend to hit the correct function.
I think my problem might have a simple solution, but I am not able to figure it out.
I have a bunch of PHP functions that output HTML. Something like:
<?php
function sample1($param1)
{
//make DB query and loop and print HTML
?>
<div class='some-class'>
Some dynamic output here...
</div>
<?php
}
?>
So like I said there are a bunch of such functions. And I want to call them using Ajax so that their values can be returned and I can print them/update DOM using Javascript. I know that I can update all the functions so that the HTML they generate can be stored into a string and then I can each that string. But is there an easier, cleaner solution to this problem?
Because you are not providing me the javascript ajax call i will focus on the php side.
I am using a simple get Ajax call:
$.get( "https://someKindofLink.php?callFunction=Hallo&doctor=who", function( data ) {
alert( data );
});
On the php side we need to check is the function exists and the run it with all variables in $_GET:
if (isset($_GET['callFunction'])) {
if(function_exists($_GET['callFunction'])){
echo $_GET['callFunction']($_GET);
exit;
}
}
function hallo($params)
{
return "Goodbye".$params['doctor'];
}
I would not advise this approach for security reasons but it should get the job done.

How to call php codes inside javascript [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I want to check the inputs of a form if they are empty and then i want to use php codes for user registeration.
<script>
$('#submitbutton').click(function(){
if($('#usernameinput').val() == ''){
alert('Input is blank');
}
else {
//here i want to use php codes for example;
$bgl = new mysqli("localhost", "root", "", "users");
if ($bgl->connect_errno) {
echo "Failed to connect to MySQL: (" . $bgl->connect_errno . ") " . $bgl->connect_error;
}
$username = mysql_real_escape_string($_POST['username']);
.....
.....
..... /and so on..
}
});
</script>
In this case you most likely want to use $.ajax() to call a PHP page that supplies this information.
jQuery.ajax()
There is no such thing as php and javascript working together like that. Javascript in run on client side and php is run on server side. The best you can to is to pass and retrieve values to and from a php page and then use those values as intended.
You have a few options here. The first is to post the form to a PHP page after the JavaScript validations (just use the form action) or use Ajax and call the PHP page, as Robin says.
That's not posible, you can embed javascript into php code but not vice versa.
The best way to implement that is developing a REST service and retrieving data with AJAX.

Using PHP in javascript's IF Statement [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to make a confirm box which will desire which php code will be executed.
Heres my code:
<script type="text/javascript">
var answer = confirm('Are you sure?');
if(answer==true)
{
<?php $confirmation = 1; ?>
}
else
{
<?php define("CONFIRMATION", 1, true); ?>
}
alert('<?php echo $confirmation; ?>')
alert('<?php echo defined("CONFIRMATION"); ?>')
</script>
The problem is , even if i click YES, $confirmation and boolean from defined() function returns 1.
Whatever I click, (cancel or ok) one of them should be 0 (I've already declared $confirmation before)
But both of codes at if and else blocks are used!
Normally it works like this
You fundamentally misunderstand what PHP is doing.
PHP is evaluated on the server before the page is sent to your browser. By the time the browser sees it and executes the javascript, all the PHP is gone.
Use your browser's "view source" on the browser window with this code in it. You'll see it looks like this:
<script type="text/javascript">
var answer = confirm('Are you sure?');
if(answer==true)
{
}
else
{
}
alert('1')
alert('1')
</script>
You either need to implement what you want to do in javascript to run on the browser, or you need to send a new request to the server and get a new page back (either directly or indirectly) with your response.
That will never work because PHP is processed before the output is sent to the browser. If you really need to modify something in PHP then try using an AJAX call.
http://ajaxpatterns.org/XMLHttpRequest_Call
Or try using jQuery's $.ajax(); function. Start by looking here.
Here is a quick example:
<script type="text/javascript">
var answer = confirm('Are you sure?');
$.ajax({
type: 'GET',
url: '/path/to/script.php',
data: 'answer=' + answer,
success: function(response) {
alert(response);
}
});
</script>
Contents of script.php:
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
// ...
}
You can't trigger a PHP code exection without a post/get request.
For your needs, you should choose between a form submisssion or load a page-link with parameters stuffed in the query string on confirmation.
P.S.
the query string parameters are the ones following the "?" in the format variable=value
for example:
index.php?answered=1
you will be then able to retrieve these vatiable/values using PHP $_POST, $_GET or $_REQUEST variables in a way like this:
if ($_REQUEST['answered'] == 1) { //confirmed
...
}
You are misunderstanding the order of what will happen here.
Firstly, PHP will output the javascript layer. Your if block will then look like this:
if (answer == true)
{
}
else
{
}
The javascript engine should then optimise that out and totally ignore it. Consider using AJAX if you need to get PHP to process something with an input from the javascript layer.
Normally it works like this
No, it never works like this. PHP is executed before the javascript so it will never work like this.
I think from what I see you would want something like
Your link
This will go to the current page with $_GET['confirmation'] set to "1".
php executed before javascript so you can't do this because
when you check it via javascript if else statement php is already executed so you can't do it
but however you can use ajax for it

Howto: PHP/Javascript communication

As I'm developing my WebIDE, I keep coming up with questions that I cannot answer myself. This is because the project is supposed to help others create what they would "normally" create, but faster (i.e. as automated as possible). In this light, my question is how to you implement a PHP backend?
Here is what I do. I like to create "functions" that the client JavaScript can call. Usually, I send (via POST and JSON) a variable called "action" which holds the name of the "function" I am calling (as well as any arguments I wish to send it). The PHP code, then, looks something like this:
if(issset($_POST['action'])) {
//function foo(arg1,arg2)
if($_POST['action'] == 'foo') {
$arg1 = $_POST['arg1'];
$arg2 = $_POST['arg2'];
//do stuff
}
}
I can still reference other real functions I create in PHP, but I find that this is a nice way to organize everything and easy to implement in both JavaScript and PHP.
What do you do?
Edit 1: Ok, based on the first two answers to this question, I do not think I am explaining myself well.
I am asking how do you create a PHP back end. The idea is that you have your AJAX client written in JavaScript (or maybe something else, it doesn't matter), and then it will call your backend PHP with POST or GET data. Based on this data, your backend will do what it needs to do (maybe it will simply update the database, and maybe even return information, again: it doesn't matter).
The question now is: how do you tell it what to do? What do you send via POST/GET and how do you interpret it in your backend?
I send all data to the backend in a big GET array.
actionpage.php?action=post&parameters[parameter1]=value1&parameters[parameter2]=value2
If you print_r($_GET), on the PHP side you'll see:
array(
"action" => "create",
"parameters" => array("parameter1"=>"value1","parameter2"=>"value2")
)
What this does is allow you to loop through your parameters. You can say in the pap
if($_GET['action'] == 'create'){
foreach($_GET['parameters'] as $key=>$value){ //something
The question now is: how do you tell
it what to do? What do you send via
POST/GET and how do you interpret it
in your backend?
Choose your own conventions. For example use an "action" value in your JSON data that tells the action, then add more parameters. You can spy on various websites's Ajax messages with Firebug extension in Firefox if you want to see what other websites do.
For example the Json POST data could be:
{
action: "create",
fields: {
firstname: "John",
lastname: "Doe",
age: 32
}
}
To which you could reply with the ID of the newly created record.
To delete the record:
{
action: "delete",
keys: {
id: 4654564
}
}
etc.
In the php ajax handler you could have something as simple as a switch:
$jsonData = Services_Json::decode($_POST['json']);
switch ($jsonData->action)
{
case "save":
if (validate_json_data($jsonData->fields))
{
UsersPeer::create($jsonData->fields);
}
break;
case "delete":
/* etc */
}
// return a json reply with
$jsonReply = new stdClass;
$jsonReply->status = "ok";
$jsonReply->statusMessage = "Record succesfully created";
echo Services_Json::encode($jsonReply);
exit;
Javascript, say prototype Ajax.Request responder function will output the error message in a specially created DIV if "status" is not "ok", etc...
I use a front page controller which handles my routing. If you set up mod-rewrite you can have very clean endpoints where the first segment of your url refers to the controller (class) and then the subsequent segments would refer to the methods inside followed by the parameters being passed to the method.
http://domain.com/class/method/param1/param2
this website will answer all your ajax questions. I found it really helpful.
http://ajaxpatterns.org/XMLHttpRequest_Call
You need to organize functions? It's called 'class'.
/// todo: add error processing
$name=$_GET['action'];
$args=json_decode($_GET['args']); /// or just subarray, doesn't matter
/// 'Action' is constant here but in reality you will need more then one class for this
/// because you will want modules in your framework
if(method_exists('Action',$name))
call_user_func_array(array('Action',$name),$args);
else { /* incorrect parameters processing */ }
/// Ajax-available functions are here
class Action
{
public static function action1()
{
echo 'action1';
}
public static function action2()
{
echo 'action2';
}
}
I do something very similar. What you need is a JSON object to pass back to the javascript. When you are done with your PHP, you can call json_encode to pass an object back to the front end. From there you can do more with it in Javascript or format it however you want.
There is more information on a similar question here:
Best way to transfer an array between PHP and Javascript
Edit: After reading your edit, I think what you are doing is fine. When you send the AJAX request from Javascript include a variable like "action", or whatever youd like. From there you can check what the action is via a case and switch statement.
I usually write the php functions as normal functions.
fn1(arg1, arg2){
//do stuff here
}
fn2(arg3){
//do stuff here
}
I pass the name of the function in a variable called action. Then do this:
foreach($_POST as $key => $value)
$$key = $value;
To assign create variables of the same name as the arguments.
Then use a switch-case to call the appropriate function like so:
switch($action){
case 'fn1':fn1(arg1,arg2);
break;
case 'fn2':fn2(arg3);
break;
}
Is this what you are looking for?
Edit: You could use the PHP SOAP and XML-RPC extension to develop a webservice, where if you specify the function name in the SOAP request, that function will be automatically executed (you don't have to write the switch-case or if). I've used it in Java, but am not sure how exactly it works in PHP.

Categories

Resources