I have the following code to display links based on the fact that a user is or is not logged:
<?php if(NOT LOGGED){ ?>
<div id="menu"><ul><li><a class="login-button" href="login">LOGIN</a></li></ul></div>
<?php }else{ ?>
<div id="menu"><ul><li><a class="logout-button" href="logout">EXIT</a></li></ul></div>
<?php } ?>
When the "login-button" is is clicked I call a JQuery function that on success will replace it with the following
<div id="menu"><ul><li><a class="logout-button" href="logout">EXIT</a></li></ul></div>
Here is the js
$.ajax({
url: 'login.php',
type: 'POST',
dataType: "json",
success: function (data) {
$('#menu').html('<ul><li><a class="logout-button" href="logout">EXIT</a></li></ul>');
},
error: function (data) {
alert('An Error occurred');
}
});
The problem is that when I click the logout link when it is created by JQuery it doesn´t work.
It only works when the page is refreshed and that is actually replaced by php
Any ideas why?
Not sure it would fix the problem, but your removing the 'ul' in your success function
$('#menu').html('<li><a class="logout-button" href="logout">EXIT</a></li>');
Should be
$('#menu').html('<ul><li><a class="logout-button" href="logout">EXIT</a></li></ul>');
Not sure you are binding the event correctly (as #Lorenzo S says) but this does remind me of an issue I had which was solved by .live:
http://api.jquery.com/live/
Up to quite recently that function was the one you would want but since jQuery 1.7 it has been replaced by .on:
http://api.jquery.com/on/
Related
So what I'm doing is that when someone clicks on search button it loads carousel's html code via ajax call, which is in another file and places under the <div id="filter_product"></div>. And it's css and js is linked in file's header and footer where I am making ajax call. I am calling only html of carousel. Let me show you my code
ajax call is
function submit() {
$.ajax({
method: "POST",
url: "<?php echo base_url() ?>public_controller/search_product",
dataType:'html',
data: {color:color, year:year, cat:cat, brand:brand, model:model},
success: function(data){
console.log(data);
$('#filter_product').html(data);
}
});
}
$(document).on('click','#serch_btn',function(){
submit();
})
controller code is
public function search_product(){
$data['cat'] = $this->input->post('cat');
$data = $this->load->view('public/result_product',$data,TRUE);
echo $data;}
If i don't call carousel code via ajax call and simply place that in index.php it is working fine. but when i call code via ajax call then it's js file is not working and display is scrambled but html is loading fine. is there any way to solve this.
thanks in advance
Function name submit is reserved. You can't use it. Try to rename it.
Suggestion: in PHP method you don't need to echo and base_url() you can use in the next way
public function search_product(){
$data['cat'] = $this->input->post('cat');
$this->load->view('public/result_product',$data);
}
//////////////////////////////////////////////////////////
url: "<?= base_url('public_controller/search_product') ?>",
Put line $('#filter_product').owlCarousel(); after $('#filter_product').html(data); in your AJAX request success function.
I have the following problem happening consistently on my code.
I have a data model with the following function:
data_model.php
public function testFunc(){
return "string";
}
site.php (controller)
public function get_more_data(){
$this->load->model('data_model');
$data['test']=$this->data_model->testFunc();
return $data;
}
home.php (view)
<html>
<body>
<button class="test">test</button>
</body>
<script>
$('.test').click(function(){
$id=1;
$.ajax
({
url: '<?php echo site_url() ?>index/site/get_more_data',
data: $id,
type: 'post',
success: function(result)
{
alert(result);
}
});
});
</html>
However every time I click the button I always get this error:
XMLHttpRequest cannot load http://[::1]/codeignitor/index.phpindex/site/get_more_data. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
What am I doing wrong or not understanding correctly here?
Thanks,
I use ajax in my CodeIgniter projects using the following procedure :
I send data to controllers using queries (like : xxxx.com?id=5)
I receive data using echo in the controller
First, precisions : I'm using MAMP and Brackets, and Chrome to test.
Here's what I have :
<ul>
<li class="brick" data-pseudo="one">Some text or elements</li>
<li class="brick" data-pseudo="two">Some text or elements</li>
<li class="brick" data-pseudo="three">Some text or elements</li>
</ul>
li.bricks are just rectangle articles "linking" to Work1, Work2 and Work3, and generated by a PHP function from an array.
I'm trying to get the "pseudo" data of the clicked .brick to put it in a PHP variable and use it to call another array in another php function, in order to generate the HTML elements of Work1, Work2,...
I found I had to use AJAX and managed to get that code :
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
$('.brick').click(function(){
//some code
pseudo = $(this).data('pseudo');
sendPseudo(pseudo); //calling sendPseudo() function
});
And here's my testing PHP function :
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
... I'm calling in my HTML document :
<section class="site">
<div class="left">
<?php loadWork() ?>
</div>
<div class="right">
//some other content
</div>
</section>
And so I have two problems. Firstly, when a .brick is clicked, the alert pops up but it's empty, absolutely nothing appears in it, but when I console.log the var pseudo, I see "one", "two"... And secondly, the echo in testing PHP function does not generate the paragraph with the pseudo.
Pleeeaaase, help me to find out what I'm doing wrong, it's making me go crazy !
Thank you !
I think there is some confusion in your order. loadWork(), as you say, is part of an html file gets called as soon as the browser reads the html file and it's only called once. If loadWork() hasn't been defined yet (or exists in another file as your AJAX request suggests based on it's call to my_php_function_page.php) then it won't output anything. In other words, loadWork() needs its post data to exist when the browser requests the html.
You can put the php in the same file as the html that is being called on, but it looks like you might be trying to get the results of loadWork() inserted into a div that already exists. Change your ajax function so that if(data!="") changes the inner html of your div to include the data:
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
$('.left').html(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
I think you have missed calling your function loadWork() in my_php_function_page.php, this code may be fix your empty alert issue.
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
data=data.trim(); // to remove the unwanted space around the string
success: function (data) { //testing the success
if(data!="")
{
alert(data);
$(".right").html(data); // This adds your AJAX success data to the class left inside your DIV
}
else
{
alert("You're wrong !");
}
},
});
}
my_php_function_page.php
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
loadWork();
I'm not sure why, but sometimes data function is not working, so I always use attr('data-pseudo') in your case.
so it would be like this:
pseudo = $(this).attr('data-pseudo');
We are creating an administration console, the client will udpate his site by himself.
To do that, we creating div with js and PHP (ajax) :
$(document).ready(function($)
{
function loadContent(page)
{
$.ajax(
{
url: 'contenu/contenu.php',
type: 'POST',
dataType: 'html',
data:
{
'onglet': page
},
success:function(contenu)
{
console.log("success");
$("div."+page).html(contenu);
}
})
};
});
And the PHP code (just a part of it) :
$reponse = $db->query('SELECT * FROM philosophie');
$data = $reponse->fetch();
//maj de la version FR de philosophie
echo '<form action="#" method="POST">
<label>Texte en français :</label><br/>
<textarea name="texte_fr">'.$data["texte_fr"].'</textarea><br/>
<br />
<input type="button" id="maj_philosophie_fr" value="Mettre à jour ce texte" />
<br /><br />';
The form appears on the site, it's working great.
After, I want to know how many button with id beginning with "maj_" are inside the site with this code :
alert($("[id^='maj_']").length);
I still have 0 as reply.
The element is not ready and I'm not able to get a change event on my divs.
I see the elements in firebug (DOM section), the are in red characters.
Have you an idea please ?
Looks like your alert is running before your success function has been called. Try moving your alert inside there, and better yet, throw it in the next event cycle with a setTimeout.
$(document).ready(function () {
function loadContent (page) {
$.ajax({
url: 'contenu/contenu.php',
type: 'POST',
dataType: 'html',
data: { 'onglet': page },
success: function (contenu) {
console.log("success")
$("div."+page).html(contenu)
setTimeout(function () {
alert($("[id^='maj_']").length)
}, 100)
// might even work with 0, if the dom render function
// is the very next thing in the queue
}
})
}
})
If you have to work with many nested ajax calls, you probably want to look into using the promise api. Here are the docs for the jQuery implementation of $.promise()
Making sure your code runs after a success function has been called is not something that can be worked around. The code can't know about the data ahead of receiving it, this means either nesting your success callbacks, or using other solutions like chaining named function callbacks, or preferably promises.
I have a dropdownlist which updates an ajax field. All works fine but the ajax field does not get filled with data on page load. How can I force the ajax field update, on page load?
This is the dropdownlist in view:
echo CHtml::dropDownList('category_selection_code', '', $cat_list_data,
array('style'=>'width:400px',
'ajax' =>
array(
'type'=>'POST',
'url'=>CController::createUrl('articles/GetContentFields'),
'update'=>'#ExtraContentFields',
)
)
);
*UPDATE
I've found the solution which is working for me:
$(document).ready(function(){
$.ajax({
type: 'POST',
data: {category_selection_code: $('#category_selection_code').val()},
url: '<?php echo CController::createUrl('articles/GetContentFields'); ?>',
success: function(data){
$('#ExtraContentFields').html(data)
}
})
})
Controller for ajax processing articles/GetContentFields is waiting category_selection_code parameter in $_POST array. And we should to set it in the data section of ajax part:
data: {category_selection_code: $('#category_selection_code').val()},
Thnx all for the help.
I don't think what you've done above is correct. Firstly, the fourth parameter to CHtml::dropdownList() function is an HTML options array. See the function signature for CHtml::dropdownList()
Put your AJAX call within
$(document).ready(function() {
//Your call goes in here.
});
Fire change event worked for me.
Also, I found useful CHtml::activeId(..) method.
<?php
$cs = Yii::app()->clientScript->registerScript(
'update-brand-car-on-page-load',
'$(document).ready(function() {
$("#'.CHtml::activeId($model, 't_brand_car').'").change();
});'
);
?>
Maybe this will help:
jQuery(function($) {
$('input name["category_selection_code"]').change();
});