I am trying to make a delete button which I'll be able to delete some user from my database but main thing how to call PHP function with clicking on some div etc..
<div class="cross" onclick='<?php deleteUser("Nickname")?>'>X</div>
<?php
function deleteUser($username) {
//... code
}
?>
Html can't directly call php, it can do a separate call to load the same page, with the action.
<?php
function deleteUser($username){}
if($_GET['action'] == "delete")
{
deleteUser($_GET['username']);
}
?>
<a class="cross" href='?action=delete&username=NickName'>X</a>
The reason for this is because PHP runs on the server, BEFORE anything is sent to the browser. So it requires another page load to run the function by clicking something. It is possible to use javascript and AJAX calls to send a call to a php script without reloading the main page. Just look into Jquery's post or ajax features.
You cannot call a PHP function that resides on the server by just clicking on a div that exists on the client browser.
You need to trigger a Javascript event (using e.g. jQuery), that will call a function on the server (e.g. through AJAX), that after checking the parameters are correct and the user has the right of calling it will do what you seek.
There are ready-made frameworks that would allow you to do that.
Otherwise (after including jQuery in your HTML page) you can do something like,
<div class="cross" id="deleteUserButton" data-user="nickname">X</div>
<script type="text/javascript">
$('#deleteUserButton').on('click', function() {
let nick = $(this).attr('data-user');
$.post('/services/delete.php',
{
cmd: 'delete',
user: nick
}).then( reply => {
if (reply.status === 'OK') {
alert("User deleted");
}
});
<?php
$cmd = $_POST['cmd'];
switch($cmd) {
case 'delete':
$user = $_POST['user'];
if (deleteUser($user)) {
$reply = [ 'status' => 'OK' ];
} else {
$reply = [ 'status' => 'failure', 'message' => 'Doh!' ];
}
break;
...
header('Content-Type: application/json;charset=UTF-8');
print json_encode($reply);
exit();
Related
I have a line in a php code that reads something like this:
echo '<div class="sample-button">Do something</div>'
This shows a clickable text link on the page. Now I want that clicking on this link should call a php function myFunc() which I have defined in the same php file. How do I implement this?
Whatever the <a href="#"> gos to is your answer.
The path needs to be <a href="#?call=1">
Now that's set, you need to create an if statment..
if ($_GET['call'] === 1){ myFunc(); }
When you click the link, it should refresh the page with the url now set to: localhost/page.php?call=1. As the php page is refreshed it can call MyFunc().
You can call a JS function on click, not a php one. I think you have to better check the documentation on what is the purpose of the php language.
If you really want to execute a php script by clicking on the link you can use jquery ajax.
In your case call the same php file where the function is located by listening to the button's click event and perform the ajax request:
$('.sample-button').click(function() {
// Ajax Call
$.ajax({
url: "/path_to_your_script.php",
contentType: "application/x-www-form-urlencoded",
type: "POST",
data: {callFunction:true},
success: function(response){
// Check your response
},
error: function(){
// Error handling
}
});
});
On top of your php script you need to check:
<?php
if (!empty($_POST['callFunction'])) {
your_function() {
return $yourResponse;
}
exit();
}
A quick example ( untested ) to show how you might invoke your php function and use the response after clicking a standard link on a page.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) && $_POST['action']=='call_my_func' ){
/* ensure we discard the buffer if we need to send a response */
ob_clean();
function myFunc($var){
echo 'PHP function...';
}
/* call your function */
call_user_func( 'myFunc', 'some variable' );
exit();
}
?>
<script type='text/javascript'>
function invoke_myfunc(){
var http=new XMLHttpRequest();
http.onreadystatechange=function(){
if( http.readyState==4 && http.status==200 ) alert( http.response );
};
var headers={
'Content-type': 'application/x-www-form-urlencoded'
};
http.open('POST', document.location.href, true );
for( header in headers ) http.setRequestHeader( header, headers[ header ] );
http.send( [ 'action=call_my_func' ].join('&') );
}
</script>
<?php
/*
in your page
-------------
*/
echo '<div class="sample-button">Do something</div>';
?>
My problem is that I need a PHP script to continously provide ouput at certein points of it's execution. I have workng AJAX to fetch the html but it only echos once the script is complete. Here is an example:
<?php
class test {
function test() {
echo '1';
sleep(20);
echo '2'
sleep(5);
}
}
I need some way to have the echo's actually displayed in the browser even though the function is still continuing. I have tried using global variables and session variables to no avail.
Thanks for the help!
I've seen many questions where people are trying to do this type of thing, but as far as I know it really isn't possible to do it the way you're trying to do it using only PHP and AJAX. In order for this to work using just AJAX rather than websockets or some other approach, you can break your script into separate pieces at the points where it needs to provide output, and provide the output as responses to separate AJAX requests. Here is a basic example of what I mean. The script on your page can start the process and makes repeated calls to step through the process until it's complete.
<button id="begin_process">Start</button>
<script type="text/javascript">
function step(step_number) {
$.get('test.php', {'step_number': step_number}, function(response){
console.log(response.message);
if (response.next_step) {
step(response.next_step);
}
}, 'json');
}
$(document).ready(function(){
$('#begin_process').click(function(){
console.log('go!');
step(1);
});
});
</script>
test.php:
<?php
class Test {
function step($step_number) {
switch ($step_number) {
case 1:
return array('next_step' => 2, 'message' => 'step 1 complete');
case 2:
sleep(20);
return array('next_step' => 3, 'message' => 'step 2 complete');
case 3:
sleep(5);
return array('message' => 'finished');
}
}
}
$test = new Test();
echo json_encode($test->step($_GET['step_number']));
I have an issue redirecting to another page in codeigniter, this is my js:
<script type="text/javascript">
$(document).ready(function () {
var url = $('#baseurl').val();
var form = $('#customerinfo');
$('#next').click(function (e) {
if ($("form")[0].checkValidity()) {
// Prevent submit.
e.preventDefault();
//Start loading
var checkbox = $('#Accept');
if (checkbox[0].checked == true)
{
$.post(url + 'customerinfo/next', form.serialize(), function(response) {window.location.href=url + 'paymentinfo';});
}
else
{
$("#errmsg .msg").text("You need to read and accept the terms and conditions before you can continue!");
$("#errmsg").css("display", "block");
}
$(".loading-add-ticket").css("display", "block");
// Send request.
}
else console.log ( "invalid form" );
});
});
</script>
What it does:
When the next button is clicked it submits the form via ajax, the form is then processed on the server and upon completion the user is redirected using the following block of code:
<?php
class CustomerInfo extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
// Write to $title
$this->template->write('title', 'Customer Info');
// Write to $content
$this->template->write_view('content', 'tickets/customerinfo');
// Write to $sidebar
$this->template->write_view('sidebar', 'sidebar');
// Render the template
$this->template->render();
}
function next()
{
if ($_POST) {
if (isset($_POST['Accept']))
{
$data[0] = array(
'TravelInsurance' => $_POST['TravelInsurance'],
'LuggagePayment' => $_POST['LuggagePayment'],
'Donations' => $_POST['Donations'],
'FirstName' => $_POST['FirstName'],
'LastName' => $_POST['LastName'],
'CityTown' => $_POST['CityTown'],
'ContactNo' => $_POST['ContactNo'],
'Address' => $_POST['Address'],
'Accept' => $_POST['Accept']
);
$this->session->set_userdata('customerinfo', $data);
redirect(site_url('paymentinfo'));
}
}
}
}
?>
The problem:
The redirect never happens, when i check the post response using firebug in my browser i notice that the target page has been returned :
What i want: I need the page to be redirected to the target page, i am new to codeigniter so i do not know what i am doing wrong.
current fix:
In the success function on my ajax function i am using javascript to redirect to the next page but i do not want the redirects to be handled on the client side.
Somtimes with forms i prefer to use
header("Location: /Controller/method/value");
i know that's a dirty method but sometimes is helpful
I want to update a div contents automatically with refresh whole page. So i did Ajax renderPartial in YII. Now I implement using AJAX button onclick
My code as follows
<?php
echo CHtml::ajaxButton ("Update data",
CController::createUrl("blog/UpdateAjax?url=$url"),
array('update' => '#inrscrn'));
?>
Now I want to render with in a time limit please help
Your question is not very clear. I suppose you want to setup an automatical & periodical refresh of the content within a div instead of clicking on the button.
This is the JavaScript you need on your page:
<script type="text/javascript">
timeout = 60 * 1000; // in Milliseconds -> multiply with 1000 to use seconds
function refresh() {
<?php
echo CHtml::ajax(array(
'url'=> CController::createUrl("blog/UpdateAjax?url=".$url),
'type'=>'post',
'update'=> '#inrscrn',
))
?>
}
window.setInterval("refresh()", timeout);
</script>
But it is not a good approach to send an URL to your controler, rather make a direct request to to make a special AJAX return of a controler which needs to return the correspondent data.
<?php
public function actionTest(){
if (isset($_REQUEST['AJAX']) || Yii::app()->getRequest()->getIsAjaxRequest()) {
$this->renderPartial(
'test',
array('model' => $model),
false,
true
);
} else {
$this->render(
'test',
array('model' => $model),
);
}
}
?>
I am doing a simple ajax request to another domain like this:
<script type="text/javascript">
$(function() {
$('.clik').click(function() {
$.ajax({
type: "POST",
url: "http://sub.mydomain.com/test.php",
crossDomain: true,
dataType:"jsonp",
success: function(data) {
$('p.txt').html(data['no']);
}
});
});
});
</script>
</head>
<body>
<p class="clik">Halleluja</p>
<p class="txt"></p>
this is the test.php page on sub.mydomain.com
<?
header('Access-Control-Allow-Origin: http://mydomain.com');
// Begin Session
require_once('cl.session.php');
$session = new Session();
$session->start_session('test', false);
// Access Database
require_once('cl.database.php');
$login_db = new Database('user', 'pass', 'accounts', 'test');
$login_pdo = $login_db->PDO;
include "fn.check_login.php";
if(checkLogin($login_pdo) == true) {
// We start out by checking if the request has been made using AJAX
if (is_ajax()) {
echo "this is working";
} else {
echo "this is not working!";
}
} else {
echo 'You are not authorized to access this page, please login. <br/>';
}
// Function to check if the request is an AJAX request
function is_ajax() {
// BOOLEAN return if AJAX
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?>
It returns a semantic issue.
Also if I simply echo some basic text:
<?
echo "Hello World!";
?>
it still returns a semantic issue.
could somebody tell me what went wrong?
Well, for a start, JSONP requests can't be POST (only GET). But I tend to assume jQuery is ignoring the invalid type. JSONP is intrinsically a GET.
Your response to it is invalid. You've told jQuery you're expecting the server to provide a JSONP response. but your responses aren't JSONP.
A JSONP response would look something like this:
callback({
"property": "value",
"anotherProperty": 42
})
...where the name of the callback (callback in the above) is taken from the query string of the request. So for instance, if the request were http://sub.mydomain.com/test.php?callback=foo, the response would use foo for the name of the callback:
foo({
"property": "value",
"anotherProperty": 42
})
jQuery will add the callback= query string parameter to the request for you automatically, and generate the corresponding function for you, which in turn calls the ajax success handler with the data passed into it.
I think you may need to use the jquery postMessage plugin (or similar if there is one). Long time since I tried it but check if you load the script from the server you wish to call (think I tried that and failed in the past but hey - its worth a bash - report back if it does).