php function call with ajax - php

I am trying to call a php function when an HTML button is clicked.i have done some searching and found that its impossible to do this directly and i should use ajax.
so this is my attempt so far which is not working.this is my test.php and the function is also in this page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.NextPage').on('click', function() {
$.ajax({
url: 'test.php',
data: {x: 1},
type: 'POST',
dataType: 'JSON',
success: function(response) {
alert(response);
}
});
});
});
</script>
</head>
<body>
<button type="button" class="NextPage">go to nextpage</button>
<?php
if (isset($_POST['x'])) {
if ($_POST['x'] == 1) {
$data = function1();
echo json_encode($data);
exit;
}
}
function function1() {
return 'Hi user! im function #1';
}
function function2() {
return 'Hi user! im function #2';
}
?>

get the value of the x from ajax call.
$x = $_POST['x'];
then use it.
EDIT
First you have to check weather your variable is set or not..
if(isset($_POST[x]))
{
$x = $_POST['x'];
}
try this

I've practically used your code and got it working. Your PHP is just fine, as for your AJAX call, it must have success or done to benefit the returned data.
The code for reference is here
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="mobile-web-app-capable" content="yes">
<link rel="shortcut icon" sizes="196x196" href="">
<link rel="stylesheet" type="text/css" href="" />
</head>
<body>
<div id="abc"></div>
<button type="submit" class="NextPage">go to nextpage</button>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
JavaScript
$(document).ready(function() {
$('.NextPage').click(function() {
$.ajax({
type:'post',
url:'service.php',
data:{x:1}
}).done(function(data) {
$("#abc").text(data);
});
});
});
PHP
<?php
$x = $_POST['x'];
if ($x == 1) {
function1();
}
function function1() {
echo "This is function 1";
}
function function2() {
echo "This is function 2";
}

First off, you need to set your button to type="button", then, make an AJAX request, then the missing part on your code is the backend part which processes the request. Then the backend responds to that call. After that you can just do what you please on that response. Consider this example:
<?php
// this part handles the AJAX request
if(isset($_POST['x'])) {
if($_POST['x'] == 1) {
$data = function1();
// a call has made, then give a response
echo json_encode($data);
exit;
}
}
function function1() {
// do some processing
return 'Hi user! im function #1';
}
function function2() {
return 'Hi user! im function #2';
}
?>
<!-- make its type "button" -->
<button type="button" class="NextPage">go to nextpage</button>
<div id="notification"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.NextPage').click(function(){
$.ajax({
url: 'test.php',
data: {x: 1},
type: 'POST',
dataType: 'JSON',
success: function(response) {
$('#notification').html('Your ajax call has been successful<br/> and this is a notification').css({background: 'yellow'});
}
});
});
});
</script>

What makes you think it is impossible to call a php function directly. This is exactly what is done in CodeIgniter PHP MVC framework. You can call a php function with arguments inside a php class directly in CodeIgniter and that is actually what is done always.

Related

Get data using jQuery ajax method in codeigniter

Below is my view:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.min.css"); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
<script src="<?php echo base_url("plugins/jQuery/jQuery-2.2.0.min.js"); ?>"></script>
<script type="text/javascript" charset="utf-8">
function waitForMsg1() {
$.ajax({//Ajax method to get data from Message Controller
type: "GET",
url: "<?php echo base_url('index.php/message/messageCount'); ?>",
async: true,
cache: false,
timeout: 50000,
success: function (data) {
addmsg("new", data);
setTimeout(waitForMsg1, 1000);
},
});
};
$(document).ready(function () {
waitForMsg1();
});
function addmsg(type, count) {
$('#badge').html(count); //selecting the element to display inside the badge
}
</script>
</head>
<header>
<a href="#"><span><div id="bounce"><i class="fa fa-envelope ">
<span class="badge" id="badge" style="background-color:red;margin:-25px 0 0 -5px;">
</span></i></div></span></a>
</header>
Below is the Controller:
<?php
class Message extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('MessageDb');
$this->load->model('UserDb');
$this->load->model('EmployeeDb');
}
public function messageCount()
{
echo '12345'; //This is the dummy value.
}
}
?>
I want to display the count from Message controller into the view, it is not working. I tried a lot but not able to rectify the problem. How this can be done?

Passing variable using ajax and open next page

I try passing variable from one page to next using ajax.
I have running passing, but I don't know how to open page with this variable.
My actual code:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<!-- <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<button id="test" class="btn btn-lg btn-primary">Test</button>
<script>
$(document).ready(function () {
$("#test").click(function () {
var variable = 'AAAaaa';
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'view.php',
data: {"temp": variable},
success: function (data) {
alert("success!");
}
});
});
});
</script>
</body>
</html>
And second page where I want watching what is in $_Post table
<?php
$table = $_POST;
?>
<pre>
<?= print_r($table);?>
</pre>
Edit for comment:
Not a problem. You can create a callback function inside ajax's
success event. On success, take that data from view.php and send it to
the second page with another ajax call. It will all be done
asynchronously and accomplish what you're asking for. – putipong
I have array in view. For example:
$array = array(
"foo" => "bar",
"bar" => "foo",
);
How to send via post and ajax this array to controller function and open this action, when I press the button.
I tried as above , but does not work
public function actionUuuu()
{
$request = Yii::$app->request;
$array = $request->post();
print_r($array)
In your view.php, you can assign the table data to $_SESSION and then retrieve later in your second page, simply by starting a session with session_start();
A session must be started on every page that requires the use of session data, else it will not work.
view.php:
session_start();
if ($_POST['temp'] == 'AAAaaa') {
$_SESSION['tableData'] = $tableData;
echo true;
} else {
echo false;
}
return;
Javascript:
$(document).ready(function () {
$("#test").click(function () {
var variable = 'AAAaaa';
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'view.php',
data: {"temp": variable},
success: function (data) {
if (data == 'true') {
window.location.replace('secondPage.php');
}
}
});
});
});
secondPage.php
session_start();
$table = $_SESSION['tableData'];

Session preservation

I read all other question but nothing really helped.
I have one page with display and other php files supporting it but when I pass a POST and make a $_SESSION['view'] out of it with another POST request but not same one the $_SESSION['view'] is gone.
So in practic when user change view from four months (default) to one month and then click NEXT view gets back to four months.
Display Page
<?php
session_start();
$dateb = (new DateTime())->getTimestamp();
$_SESSION['usrdate'] = $dateb;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="site.css" type="text/css" rel="stylesheet">
<script>
$(document).ready(function () {
$("#four").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
view: "four"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
$("#one").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
view: "one"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
$("#next").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
toggle: "next"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
});
</script>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="nav"></div>
<div id="loginform"><?php
/*require "navigation.php";*/
if (!isset($_SESSION['id'])) {
include "logon.php";
} else {
echo "<a href='logoff.php'>Logout</a>";
}
?>
</div>
<div id="loadplace">
<?php
if (isset($_SESSION['id'])) {
include "switcher.php";
}
?>
</div>
<div id="tog"><button type="button" id="prev">Prev</button>
<button type="button" id="next">Next</button></div><br/><br/>
<div id="view"><button type="button" id="four">Four</button>
<button type="button" id="one">One</button></div>
</body>
</html>
Script
<?php
session_start();
$_SESSION['view'] = $_POST["view"];
$_SESSION['toggle']= $_POST["toggle"];
$tog = $_SESSION["toggle"];
if ($_SESSION['view'] == "four") {
include_once "four_m.php";
} elseif ($_SESSION['view'] == "one") {
include "calendar.php";
} elseif ($_SESSION['view'] == "week") {
include "week.php";
} elseif ($_SESSION['view'] == "day") {
include "day.php";
} else {
include "four_m.php";
}
?>

Access JavaScript variables value in php to store in mysql

Just simple,
I am trying to access the variable in javascript inside the php while working with elrte,
bleow is my index.php file
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>One textarea with elRTE and file upload plus one text field with elFinder</title>
<!-- jQuery and jQuery UI -->
<script src="js/jquery-1.4.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery-ui-1.8.7.custom.min.js" type="text/javascript" charset="utf- 8"></script>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.7.custom.css" type="text/css" media="screen" charset="utf-8">
<!-- elRTE -->
<script src="js/elrte.min.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="css/elrte.min.css" type="text/css" media="screen" charset="utf-8">
<link rel="stylesheet" href="css/elrte.full.css" type="text/css" media="screen" charset="utf-8">
<!-- elFinder -->
<link rel="stylesheet" href="css/elfinder.css" type="text/css" media="screen" charset="utf-8" />
<script src="js/elfinder.full.js" type="text/javascript" charset="utf-8"></script>
<!-- elRTE and elFinder translation messages -->
<!--<script src="js/i18n/elrte.ru.js" type="text/javascript" charset="utf-8"></script>
<script src="js/i18n/elfinder.ru.js" type="text/javascript" charset="utf-8"></script>-->
<script type="text/javascript" charset="utf-8">
// elRTE with elFinder on a textarea
$().ready(function() {
var opts = {
cssClass : 'el-rte',
lang : 'en', // Set your language
allowSource : 1,
height : 450,
toolbar : 'maxi', // 'tiny', 'compact', 'normal', 'complete', 'maxi', or 'custom' (see advanced documentation for 'custom')
cssfiles : ['css/elrte-inner.css'],
fmAllow : 1,
fmOpen : function(callback) {
$('<div id="myelfinder" />').elfinder({
url : 'connectors/php/connector.php',
places : '',
lang : 'en', // Set your language
dialog : { width : 900, modal : true, title : 'Files' }, // Open in dialog window
closeOnEditorCallback : true, // Close after file select
editorCallback : callback // Pass callback to file manager
})
}
}
$('#editor').elrte(opts);
// Text field with elFinder
var opt = {
url : 'connectors/php/connector.php',
places : '',
lang : 'en',
editorCallback : function(url) {document.getElementById('field').value=url;}, // The id of the field we want elfinder to return a value to.
closeOnEditorCallback : true,
docked : false,
dialog : { title : 'File Manager', height: 500 },
}
$('#open').click(function() { // The id of the button that opens elfinder
$('#finder').elfinder(opt) // The id of the div that elfinder will open in
$('#finder').elfinder($(this).attr('id')); // it also has to be entered here.
})
$('#btnsub').click(function() {
var content = $('#editor').elrte('val');
});
})
})
</script>
</head>
<body>
<?php
$q=mysql_query("select * from aw_about_us")or die(mysql_error());
$r=mysql_fetch_array($q);
extract($r);
?>
<div id="finder"></div>
<table cellpadding="5" cellspacing="5" border="0" width="100%">
<form name="feedback" id="frm" method="post">
<tr>
<td>Title : </td>
<td><input type="text" id="atitle" size="75" value="<?=$abt_title?>"></td>
</tr>
<tr>
<td>Tag Line : </td>
<td><input type="text" id="atag" size="75" value="<?=$abt_small_line?>"></td>
</tr>
<tr>
<td colspan="2"><textarea id="editor" id="acontent" cols="50" rows="4">
<?=$abt_content?>
</textarea></td>
</tr>
<!--<input type="text" id="field" name="field" size="60"/> -->
<!--<input type="button" id="open" value="Browse..." /><br>-->
<tr>
<td><input type="submit" id="btnsub" value="Submit"></td>
</tr>
</form>
</table>
<?php
/*echo $_GET['val'];
if(isset($_POST['updabt']))
{
extract($_POST);
$q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
*/?>
</body>
</html>
I am able to get the value of elrte inside the javascript variable, but now I wanted store this value inside the mysql database, as I am using PHP I want to access this value inside a php so that I can store it in database,
I tried using window.open("abc.php?val="+content); but the value is very large so get method cannot be acceptable here, so is there any way to get this value inside the php? or any alternate way to do this?
** Edit :**
Now it gives me a value of content variable after making following changes, but I want all 3 variables, but unable to get
$('#btnsub').click(function() {
var content = $('#editor').elrte('val');
var title = document.getElementById('atitle').val;
var tag = document.getElementById('atag').val;
alert('title'+title);
$.ajax({
type: "POST",
url: 'abc.php',
data: {title : title, tag : tag, content : content},
success: function(html) { $('result').append(html); },
dataType: 'html'
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
and php file
<?php
include('inc/conn.php');
if(isset($_POST['updabt']))
{
$cont=$_POST['updabt'];
$q1=mysql_query("update aw_about_us set abt_title='$title', abt_small_line='$tag', abt_content='$cont'") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
?>
Now how to get all three variables??
You'll need to submit the value to your PHP script using a POST request to your server. You can do this with Ajax requests, and I believe jQuery has built-in methods for Ajax which are cross-browser.
You need 2 pages, one which will send AJAX (this you have) and one wich will respond (below):
<?php
///ajax.php
if(isset($_POST['updabt']))
{
extract($_POST);
$q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
?>
In javascript you create AJAX post
data['updabt'] = '';
$.ajax({
type: "POST",
url: 'ajax.php',
data: data,
success: function(html) { $('result').append(html); },
dataType: 'html'
});
You can use AJAX (easiest with a library such as jQuery) to submit the variables to another PHP script that will INSERT the values to your database.
Start by reading the following...
jQuery.ajax
jQuery.post
This is actually very simple once you get your head around the subtleties of AJAX.
Here is a simple example to get you off and running. Suppose you wanted to log something to your PHP error log...
This would be my JavaScript function:
var log = function(val) {
$.post("ajax.php", {"mode": 'log', "val": val}, function() {});
}
ajax.php would be a collection of functions, ideally a class...
public function __construct() {
$arrArgs = empty($_GET)?$_POST:$_GET;
/**
* using 'mode' I can send the AJAX request to the right method,
* and therefore have any number of calls using the same class
*/
if (array_key_exists('mode', $arrArgs)) {
$strMethod = $arrArgs['mode'];
unset($arrArgs['mode']);
$this->$strMethod($arrArgs);
}
}
protected function log($arrArgs) {
error_log($arrArgs['val']);
}
The same idea can easily be adapted to write data to a database.

I am trying to update part of my HTML every second and fetching data from database into that Div

I am trying to update part of my HTML every second and fetching data from database into that Div but the code is not working. :( Please help. The first section of code is html page where update function is called and ajax call is made on check_status.php and check_status.php fetches the data from php file from database
<html>
<head>
<title>Reloading testing</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
</script>
</head>
<body>
<h1>Refresh part of the page</h1>
<div id="status">
</div>
</body>
</html>
This is check_status.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("manchesterunited", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM players LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
</body>
</html>
}
You have a syntax error related to parentheses. Try this:
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}); // properly end the ajax() invocation
}
You should be able to fix syntax problems yourself with the help of errors reported on the javascript console.

Categories