No luck when trying to use JQuery with CakePHP 1.3 - javascript

I'm new to cakePHP but am close to quitting using it due to my inability of getting jQuery to work with it.
I'm using cakePHP 1.3 and so thought the Html and Js helpers had made Javascript and Ajax redundant but I can't really find any help/api documentation on how to use Js that is sufficient.
All I'm trying to do first of all is send some data to cakePHP with jQuery and then get some data back into jQuery and alert() it. For some reason this just isn't working. Here is my code:
test.js
$('.social').click(function()
{
$.ajax({
type: 'POST',
url: '/activities/add_activity',
data: 'type=social',
dataType: 'json',
success: function(data)
{
alert(data);
},
error: function()
{
alert('wut');
}
});
});
activities_controller.php
function add_activity()
{
if($this->RequestHandler->isAjax())
{
$this->autoRender = false;
$this->autoLayout = false;
$this->header('Content-Type: application/json');
echo json_encode(array('result'=>'hello');
return;
}
}
Every time I click the button with class='social' I get the alert "wut" which means error.
I have the RequestHandler component and Javascript, Js, and Ajax helpers included in my activities_controller.php.
Also, test.js and jquery.js is linked using html->script(); in default.ctp and all other jQuery stuff is working so it's not that.
I've also got this in my beforeFilter() for activities_controller.php:
if($this->RequestHandler->isAjax())
{
Configure::write('debug',0);
}
parent::beforeFilter();
Any ideas what is wrong? Is it a jQuery thing or a cakePHP thing? Or both?
Thanks in advance,
Infinitifizz
P.S.
I have never done AJAX in jQuery before so maybe it is something to do with that that is messing up, I've only ever done simple javascript AJAX.

Don't give up on CakePHP. There is a learning curve, but it's worth it.
I would specify the url like this:
<?php $Url = Router::url(array('controller'=>'activities','action'=>'addActivity'),true); ?>
$('.social').click(function()
{
$.ajax({
type: 'POST',
url: '<?php echo $Url ?>';
...
On the CakePHP side, my method would be like this:
function addActivity()
{
$this->autoRender = false;
$this->autoLayout = false;
App::import('Helper', 'Javascript');
$javascript = new JavascriptHelper();
echo($javascript->object(array('result'=>'hello')));
exit(1);
}
I never use if($this->RequestHandler->isAjax()) although I'm sure some kind soul will tell me why I should.
I prefer to camelCase method names in line with CakePHP convention.
Note that this line in your code: echo json_encode(array('result'=>'hello'); is missing a closing bracket.
Also, I wouldn't use jQuery to do simple AJAX like this - it can make it difficult to debug, but that's just personal preference.

I hate the Ajax Helper in CakePHP... that is until I found this: http://blog.loadsys.com/2009/05/01/cakephp-jquery-ajax-helper-easy-scriptaculous-replacement/
Now I can use native CakePHP Ajax calls with jQuery! Look into this. I was able to solve all of my "simple" ajax issues with this darg-n-drop ajax helper replacements. I just drop this into the helpers directory in my app and replace the ajax.php that is there and viola! jQuery is working. You need to include the jQuery script in the layout of course. Try it, you will love CakePHP again!

I would recommend you to use CakePHP json layout to output the data from view instead of echo json data from your controller.

This probably is offtopic, but...
What I do in order to have the application's root in my javascript:
In the /app/views/layout/default.ctp I have following code
<?php
echo $javascript->codeBlock("var root = '".$html->url('/')."';");
?>
Your parameter url will look like:
url: root+'activities/add_activity',
this way even if you app is in a subfolder or in a tld domain the script will work properly.
Returning "wut" for me means that the script couldn't reach the page in your url parameter. Especially if you working in a subdirectory it will look in http://server.com/activities/add_activity. I am 99% sure that this is the problem :)
Another suggestion: Remove Ajax while it was meant to work with Prototype rather with jQuery

Related

Using GET in jQuery to send data to php file

I am trying to send a row and column number of the clicked cell via GET method.
to php file, where I can check if this cell contains something or not.
For example that the URL will loke like this:
.php?c=3&r=5
I am using:
https://www.w3schools.com/jquery/ajax_get.asp and I have been trying to send data like it is listed on W3schools:
Request "test.php" and send some additional data along with the request (ignore return results):
$.get("test.php", { name:"Donald", town:"Ducktown" });
I am doing it like this:
$(document).ready(function() {
$("td").click(function(event) {
var clickedBtnID = $(this).attr('id');
values=clickedBtnID.split('.');
var row=values[0];
var col=values[1];
$.get("info.php", {"row":row, "col":col});
I was looking at some other examples on StackOverFlow, like:
How to send data to PHP file using JQuery Ajax?
I would like to say it that info.php is the diferent .php file, as the one we are working from. And another thing is that the best way to do this, would be to do it without refreshing the page. So is Ajax call the best way for this? I have tried many different things, but it seems like I can't send the data via GET method.
I'm not 100% sure I understand what you're looking to do, but I'll try to help!
Have you tried something like this? In your js file:
$.get("info.php?c=3&r=5");
Then in your PHP file:
//Retrieve the variables
$c = ($_GET["c"]);
$r = ($_GET["r"]);
//Then do what you need to do with $c and $r
Let me know if that helps.
I have tried this:
$.ajax({ url: 'info.php',
data: {'row':row, 'col':col},
type: 'GET',
success: {}
});
And it works perfectly. I don't know why the jquery $.get didn't work.

How do I properly use the json ajax

I want to send data from php to a browser using JSON. I think I understand the process - see my example code below. But someone told me this is not the right way to do it. I have been researching for three days but because my English is poor I am not confident that I have found an answer.
What I am hoping for is a sample of code that will receive the JSON and pour it into html elements such as a div, and give it style via CSS, etc.
I really just want an example of how to do this so that I can learn from it and expand it myself for my own needs, but I am unconfident that this approach is correct and do not want to write more bad code.
Thanks
Javascript
$(document).ready(function() {
$.ajax({
type : 'POST',
url : 'server.php',
dataType:"json",
success : function (data) {
$("#orders").html(JSON.stringify(data));
}
});
});
PHP
<?php
$db = new PDO('mysql:host=localhost;dbname=Contact', 'root', '');
$statement=$db->prepare("SELECT * FROM myfeilds");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
You don't need to call JSON.stringify on the data that gets returned in your response. This method is for converting a javascript object to a JSON string, but your PHP code should be sending a JSON string back already by the looks of it.
So it depends on what your returned JSON looks like, but usually it'll be something like this:
{"name":"Mike", "phone":"5551234", ...} etc
So in your success callback, you would do something like this:
$("#name").text(data.name);
$("#phone").text(data.phone);
And so on.
Note that I'm using the .text() method. You could use .html() as you've done but you probably don't need to unless your JSON strings contain HTML or you want to write out HTML like so:
$("#name").html("<p>" + data.name + "</p>");
As for styling, I would setup your styles in advance so that you don't have to do it in javascript as this will be more performant.
However, if for some reason you needed to then you could do something like:
$("#name").css({"display":block","color": "#000"});
Hope that helps.

dynamically change select options with php

Okay, so I have this function in PHP that gets an attribute and returns an array. Something like this:
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
Everytime the parent select changes, the function getProvinces() should be executed with the new ID and the arrayWithProvince should be included as options in the child select.
I'm using jquery to handle the events, as I found somewhere. I need to do something like this.
$("#selectCountry").change(function() {
var parent = $(this).val(); //get option value from parent
var prov = <?php echo json_encode($pagina->getProvinces( <PARENT> )); ?>;
list(prov);
My problem is that I don't know how to tell the getProvinces($countryID) php function which is the new value of the parent.
Thanks in advance.
You should use javascript for that in order to refresh part of your page with dynamic content.Below is an example using jquery's ajax function.When the select with id #parent_select changes you call your php script and you append the returned data (the html of the child select in the example) in a div you want.
Javascript part would be something like this:
$("#parent_select").change(function() {
$.ajax({
url: "your_script.php?cid="+$(this).val(),
success: function(html){
$("#child_select_container").append(html);
}
});
});
And your_script.php code would look something like :
<?php
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
$countryID=(int)$_GET['cid'];
$provinces=getProvinces($countryID);
echo '<select id="child_select">';
foreach($provinces as $key=>$province){
echo '<option id="'.$key.'">'.$province.'</option>';
}
echo '</select>;
I havent tested the example.It is just a basic how to example.You should be able to work your way from here.But if you have any problems let me know.
As far as I know, you cannot execute the function without reloading entire page (I mean php should recompile it and pass it to the client).
You should use only JavaScript for that purpose. Store you arraylist in JS code, and validate it once upon form submission (just to be sure).
You need to make an Ajax request to the server.
Look at it this way: Your Javascript/jQuery is running on the client side (web browser) and you PHP is running on your web server.
So to communicate between the browser(jQuery) and the server(PHP) you need to make a Ajax request.
jQuery has a ajax function you could use, your best bet is to do some research on the subject as Ajax is something you will use all the time and understanding how it works is crucial.

How to load an external js file as plain text and assign to variable as a string

Really sorry if this is a dumb question but I can't seem to get this to work. As the title says i am trying to load an external js file and assign it to a variable as plain text. The project is a simple js "compiler" that stitches together a number of js files and minifies them into one. I am currently using the $.get() method and appending the response to a string.
The problem is that the js file that handles the above also needs to be included in the final minified file. I can load in all the other files and stitch them together just fine but when i load this main file into itself sourcing a js file it seems to evaluate and overwrite itself and so stops the process.
For the time being i have got around the problem by loading in a copy as a .txt file but it means i have to keep two files up to date which isn't ideal.
I found this article but it refers to javascript loaded via script tags in the head.
Any help would be appreciated. I will happily post code but not sure which bits would be useful.
Update: I probably should have mentioned that the project needs to run entirely client side so i can't use PHP/.NET pages. All the files I'm loading in are on the same domain though.
Try to use Ajax.get() :
var script;
$.get('script.js', function(data) {
script = data;
});
for Ajax.get() it will work inside your domain, you can't call external domains, if your application requires loading external JS file then my guess is that you have to use PHP or another server-side language as:
var script;
$.get('getScript.php', {url: "http://test.com/script.js"}function(data) {
script = data;
});
in getScript.php you can use CURL or file_get_contents
Note that $.get() and $.post() and $.ajax() are all the same thing.
$.get and $.post are just shorthand versions of $.ajax() that come with presets (obviously, type: "GET" and type:"POST" for one...). I prefer using $.ajax because the format can be more structured, and therefore easier to learn/use.
Javascript/jQuery would look something like this:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "loadmyfile.php",
data: 'filename=js/myscript.js',
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#myhiddentext').val(whatigot);
} //END success fn
}); //END $.ajax
}); //END $(document).ready()
</script>
Important: Note that you would need to do all the post-AJAX processing inside the success function. See this link for some simple AJAX examples.
Note that you can send data across to the PHP file by specifying a data: parameter in the AJAX code block. Optionally, you can leave out that line and simply hard-code the filename into the PHP file.
The text of the retrieved js file comes back into the AJAX success function (from the PHP file) as a string in the variable specified as the function param (in this case, called 'whatigot'). Do what you want with it; I have stored it inside a hidden <input> control in case you wish to retrieve the text OUTSIDE the AJAX success function.
PHP would look something like this:
loadmyfile.php
<?php
$fn = $_POST['filename'];
$thefile = file_get_contents($fn);
echo $thefile;
References:
PHP file_get_contents

how to use JSON for an error class

Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")

Categories