What is the better way to deal with urls in ajax calls made in javascript files present in the webroot and because of that, are not interpreted by PHP?
I'm using CakePHP and require.js and therefore would not put the javascript code directly in views. The only way I found was to declare a variable in the layout that receives the value of the webroot like this:
<script>var webroot = "<?php echo this->Html->url('/') ?>" </script>
And then in my js files I hardcoded the urls to the ajax calls like this:
$.getJSON(webroot + 'users/list', function(){ ... } );
But it does not solve the problems if there are changes in the Routes file. I generally change the routes to be more friendly after I finished the project and this would cause a big problem if I have many ajax calls or urls been referenced in js files.
I usually work this way:
In my layout header I add the following before any other javascript is included:
<script type="text/javascript">var baseUrl = '<?php echo $this->base; ?>';</script>
Then at my javascript files I do this:
$.post("http://"+ document.domain + baseUrl +"/controller/action.json");
use
echo Router::url(array('controller' => 'Users', 'action' => 'list'));
Will output;
/Users/list
in js
$.post({url : "<?php echo Router::url(array('controller' => 'Users', 'action' => 'list')); ?>"})
I think you’re working against CakePHP’s conventions if you’re wanting to display your app’s data in JSON format. Have a look at the CakePHP cookbook entry on JSON and XML views.
Related
I'm making a change to the way a site works and trying to find a solution that requires as little re-writing as possible.
At the moment, I have a file (myFile.php) which loads (using Wordpress) into a page. It uses a PHP array for outputting data. The PHP array is $property_list_featured_search and the content looks something like this:
<?php
foreach($property_list_featured_search as $individual_property){
?>
<span><?php echo $individual_property['info']['status'] ?></span>
<?php
}
?>
So in my small example, it's outputting data from $property_list_featured_search and this works OK.
My problem is that I now want to load the HTML&PHP above using jQuery AJAX. When a user clicks a button, it loads the HTML (which is stored in a file, called myFile.php into a div on the page:
function loadView(view){
$.ajax({
type: "POST",
url: 'path/to/file/property-search/myFile.php',
data: property_data,
success: function(result)
{
$("#search-page-content").html(result);
});
}
In the case above, property_data is the $property_list_featured_search data localized using Wordpress so that the file can access it. I have tested it and can confirm that the file loaded in with AJAX is able to see the data. My problem is that I now have a file with PHP echo everywhere and the data in JSON format.
Is it possible to still use this data in this way? I'm guessing because the data is JSON that it's not possible to use echo $data[key] at all like it was in the original file?
What's the best way to output all the data in the JSON file on the page?
You can try something like this:
When u get your data:
$checked = $_POST['property_data'];
$checked = array('first' => $checked[0], 'second' => $checked[1], 'third' => $checked[2], 'forth' => $checked[3]);
Then you can echo it like this:
$checked['first'], $checked['second'] and so on.
Hope this helps
I would need to echo php variables (from the server and related to service behaviour) into javascript. For example, "ssl" => "true" and adapt accordingly in javascript. The thing is I'm doing this for some API files I'm writing and I want the client to have direct access to these files (<script src="... .js">) and this forces me to hardcode info that might change in the future across multiple file references. What I'd like to do was something like this, is it possible? (the content to fetch must remain completely private - from the server folders to the php script files - and so it is really not an option to fetch this info using javascript):
api.js
<? //PHP here. (I know...)
(...)
?>
//some javascript
var is_secure = <? echo "true"/"false" ?>
(...)
So that when doing <script src="api.js"/> the user only fetches:
var is_secure = "true";
(...)
or
var is_secure = "false";
(...)
Any idea on how I could do something similar? Thank you very much...
You could just create your PHP file with this line before everything :
header("Content-Type: application/javascript");
EDIT:
I did misunderstood the question. If you want js in an php file, you should do it like this:
header("Content-Type: application/javascript");
OLD ANSWER:
I don't know if you know, but client can't see your php code...
So if You'd:
echo "Something"
The client would only see Something.
It's not clear, what you're trying to do...
If you don't want to see Something when you go directly into your "secret" php page, then you should do it like this:
JS:
jQuery.ajax({
type: "POST",
url: 'secretfile.php',
dataType: 'html',
data: {apiRequest: 1},
success: function (response) {
yourVar = response;
}
});
PHP:
If ($_POST['apiRequest']==1){
echo "Something";
}
yourVar would be = "Something"
If you'd go to this page, it wouldn't display anything;
I have a CHTML:ajax function that does some AJAX stuff on a select dropdown - I simply want to do something which says..
"on change, grab the selected value & pass that as param childID in the URL"
This should then display the following in the url section of the
CHTML::ajax function:-
'url' => 'isAjax=1&childID=5134156'
I've tried to append the variable selected onto the url but it doesn't work - can anyone see what I'm doing wrong
jQuery(function($) {
$('#child-form select[name="Child[user_id]"]').bind('change', function(e){
var selected = this.value;
console.log('selected : '+selected ); // outputs an ID to the console.
<?php echo CHtml::ajax(array(
'url' => '?isAjax=1&childID='+selected,
'type' => 'post',
'update' => '#parents-sidebar',
// rest of the ajax function (quite long...)
You can't take a value extracted from the dom using javascript and inject it directly into PHP code.
From the PHP.net documentation:
Since Javascript is (usually) a client-side technology, and PHP is
(usually) a server-side technology, and since HTTP is a "stateless"
protocol, the two languages cannot directly share variables.
CHtml::ajax() is primarily a shortcut for generating javascript code. So the easy solution would just be to write your javascript manually. That will allow you to use your selected variable.
Note:
You might try Taron Saribekyan's solution, posted in the comments. The idea is that the javascript expression ('...+selected') will be printed by PHP as a string, and thus be evaluated by javascript. In theory, this should work.
That is obvious. You have defined a javascript variable and you are using it in your php code! Everything inside <?php ?> block, will interpret on the server and before javascript. So, I think you should use normal jquery ajax method in your case. Something like this:
$.ajax({
"url": <?php echo Yii::app()->baseUrl.'/controller/action' ?>'?isAjax=1&childID='+selected,
'type' => 'post',
...
})
I want to use jquery ajax to change the content of my div elemnt by requiring different php files.
here is the ajax code :
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num
},
success:function(result){
$("#right_bot").html(result);
}
});
the project_functions.php would be something like :
$result = '<?php require "Panels/Project/Main/main.php" ?>';
echo $result;
I can see the value being outputted , but the html comment out the php part
<!--?php require "Panels/Project/Main/main.php" ?-->
It just comments out the php. Is there a way i load different php files into my div ?
In the main.php file , It has php code , html code , and some style tags. Can I use ajax to load all this into the div element ? or I have to echo all my html code ?
You can't do this like that. What you want is that all PHP is excecuted on the server and only the result has to be returned.
You can't send php-code back to javascript and try to run it there, PHP is a serverside language, it will only work on the server. Javascript is clientside, it will only run in the browser.
If you where to send <?php echo 123; ?> back to Javascript, you'll get exactly that as result, not 123.
The solution in your case is to make project_functions.php really require it. This will include the main.php, all it's functions and output.
require "Panels/Project/Main/main.php";
Some suggested reading:
http://www.codeconquest.com/website/client-side-vs-server-side/
A trick which might help you: Paste the link to your urlbar, and add the variables to it. The result you get in your screen is what Javascript will output. Note: This only works for method=get, not post.
In this case browse to /project/Functions/project_functions.php and do the simple require per my code above. That output will be send to Javascript.
Send a parameter in the ajax request 8for example type):
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num, type: "main"
},
success:function(result){
$("#right_bot").html(result);
}
});
And then in php-file get the type variable:
if($type == "main") {
require "Panels/Project/Main/main.php"
}
else {
require "Panels/Project/Main/sthelse.php"
}
You should also have some sort of same function name or something to output the results of the file;
<?php
function printResult() { }
echo printResult();
Try:
$result = file_get_contents('Panels/Project/Main/main.php');
Fellow Coders,
so far I have been using the CI url helper to build full urls using base_url() and site_url(). Now I'm trying to access a controller function within some javascript code that will be loaded as a js file.
it's actually an ajax call with a url parameter that should be something like:
url : '/account/check_user'
now unless i prefix the url with the full path as ins http://servername/..... the code fails.
all the code examples i've seen use the short version of the url but i cannot get it to work. I'm sure this is really simple but i'm stuck.
i could pass a hidden form field to the js code but i'd rather not. any ideas?
thanks
Well, I also tend to use absolute URLs and a good practice I always do is declaring a JS variable:
var base_url = "<?php echo base_url(); ?>";
In:
the head section
as the first line of my script tag
if I have a main.js file that holds most of my JS code AND it's always included in my views, then I put that line first thing in the file.
After that, you use it like:
url : base_url + 'account/check_user'
Anyway, the first slash / in your url tells the browser to go to the URL root which would not be the right place to put your url chunk in! for example:
if your CI installation is in ci folder and your URL is: domain.com/ci/contorller/method/
Then your URL will become: domain.com/contorller/method/!!
I'm usually assigning the base_url() to a JS variable right in the head to have it available to all methods. Something like this
<script type="text/javascript">
var baseUrl = "<?php echo base_url() ?>";
</script>
You should actually be using CI's site_url() function. base_url() is useful for generating a URL to a resource (such as script or stylesheet), but site_url() is the best choice when generating a URL to a page within the app itself, such as when making an Ajax request, as described.
So the best code to use would be something along these lines:
<script type="text/javascript">
var site_url = "<?php echo site_url() ?>";
</script>