How to check if table is empty using cakephp and AJAX? - javascript

how do we check if table is empty with cakephp and ajax? In my index.ctp I have an image that when clicked, it will inform the user if the table is empty or not. If it's empty, an alert box will appear, and if it's not, it will be redirected to another page.
<?php
echo $this->Html->image('movie.png', array('onclick'=>'check()'));
?>
JAVASCRIPT:
function check(){
//check browser comp, create an object
object.GET("GET", url, false);
//rest of the code here
}
MoviesController.php
function index(){
//something here
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
I know how to do it using the normal PHP coding, but with cakephp, and since I am new, I dont know yet. For regular PHP coding, I used the GET method for AJAX, and I can specify the URL for the PHP query inside the GET function. I don't know how to do it using cake.

You need to set the layout to AJAX then render your view. I strongly recommend not to use the index() method for this. Instead you can define a whatever() method in the MoviesController:
function whatever(){
//It is not a bad idea to do this only for GET - use the RequestHandlerComponent
$this->layout = 'ajax';
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
The in the view file whatever.ctp:
echo json_encode(array('moviecount' = $moviecount));
//It is a good idea to add an isset() ternary check here like:
// echo isset($moviecount) ? json_encode(array('moviecount' => $moviecount)) : json_encode(false);
Notice that I am creating an array and encoding it to JSON. This is the way to convert variables to and from JSON. To decode use json_decode() of course.
The Client-side code really depends on what you're using to make the AJAX call but let us say that the call succeeded and you got the data back in the data variable:
//Make the AJAX call to example.com/movies/whatever via GET
//Check what data is but it should definitely be an array
if (data['moviecount']) {
//If moviecount is 0 it will go in the else statement - 0 i falsey
window.location = 'example.com/redirect/url';
} else {
alert('No records');
}
I advice against using alert() to inform the user that there are no records. Better put it somewhere in the page - in some div or whatever. Since this is an AJAX request it could be repeated many times. Consecutive use of alert() is not really user-friendly in this case.

Related

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

Use variable value on php webpage in separate javascript function

I have a server running which has a php function which returns true/false depending on input values. Currently I am just echoing the result on the page. I want to use this true/false in a to evaluate a condition in a javascript function running completely separately from the server.
Is there a javascript function I can use to get the text from a webpage and put it in a variable? I looked at the jquery load() function but this doesn't seem like it will work for this purpose.
Keep the output of the PHP script as simple as possible (a text response outputting only "true" or "false").
To send a text response (instead of an HTML response), you can use:
header("Content-Type: text/plain");
You have to call this function before outputting anything.
Now, assuming you can access the output of the script at the URL http://www.example.com/webpage.php
if($.ajax({type: "GET", url: "http://www.example.com/webpage.php", async: false}).responseText == "true")
{
// do something
}
else // "false"
{
// do something else
}
Not sure if it would work, but you might try using document.body.innerHTML. It gets you the innerHTML from the body element from the document (which, in your case, should be a true or false string).
If you are just wanting to use jQuery to get the echoed out result of your php you can do:
var whatever = "<?php echo $result ?>";
In your PHP/HTML (assuming you have a function named "yourFunction" that returns a boolean):
<div id="your_id">
<?php echo yourFunction()?'true':'false';?>
</div>
And in your JavaScript
if($('#your_id').text() == "true")
// do something
else
// do something else
You could treat it like html, update your doc to add a tag around the result. "true" at which point your almost using XML.
You should be able to get the raw response. I usually don't recommend consuming raw text tho as people could inject malicious js into the response.

PHP function calling from Javascript not working

I am working on a posting system in PHP. The posting system goes through a SQL database and then prints out data from the database. I am trying to use javascript to see if the system has been updated. Basically, I want to use javascript to check whether any new posts have been added. I have some code that goes into the database
function minicheck (){
$query= "SELECT * FROM posts";
$result= mysql_query($query);
return mysql_num_rows($result);
}
The function returns the number of rows in the database every 10 seconds.I use javascript to call this function.
<?php
echo(" <script>
killPage();
function killPage () {
setInterval(function(){
x++;
alert(".minicheck().");
}, 10000);
}
</script> ");
?>
THe issue i am facing is that the function returns the exact same value no matter whether or not a row has been added into the sql databse. Even if I add a row into the sql database, the value that is returned by this function is the exact same every time.
How can I fix this?
Thank You,.
You cannot call PHP functions from JavaScript like that.
What you are doing is calling the function once when building your JavaScript, which is then being sent to the browser.
The browser only ever gets the static value you've put in the string, so naturally it can never update.
If you want to call something in PHP from JavaScript, you'll probably want to use XMLHttpRequest (or any of the readily available libraries like jQuery that can help w/AJAX) to query a PHP file that runs the function and returns the value.

Capture instance of PHP class and call an instance function from JS

I have a page that asks for a country code in a ComboBox, and I want it to load some other ComboBox with certain values that depend on the first one.
The secondary data should be loaded using a function inside a PHP class, whose instance I need to capture. I'm still not very familiar with AJAX and jQuery, so that's my problem.
My code is like this (I omitted the most obvious parts, of course):
new.html
<script src="findIDTypes.js"></script>
<form>
<select id="country_id" onchange="findIDTypes(this.id)">
<option value="AR">Argentina</option>
<option value="BR">Brazil</option>
</select>
</form>
dbfunctions.php
class DBConn {
public function GetInstance($host = FALSE, $user = FALSE, $pass = FALSE) {
static $_instance = FALSE;
if ($_instance === FALSE) {
if ($host == FALSE || $user == FALSE || $pass == FALSE) {
// Error! Can't instantiate
}
$_instance = new DBConn($host, $user, $pass);
}
// OK!
return $_instance;
}
public function findIDTypes($country_id) {
// Returns array of value pairs (Code, Description)
}
}
findIDTypes.js
function findIDTypes(value_to_search) {
// ???
}
What I need my AJAX/jQuery (not sure which) function to do is:
Capture the instance of DBConn
Call the instance function "findIDTypes()" in the PHP class
Retrieve the array of (C,D) pairs and load them, one by one, on the secondary combobox
What exactly do I need to do to complete steps 1 and 2, if it's possible at all?
Thanks! :)
php and javascript are entirely different, and while you can use php to generate javascript code before the page is rendered, you cannot call php functions from javascript.
This is because php runs on the server, and javascript (which the exception of Node.js!) runs in the browser.
To solve this, you need to expose your php as an API using HTTP GET or POST methods.
Steps
Build your php page to accept $_GET url query parameters or $_POST parameters, in one form or another.
Decide upon a method of communicating your data on the server end back to your browser's javascript/ajax. For this, I highly recommend json for an innumerable number of reasons. It easily integrates with php via json_encode() and json_decode(), and javascript via JSON.parse() and JSON.stringify().
Once you've established your "API" as it were in php, you can easily use jQuery's $.ajax to send and retrieve data to your php. Since your example is relatively simple, it may be as easy as something like http://yoursite.com/?init=DBConn_GetInstance and handling the $_GET['init'] function, then outputting the results of your function.

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