How do I call a controller from jquery? - javascript

I'm trying to call a controller (I'm using codeigniter) from my js script (using jquery) and it's been harder than I expected.
The controller function is meant to delete some item from the database. To do this I just call the function using jquery's post or get (I tried both).
Since I'm using codeigniter I figured the easiest way to do this is to pass the arguments through the URL and then get them in the controller ($this->uri->segment(NUMBER);)
So my get request would look something like this:
$.get('my_function/'+item_id);
my_function is in the same controller I'm calling it from, so there are no problem with the URL (I clarify this because at first I wrote the whole /index.php/my_controller/my_function and threw an error)
Like I said, my_function is meant to delete an item but it wasn't doing so, therefore I decided to check whether my script was calling my_function by writing this at the very beginning of the function:
echo 'hello';exit;
But the 'hello' never appears, which only means that is not calling the function.
I remember many years ago I made this jquery/codeigniter combination work, so there's something I'm doing wrong here and I have no idea what it is.
Thanks in advance for the help.
MODIFIED:
More information: I trigger the $.get() method when the user clicks on a certain kind of class
$('.my_class').click(function(){
$.get('my_function');
});

You should use:
var url = "<?php echo base_url('name_of_controller/my_function/'); ?>"+item_id;
$.get(url);
(this works if you removed the 'index.php' from .htaccess). You can check with firebug the URL called and check if it's the one you desired, but I always made that way to work either with $.get() & $.post().
UPDATE
Try this, is a simple example that should work, if doesn't work, share the .htaccess file and the output of this:
JS:
<script type='text/javascript'>
$(document).ready(function(){
var url = "<?php echo base_url('test/hello_function'); ?>";
$('.class').click(function(e){
e.preventDefault();
$.get(url,function(data){
alert(data);
});
});
});
</script>
CI:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed: login');
class Test extends CI_Controller {
function __construct(){
parent::__construct();
}
function hello_function(){
echo "HELLO!!!";
}
}

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

Wordpress get post id with a php file

I have been stuck on this for weeks. I have an HTML slide presentation using Reveal.js. I want to run a php script on the very last slide.
This is an HTML button on the last slide within a Wordpress post:
<button onclick="myFunction()">Open php file</button>
<script>
function myFunction() {
window.open("../../testing/test.php", "_self");
}
</script>
This is the code inside the test.php file that I am trying to run but it returns null:
define('WP_USE_THEMES', false);
require_once('../wp-load.php');
echo "Post ID: ".get_the_ID(); // Returns nulls but I want this to return 86.
The post id is 86. I can hard code it into the html (if I have to) but I don't want to hard code it into the php file. Also, I would prefer not to use jquery. How can I get the post id into the php file? Thanks.
Have you tried using global $post variable??
global $post;
And after that, you can get the id,
echo "Post ID: ".$post->
Another approach is using $wpdb global variable to make database queries.
You can also use JavaScript to send your post id to another php file using javaScript forms, Ajax or jQuery. jQuery Post.
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Call a javascript function from php [duplicate]

How to call a JavaScript function from PHP?
<?php
jsfunction();
// or
echo(jsfunction());
// or
// Anything else?
The following code is from xyz.html (on a button click) it calls a wait() in an external xyz.js. This wait() calls wait.php.
function wait()
{
xmlhttp=GetXmlHttpObject();
var url="wait.php"; \
xmlhttp.onreadystatechange=statechanged;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function statechanged()
{
if(xmlhttp.readyState==4) {
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
and wait.php
<?php echo "<script> loadxml(); </script>";
where loadxml() calls code from another PHP file the same way.
The loadxml() is working fine otherwise, but it is not being called the way I want it.
As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.
All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.
Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.
So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".
There are many ways to do this, but here are a couple.
Using just PHP:
echo '<script type="text/javascript">',
'jsfunction();',
'</script>'
;
Escaping from php mode to direct output mode:
<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>
You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.
Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.
Here's an example of what I think you're doing with jQuery's AJAX
$.get(
'wait.php',
{},
function(returnedData) {
document.getElementById("txt").innerHTML = returnedData;
// Ok, here's where you can call another function
someOtherFunctionYouWantToCall();
// But unless you really need to, you don't have to
// We're already in the middle of a function execution
// right here, so you might as well put your code here
},
'text'
);
function someOtherFunctionYouWantToCall() {
// stuff
}
Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.
$.get(
'wait.php',
{},
function(returnedData) {
// Assumes returnedData has a javascript function name
window[returnedData]();
},
'text'
);
* Or JSON or XML etc.
I always just use echo "<script> function(); </script>"; or something similar. You're not technically calling the function in PHP, but this is as close as you're going to get.
Per now (February 2012) there's a new feature for this. Check here
Code sample (taken from the web):
<?php
$v8 = new V8Js();
/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;
try {
var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
var_dump($e);
}
?>
You can't. You can call a JS function from HTML outputted by PHP, but that's a whole 'nother thing.
If you want to echo it out for later execution it's ok
If you want to execute the JS and use the results in PHP use V8JS
V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');
You can refer here for further reference:
What are Extensions in php v8js?
If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution
Thats not possible. PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer). Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).
<td onClick= loadxml()><i>Click for Details</i></td>
function loadxml()
{
result = loadScriptWithAjax("/script.php?event=button_clicked");
alert(result);
}
// script.php
<?php
if($_GET['event'] == 'button_clicked')
echo "\"You clicked a button\"";
?>
I don't accept the naysayers' answers.
If you find some special package that makes it work, then you can do it yourself! So, I don't buy those answers.
onClick is a kludge that involves the end-user, hence not acceptable.
#umesh came close, but it was not a standalone program. Here is such (adapted from his Answer):
<script type="text/javascript">
function JSFunction() {
alert('In test Function'); // This demonstrates that the function was called
}
</script>
<?php
// Call a JS function "from" php
if (true) { // This if() is to point out that you might
// want to call JSFunction conditionally
// An echo like this is how you implant the 'call' in a way
// that it will be invoked in the client.
echo '<script type="text/javascript">
JSFunction();
</script>';
}
Ordering It is important that the function be declared "before" it is used. (I do not know whether "before" means 'lexically before' or 'temporally before'; in the example code above, it is both.)
try like this
<?php
if(your condition){
echo "<script> window.onload = function() {
yourJavascriptFunction(param1, param2);
}; </script>";
?>
you can try this one also:-
public function PHPFunction()
{
echo '<script type="text/javascript">
test();
</script>';
}
<script type="text/javascript">
public function test()
{
alert('In test Function');
}
</script>
PHP runs in the server. JavaScript runs in the client. So php can't call a JavaScript function.
You may not be able to directly do this, but the Xajax library is pretty close to what you want. I will demonstrate with an example. Here's a button on a webpage:
<button onclick="xajax_addCity();">Add New City</button>
Our intuitive guess would be that xajax_addCity() is a Javascript function, right? Well, right and wrong. The cool thing Xajax allows is that we don't have any JS function called xajax_addCity(), but what we do have is a PHP function called addCity() that can do whatever PHP does!
<?php function addCity() { echo "Wow!"; } ?>
Think about it for a minute. We are virtually invoking a PHP function from Javascript code!
That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!
For some backend node processing, you can run JS script via shell and return the result to PHP via console.log
function executeNode($script)
{
return shell_exec('node -e \'eval(Buffer.from("'.base64_encode($script).'", "base64").toString())\'');
}
$jsCode = 'var a=1; var b=2; console.log(a+b);';
echo executeNode($jsCode);

Button On click call jquery function and acess php

I am very new to Wordpress and Woocommerce. I have few doubts wrt jquery in Wordpress. Say i have a function
function test(){
alert("test");
<?php
error_log("Test ---------------------------- ", 0);
?>
}
and a button:
<input type="button" id="btnclick" onclick="test();" value="Test" />`
error log is printing on page load but not on click. But i want to execute code inside php block only when user clicks on button.Is there a way to achieve this ? Thanks in advance`
jPO has already explained how to solve this in a good way, but I thought I should explain why this happens.
PHP is executed on the server. Once the page has been sent to the client, the PHP is no more. JavaScript happends on the client, and can be executed as long as the user is viewing the webpage. Since they do not live during the same timeperiod they are not aware of each other and can not be mixed in that way.
When you visit the page in your browser, the browser sends a request to the server. On the server the PHP interpreter goes through the code of the requested page, executing everything between <? and ?>. It does not understand what the other stuff around it is - it could be HTML, JS, plain text, anything, the PHP interpreter does not know and does not care. That is why it writes to the error log on page load.
When the PHP interpreter is done it has produced a document looking like this:
function test(){
alert("test");
}
That is sent to the client, and the JS (without any instruction to write to the error log) is run on the client when the button is pushed.
Not possible like that. If you'd like to do so. You need something like ajax method in php which you can call. Let's say you have a file in the root of your project called ajax.php, there you can define a function named test(), then you have to have a $_REQUEST translator, which calls your function test(), so the ajax.php would look like this
<?php
// checks if you sent a parameter named method and calls the method
// if you provide parameter named params it will send them too
if(isset($_REQUEST)){
if(isset($_REQUEST["params"]))
ajax($_REQUEST["method"],$_REQUEST["params"]);
else
ajax($_REQUEST["method"]);
}
function ajax($function,$data = null){
$function($data);
}
function test(){
error_log("Test ---------------------------- ",0);
}
and your ajax would look like this
function test(){
$.ajax({
url:"ajax.php",
data:{
method:"test"
}
});
}
hope it helps

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

Categories

Resources