I am wondering about how people go about using CodeIgniter and jQuery for AJAX.
In your AJAX request you have
{
url : ???,
data : {a:1,b:2},
success: ....
}
So, how do you build the URL?
Do you
have all your JavaScript in your view files, and just use site_url() to build the URL
have all your JavaScript in external js files, have a header view you include that has something like <script>var base_url = '<?php echo site_url(); ?>';</script>. Then in your external js files have url: base_url+'rest/of/path/';
some other method?
I have my all my js in an external file and load it in my template.
For specific ajax requests, just call the page as you normally would.
$.ajax({
type: 'POST',
url: '/ajax/login',
data: blabla,
success: function(data) {
// do something
},
dataType: 'json');
});
In answer to your question, I've had no need to specify the base url, as putting '/' before the controller name sets the root of the site automatically. You could also use ../ etc
if you are writing your ajax in external file then you can define your base url in the view file like
<script>
var base_url = '<?php echo base_url(); ?>';
</script>
Then on your external ajax file write
url : base_url+'controllerName/functionName',
It can also be done by loading a view that contains your JavaScript.
I currently load JavaScript from a view at the end of the rendered page. Since it is a PHP file with html <script> in it, you can use the URL helper functions like site_url() to generate the URLs you need for each function.
An example view might contain:
<script>
$.ajax{
url : "<?=site_url("controller/function")?>",
data : {a:1,b:2},
}
</script>
That will get you CodeIgniter generated URLs for your JavaScript. You could even pass variables into the view for more control over your js.
Usually I make a small javascript in my header, in which I create a base_url and site_url variable (usually being properties of an object I name CI, but that's a personal preeference). I fill these values by echoing the values with PHP. If you make that the first loaded script, you'll always have the site_url available in JS.
Since I'm on mobile I can't post the source now.
Related
I have a little weird problem
I want to call wordpress ajax url in a custom page.php in public_html
The weird thing is that I have two type of these pages which have two different path :
First one is : the_permalink()/page1
Second one is : the_permalink()/page1/page2
The problem is that the ajax url call is working fine in page1 path : the_permalink()/page1
But same functions with same way of calling is not working in page2 path : the_permalink()/page1/page2
Is there any suggestions ?
Note : i have tested the the SCRIPT code which call the ajax with alert() function and found that that the code stops when it becomes to ajax part is this code :
<script>
$(document).ready(function(){
$('.checknow').click(function(e){
e.preventDefault();
var data = "test";
//alert(ajaxurl);
$.ajax({
type:"POST",
url:ajaxurl,
data: {
action:'action_function_php',
data:data,
},
success:function(data){
$('.security-check-result').html(data);
}
});
});
return false;
});
</script>
Note : i am using wildcard *, so the permalink return is subdomain if this would help
I have also tried to type the url directly but didn't work also
Here is an example page ( will remove it soon ) - just for make things
clear -
https://gameloop.bramj.store/windows
in this page if u tried to search something in the search bar you will find the ajax return works fine
but if you move to
https://gameloop.bramj.store/windows/download
you will notice that every single ajax code in the page is not working.
Thank you so much the problem is solved
i had to put the current main url ( domain/ subdomain ) without any slugs
so the best solution for this case is use this url :
var ajaxurl = "https://<?php echo $_SERVER['HTTP_HOST'];?>/wp-admin/admin-ajax.php";
You need to use wp_localize_script in order to have access to ajaxurl global.
If you don't want to do that then you can replace ajaxurl with <?php echo admin_url('admin-ajax.php');?> if you javascript is inside a PHP file.
I am developing an application in Yii.. One issue i am facing is, when i am writing ajax functions, the url's will be in php. so i am unable to move the codes to another javascript file.
$.ajax({
url: "<?php echo Yii::app()->createUrl('provider/ajaxdetail');?>",
data: {'type':tagtype},
beforeSend: function() { },
success: function(data) {
}
});
so what is the best method to move php out of the javascript so that i can move the javascript code to another js file. I Thought of putting the url's in a hidden box and then call it in the javascript function. but i hope there will be better methods to do this .
please help
you could create a global variable to store the url, in your html head , so that any js file that needs the url can access it, like:
<html>
...
<head>
..
var MY_APP_URL = '<?php echo Yii::app()->baseUrl; ?>'; //can be like www.somesite.com/
....
//load js files
...
and in the js file you could do:
$.ajax({
url: MY_APP_URL + "controller_name/function_name",
data: {'type':tagtype},
OR you could do:
Yii::app()->clientScript->registerScript('helpers', '
someUrl = '.CJSON::encode(Yii::app()->createUrl('blabla')).';
baseUrl = '.CJSON::encode(Yii::app()->baseUrl).';
');?>
and you can use variables someUrl and baseUrl in your Javascript files
I found many examples but I can't figure out how to apply it to my code. I'm adding a wish list button and want users to click it, get an alert that it was added to their member page and continue scrolling through content. I know I need to use ajax to send the variables from the url to javascript and then to php with ajax. But I'm stuck on getting those variables passed to ajax...probably because I'm still learning it. Using the GET in php is easy to get multiple variables but I can't figure out how to do it in javascript. And of course I don't want the page to reload. This is what I'm passing:
<div><a href='wish_list.php?title=".urlencode($title)."&link=".urlencode($link)."'
onClick='wish(this.href); return false;'>Add to Wish List</a></div>
How can I set these variables in javascript? Ajax I would use is:
$(function (){
set variables from url
$.ajax({
type: "POST",
url: "wish_list.php",
data: "$link and $title" //Need help with this here
success: function()...
});
});
I need the link variable to remain encoded because well it's a link. So how do I pull the title and link out of url and pass it to the php file?
js can't access php variables. You could store those values in a hidden html input field and then get it with jquery.
link = $(#IdHiddenField).val();
and then in the ajax function:
data: { link: link}
You'll need at least the basics of javascript and jquery to deal with the ajax functions.
You pass the parameters in the data attribute witch is an javascript object. It would look like this:
data: {"link":"value of link", "title":"value of title", "numbers_too":1},
You have to replace the values of those attributes above with your server side values.
You could put this data into the tag using data attributes:
<div<a class="sender" data-link="<?= $link; ?>" data-title="<?= $title; ?> href="wish_list.php" ... etc.
Then:
$(".data").click(function(e){
type: "POST",
url: $(e).attr("href"),
data: $(e).data()
});
You can add in the ajax function to use directy the "href" from link.
function wish(link){
$.ajax({
type: "POST",
url: link,
data: '',
success: function()...
});
}
With your link:
<div><a href='wish_list.php?title=".urlencode($title)."&link=".urlencode($link)."'
onClick='wish(this.href); return false;'>Add to Wish List</a></div>
Then, you get data from url with $_GET.
<div><a onClick=wish(urlencode($title),urlencode($link));>Add to Wish List</a></div>
function wish(title,link) {
$.post("wish_list.php", { title: title, link: link }).done(function() {
alert("Added to your member page");
});
}
I'm creating an AJAX script that reads a specific file, which name is identified with a GET var. The beginning of the script in index.php is:
var expFile = '<?php echo $_GET['text_name']; ?>';
$(document).ready(function () {
$.ajax({
url: expFile+'.xml',
type: 'get',
dataType: 'xml',
success: function (data, textStatus) {
// Parses the content, which is escaped into a "text" tag in the xml, and puts it
//into an html div with a "content" class"
var content = decodeURIComponent($(data).find('text').text());
$('.content').html(content);
}
});
});
And everything went ok. The file is read and the thing is shown correctly.
The XML file, that is in the same folder of the index.php file, is read directly from AJAX.
Now i'm using a mod_rewrite in order to make the URL SEO-Friendly.
When i type the dirty URL (http://www.mysite.com/index.php?text_name=name-of-the-file-to-read) it's OK.
But when i type the rewritten url (which is http://www.mysite.com/lyrics/name-of-the-file-to-read) the content is not shown.
I know that AJAX is client-side, while mod_rewrite is server-side, but I don't know how to reach a parent folder (that really doesn't exist) from the "url" parameter of the $.ajax or an absolute link like url: 'http://...' (but it goes against Same Origin Policy).
Help me please!!!
Francesco's answer, initially put into the question:
SOLVED.
THE PROBLEM was with the script tag. I had to put a ../ to the jquery href
<script type="text/javascript" src="../libraries/jquery.min.js"></script>
Then I added ../ to the URL and everything went fine.
The URL is having .xml appended by the function itself - on this line:
url: expFile+'.xml',
Is that still there when you are trying with the SEO friendly URL? If so, I'd remove that appended .xml and try again.
I have a website, that uses PHP to select the content,
<div>
<? include ("navigation.php"); // navigation.php generates the menu ?>
</div>
<div>
<?
$type = $_GET["type"];
switch ($type) {
case "page" :
include "Text.php";
break;
case "news":
include "news_2.php";
break;
default :
include "main.php";
}
?>
</div>
The url is of the format domain.com/index.php?type.
I need to change the block #content without reloading the whole page, how can I do this?
As you've tagged the question with "jquery" I assume you know what that is, and that you're loading it into your page.
All you need to is give your div and ID... content here
And then use a bit of jquery.. in its simplest form just to load your content from 'myurl.php' into 'mydiv' when the page has finished loading:
$(document).ready(function() {
$("#mydiv").load("myurl.php");
});
You'll no doubt want some logic to determine what loads, and under what circumstances. If you need to pass data back to the URL then you'll need to go for jquery ajax ($.ajax). Its all pretty easy, loads of examples on the web, and good docs on the JQuery website.
This would best be done with Ajax. I like using jQuery's ajax function. Something like this:
function load(page){
var datastring='ANY DATA YOU WANT TO SEND';
$.ajax({
type: "POST",
url: 'your/pagehtml/',
data: "bust="+Date()+datastring,
dataType: "html",
cache: false,
success: function(html){
$('#content').html(html)
}
});
return false;
}
You wouldn't need to send the page in the URL this way. Anytime you change the url, you must be loading a different page. Outside of .htaccess rewrite. Which isn't what you need.
Fire this on click or whatever you want.
If you're using jQuery, it's pretty easy. You didn't post what is supposed to trigger the change, so I'll assume you have a list of links in another element with an id of nav.
Read more about the jQuery Ajax request here: http://api.jquery.com/jQuery.ajax/
//run on page load
$(function(){
//bind a click event to the nav links
$("#nav a").bind("click", function(e){
//keep the links from going to another page by preventing their default behavior
e.preventDefault();
//this = link; grab the url
var pageLocation = this.href;
//fire off an ajax request
$.ajax({
url: pageLocation,
//on success, set the html to the responsetext
success: function(data){
$("#content").html(data.responseText);
}
});
});
});
I'd also suggest doing some code cleanup like caching your $("#content") element on the load event (something like window.container = $("#container"), and using window.container later on), but I left it as-is so that everything remains clear.