Make jQuery AJAX Call to Specific PHP Functions - javascript

I am a rookie PHP developer.
I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class located in /controller/ folder in the project named, Award.php. This PHP file which contains code to execute a function called, addFunction() in another Award.php file located in /model/ folder in the project, which returns a JSON array and is displayed in the awards.html page.
The source code of my files is given as follows:
Awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onAdd();">Add</button>
</div>
</div>
awards.js
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
Award.php (located in /controller/ folder)
<?php
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
Award.php (located in /model/ folder)
<?php
class Award
{
public function addFunction() {
$array = array(
'status' => '1'
);
return $array;
}
}
My code works perfectly and is error-free. Now I want to add another button in awards.html called, Save which when clicked will call a function onSave() in the JS file. Thus the source code of my files will change to the following:
awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onAdd();">Add</button>
<button class="btn" onclick="onSave();">Save</button>
</div>
</div>
awards.js
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
function onSave() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
Now the problem here is that since I want to call the same Award.php file from JS, how do I modify my controller Award.php file? In my opinion there should be twoo different functions which would contain code to instantiate the view Award.php class and call a different function; something like the following:
Award.php
<?php
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
function add(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
}
function save(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->saveFunction();
echo json_encode($method);
}
Award.php
class Award
{
public function addFunction() {
$array = array(
'status' => '1'
);
return $array;
}
public function saveFunction() {
$array = array(
'status' => '2'
);
return $array;
}
}
But how do I call these specific PHP functions from my JS file? If the code I have assumed above is correct, then what should be my JS code? Can anyone please advise me on this? Replies at the earliest will be highly appreciated. Thank you in advance.

Okay I found the solution to the problem myself.
I sent a GET-type AJAX call with the data passed in the form of String parameters and added a success property to get a confirmation whether my code has worked or not. I also changed my Award.php code to catch the passed parameter successfully.
So the source code of my files is:
awards.js
function onAdd() {
$("#display").load(filePath);
$.ajax({
type: "GET",
url: 'controller/Action.php',
data: "functionName=add",
success: function(response) {
alert(response);
}
});
}
function onSave() {
$("#display").load(filePath);
$.ajax({
type: "GET",
url: 'controller/Action.php',
data: "functionName=save",
success: function(response) {
alert(response);
}
});
}
Award.php
$functionName = filter_input(INPUT_GET, 'functionName');
if ($functionName == "add") {
add();
} else if ($functionName == "save") {
save();
}
function add()
{
$award = new Award();
$method = $award->addFunction();
echo json_encode($method);
}
function save()
{
$award = new Award();
$method = $award->saveFunction();
echo json_encode($method);
}

You would be better off using an MVC framework in which you can have controller functions for add and save functionality. You can achieve the required behavior with your current implementation by sending a query string parameter to tell your php script which function to call:
<?php
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
function add(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
}
function save(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->saveFunction();
echo json_encode($method);
}
if($_GET["action"] == "save")
save();
else if($_GET["action"] == "add")
add();
Your js code will look like:
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php?action=add'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
function onSave() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php?action=save'
).success(function(resp) {
json = $.parseJSON(resp);
});
}

There is a method that I have discovered. Please read my explanation completely to continue.
In your ajax code (I think you use jQuery), include another info 'perform', with value = php function name.
$.post("something.php", {
something1: something1value,
something2: something2value,
perform: "php_function_name"
});
Then, in your PHP file, add this piece of code at the beginning :
<?php if (isset($_POST["perform"])) $_POST["perform"](); ?>
Then, when you call using ajax, you can get a particular function executed.
Example Usage :
Javascript :
$.post("example.php", {
name: "anonymous",
email: "x#gmail.com",
perform: "register"
}, function(data, status) {
alert(data);
});
PHP file example.php:
<?php
if (isset($_POST["perform"])) $_POST["perform"]();
function register() {
echo "Hai " . $_POST["name"] . " ! Your email id is " . $_POST["email"] . ".";
}
?>
When you do this, automatically, function register() will get executed.

Related

Where do PHP echos go when you are posting to a page?

This might be a dumb question. I'm fairly new to PHP. I am trying to get a look at some echo statements from a page I'm posting to but never actually going to. I can't go directly to the page's url because without the post info it will break. Is there any way to view what PHP echos in the developer console or anywhere else?
Here is the Ajax:
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
imgurl = 'url';
filepath = 'path';
$.ajax({
url: imgurl,
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
error: function(data) {
console.log(data);
}
});
}
And here is the php file:
<?php
$image = $_FILES['image']['name'];
$uploaddir = 'path';
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo $uploadfile;
} else {
echo "Unable to Upload";
}
?>
So this code runs fine but I'm not sure where the echos end up and how to view them, there is more info I want to print. Please help!
You already handle the response from PHP (which contains all the outputs, like any echo)
In the below code you have, url will contain all the output.
To see what you get, just add a console.log()
$.ajax({
...
success: function(url) {
// Output the response to the console
console.log(url);
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
...
}
One issue with the above code is that if the upload fails, your code will try to add the string "Unable to upload" as the image source. It's better to return JSON with some more info. Something like this:
// Set the header to tell the client what kind of data the response contains
header('Content-type: application/json');
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo json_encode([
'success' => true,
'url' => $uploadfile,
// add any other params you need
]);
} else {
echo json_encode([
'success' => false,
'url' => null,
// add any other params you need
]);
}
Then in your Ajax success callback, you can now check if it was successful or not:
$.ajax({
...
dataType: 'json', // This will make jQuery parse the response properly
success: function(response) {
if (response.success === true) {
var image = $('<img class="comment_image">').attr('src', path + response.url);
$('#summernote').summernote("insertNode", image[0]);
} else {
alert('Ooops. The upload failed');
}
},
...
}
If you add more params to the array in your json_encode() in PHP, you simply access them with: response.theParamName.
Here is a basic example...
HTML (Form)
<form action="script.php" method="POST">
<input name="foo">
<input type="submit" value="Submit">
</form>
PHP Script (script.php)
<?php
if($_POST){
echo '<pre>';
print_r($_POST); // See what was 'POST'ed to your script.
echo '</pre>';
exit;
}
// The rest of your PHP script...
Another option (rather than using a HTML form) would be to use a tool like POSTMAN which can be useful for simulating all types of requests to pages (and APIs)

Get PHP variable in Javascript file

I have a PHP file on my server which is counting the number of files in a directory. I would like to get the number of files ($fileCount) in my Javascript file.
numberOfImages.php:
<?php
$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
echo $fileCount;
?>
main.js (EXTERNAL JS FILE)
I don't have any code to do with my php file in my JS file yet. I would like to get the variable from my PHP file(http://www.website/numberOfImages.php) and use it (alert it) in my external JS file.
I'm willing to use AJAX.
You may adopt one of 2 Possibilities... Option Nr. 1: You can expose the Number of Images as a Global Variable & Use it in your main.js (that is Assuming that main.js was included in the numberOfImages.php Script. Option Nr. 2 You can use Ajax to do that too:
OPTION NR. 1
<?php
//FILE =>numberOfImages.php:
$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
// EXPOSE THIS VARIABLE TO JAVASCRIPT AS A GLOBAL VARIABLE..
//echo $fileCount;
?>
// SOMEWHERE IN THE SAME FILE: numberOfImages.php:
<script type="text/javascript">
var _NUM_IMAGES = "<?php echo $fileCount; ?>";
</script>
Now, you can access the Number of Images in the main.js by simply referencing the variable _NUM_IMAGES. So doing alert(__NUM_IMAGES) would work. However, be Sure that the main.js is included in the numberOfImages.php File
OPTION NR 2
// INSIDE YOUR HTML/PHP FILE THAT RUNS THE SHOW; IMPORT BOTH JQUERY & YOUR main.js BELOW.
// INCLUDE JQUERY LIBRARY: OTHERWISE THIS WON'T WORK...
// SURE YOU CAN ALSO DO ALL THESE IN PURE JAVASCRIPT, BUT WHY RE-INVENT THE WHEEL???
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
//YOUR main.js COULD LOOK SOMETHING LIKE THIS:::
jQuery.noConflict();
(function ($) {
$(document).ready(function(e) {
$.ajax({
url: 'numberOfImages.php', // <== POINTS TO THE VALID URL OF THE PHP FILE THAT OUTPUTS THE NUMBER OF IMAGES...
dataType: "HTML",
cache: false,
type: "POST",
//HANDLE THE SUCCESS CASE FOR THE AJAX CALL
success: function (data, textStatus, jqXHR) {
if(data){
alert(data);
}
},
//HANDLE THE FAILURE CASE FOR THE AJAX CALL
error: function (jqXHR, textStatus, errorThrown) {
console.log('The following error occured: ' + textStatus, errorThrown);
},
//HANDLE THE EVENT-COMPLETE CASE FOR THE AJAX CALL
complete: function (jqXHR, textStatus) {
}
});
});
})(jQuery);
And the numberOfImages.php could look something like this. Exactly the same way you did it:
<?php
/**
* filename: numberOfImages.php
*/
$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
die($fileCount);
However, be informed that You need JQuery for this to work. You can add this to the File in which you are importing the main.js but before you import the main.js.
if your other javascript isn't from an external source you can do something like:
<?php
$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);
?>
<script type="text/javascript">var fileCount = "<?= $fileCount?>";</script>
<script type="text/javascript" src="main.js"></script>
and then in the main.js use FileCount like so:
alert("fileCount: " + fileCount);

Load php function in js file and use function

I have the following php function.
public function dateIndaysoff($mydate=false){
if(!$mydate)return false;
$host = "localhost";
$user = "user";
$pass = "pass";
$databaseName = "database";
$tableName = "table";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
// $db=JFactory::getDbo();
$dbs->setQuery("select date from table WHERE `date`='$mydate'")->query();
return (int) $db->loadResult();
}
This function searches an input value inside a database table column and if it finds then we have a TRUE, else FALSE.
So, i have a jquery inside .js file where i execute a specific action and i want to check if i have a TRUE or FALSE result. In jquery i use a variable called val. So inside jquery in some place i want to have something like this:
if (dateIndaysoff(val)) {something}
Any ideas?
Instead of wrapping the php code in a function you can wrap it in a if($_POST['checkDate']){//your code here}, then in javascript make an ajax request (http://www.w3schools.com/ajax/), which sends a parameter named checkDate and in the success block of the ajax call you can have your code you represented as {something}
function checkDate(){
$.post('yourPhpFile.php', {checkDate:$dateToBeChecked}, function(data){
if(data){alert("true")};
});
};
and the php:
if($_POST['checkDate']){
//your current function, $_POST['checkDate'] is the parameter sent from js
}
Just to work with your current code.
In your php file lets say datasource.php
echo dateIndaysoff()
In your requesting file lets say index.php
$.ajax({
url: "index.php",
context: document.body
}).done(function( data ) {
/* do whatever you want here */
});
You can do it with AJaX. Something like this:
A PHP file with all the functions you are using (functions.php):
function test($data) {
// ...
}
A JS to request the data:
function getTest() {
$.ajax('getTestByAJaX.php', {
"data": {"param1": "test"},
"success": function(data, status, xhr) {
}
});
}
getTestByAJaX.php. A PHP that gets the AJaX call and executes the PHP function.
require 'functions.php';
if (isset($_REQUEST["param1"])) {
echo test($_REQUEST["param1"]);
}
Ok if i got this right i have to do this:
1st) Create a .php file where i will insert my php function and above the function i will put this:
$mydate = $_POST['val'];
where $mydate is the result of the function as you can see from my first post and val is the variable i want to put in $mydate from ajax.
2nd) I will go inside .js file. Now here is the problem. Here i have a code like this:
jQuery(".datepicker").change(function() {
var val = jQuery(this).datepicker().val();
console.log(val);
if (dateIndaysoff(val)) {
console.log("hide");
jQuery('.chzn-drop li:nth-child(9)').hide();
jQuery('.chzn-drop li:nth-child(10)').hide();
} else {
console.log("show");
jQuery('.chzn-drop li:nth-child(9)').show();
jQuery('.chzn-drop li:nth-child(10)').show();
}
});
Inside this code, in the first if, i want to see if the variable val is inside my database table. So, how could i write correctly this jQuery with the Ajax you propose in order for this to work? Also please take a look maybe i have a mistake in my php function (in this function i want to connect with a database and take a TRUE if $myvalue is inside a table column)

Blueimp plugin fileupload Jquery: Send additional information to PHP handler

I'm trying to send information (additional Handling form data) from fileupload jquery plugin (blueimp) to PHP file. In the PHP file handle can not get the information (content of variable). I think I have a problem in the code. Can some altruistic soul enlighten the way? Thanks in advance.
Javascript file:
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
formData: {idGrupo: 250}, <----I want to send this to PHP file!
done: function (e, data) {
$.each(data.result, function (index, file) {
// $('<p/>').text(file.name).appendTo('body');
});
}
});
});
PHP file (index.php ):
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
class CustomUploadHandler extends UploadHandler
{
protected function handle_form_data($file, $index) {
$sesionIdGrupo2 = $_REQUEST['idGrupo'];
}
protected function trim_file_name($name, $type, $sesionIdGrupo2) {
$name = parent::trim_file_name($name, $type);
$name = $seionIdGrupo2;
return $name;
}
}
$upload_handler = new CustomUploadHandler();
Again I appreciate the help, that would not do without this community (well yes, would do anything that was not code ;). Please be patient, I am newbie :(
Note:
The variable $sesionIdGrupo2 not retrieve the value. My intention is to put the contents of this variable (250) as the name of the uploaded file. ¿Could it be a problem of global variables?
To send Data to PHP UploadHandler.php just send it via url like this:
$(function () {
$('#fileupload').fileupload({
url: 'server/php/index.php?idGrupo=250',
dataType: 'json',
autoUpload: false,
});
});
....i solve that problem! ...i put the Request inside the function "trim_file_name". I think is bad idea, but seem work...
protected function trim_file_name($name, $type) {
$name = parent::trim_file_name($name, $type);
$sesionIdGrupo = $_REQUEST['idGrupo']; <------this work, recibed 250
$name = $sesionIdGrupo;
return $name;
Saludos!

JavaScript in CakePHP's controller

In my CakePHP view, I call method in controller, using jQuery:
function placeSensors(nk) {
$.ajax({
type:'post',
url:'/myapp/maps/placeSensors/' + nk,
success: function(r) {
if(r.status = 'ok') {
}
}
});
}
JS in controller is defined with ie.:
class MapsController extends AppController {
var $name = 'Maps';
var $helpers = array('Js');
var $uses = array('Measurings', 'Maps');
var $components = array('RequestHandler'); // added later, but still the same
function index( $id = null, $value = null ) {
$code = '';
?>
<script type="text/javascript">
alert('Hello!');
</script>
<?php
return $code;
}
So, with simple code, I can not get alert message on my web form. Very simple code I was using in some other project and it works there, and for some reason this does not work on this one...
I'm really stuck with this one, can you please help me.....
UPDATE: this is response i'm getting by Firebug:
<script type="text/javascript">
alert('Hello!');
</script>
You're trying to place code that should be viewed (javascript) by the client, inside a controller. Controller is for business logic, that the client doesn't see.
Place your javascript inside a javascript file in the /webroot/js/ directory.
For interacting with ajax, tell your controllers to use the RequestHandler component to determine that they're being called by ajax. From there you can return simple values, or return a json or xml view.
If that sounds complicated, don't worry about it for now and just start as simple as you need and slowly build up your application.
function placeSensors(nk) {
$.ajax({
type:'post',
dataType:'json',
url:'/myapp/maps/placeSensors/' + nk,
success: function(r) {
if(r.status) {
alert(r.code);
}
}
});
}
class MapsController extends AppController {
var $name = 'Maps';
var $helpers = array('Js');
var $uses = array('Measurings', 'Maps');
function index( $id = null, $value = null ) {
}
// update below code
function placeSensors( ) {
$nk = $_POST['nk'];
echo json_encode(array(
'status' => true,
'code' => "code"
));
exit();
}
Ok, i finally solved this one.
All I needed was to add one form and one text, or even better hidden element on form.
After that everything started to work.
So my mentioned code was ok, all I needed was that one text box......... Hope that somebody can tell me why?
Thank you on all your help and support.

Categories

Resources