YII: How to update ajax data on page load? - php

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();
});

Related

JS file not loading via ajax call

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.

Send a variable to a PHP page and open the page in new tab

I've this code
$(document).on('click', '#button', function(){
var my_data = 'Test Test Tes';
$.ajax({
type: "POST",
url: "preview.php",
data: "my_data=" + my_data,
success: function() {
window.open('preview.php');
},
});
});
Above codes open the preview.php but I'm getting this error -
Notice: Undefined index: my_data in
C:\xampp\htdocs\tb-builder\preview.php on line 3
This is what I've in preview.php -
<?php
$data= $_POST['my_data'];
echo $data;
?>
Can anybody help me to solve this please? Thanks
Main error is , window.open('preview.php'); loads the page preview.php ,
You are not sending any data with post/get request while loading it using
window.open('preview.php'); and you are expecting value at $_POST['my_data']
$(document).on('click', '#button', function(){
var my_data = 'Test Test Tes';
$.ajax({
type: "POST",
url: "preview.php",
data: "my_data=" + my_data,
});
});
preview.php
<?php
if(isset($_POST['my_data']){
$data= $_POST['my_data'];
header('location:preview.php?my_data=$data'); //reload preview.php with the `my_data`
}
if(isset($_GET['my_data'])){
$data=$_GET['my_data'];
echo $data; //display `my_data` as you requested
}
?>
Update
With out using ajax ,to achieve what you required.
$(document).on('click', '#button', function(){
var my_data = 'Test Test Tes';
window.open('preview.php?my_data='+my_data);
});
preview.php
<?php
if(isset($_GET['my_data'])){
$data=$_GET['my_data'];
echo $data;
}
?>
final Update
Actually you don't need ajax at all , because you are going to another page with the data .
to avoid get request
Wrap the button inside a form with hidden input having value
my_data and set action="preview.php" like below
<form action="preview.php" method="post">
<input type="hidden" id="my_data" value="Test Test Tes">
<button type="submit" id="button">post</button>
</form>
use
if (isset($_POST['my_data']))
{
$data= $_POST['my_data'];
echo $data;
}
Please change your preview.php code with the following :-
<?php
if (isset($_POST['my_data']))
{
$data= $_POST['my_data'];
echo $data;
}
?>
It may help you.
It was completed question in
Is your error in new window ?? – HoangHieu 1 min ago
yes. in new window – Xahed Kamal
First Ajax post it completed when success: function called... In new window you doesn't have any post data, I don't know any solution post data by javascript to new window.. only one you can send data by GET request ..
window.open just create a new window object. That window will have no $_POST globals. Use window.open('preview.php?my_data=' + my_data); and use $_GET['my_data'] in that PHP.
The post is related to the ajax not for the new window.
EDIT
Ok guys, I see here is a little confusion.
Above codes open the preview.php but I'm getting this error -
So what happens?
OP is sending a data called my_data to the preview.php. This data is travelling through $_POST to the preview.php. At this point, there is $_POST['my_data'];
When it finish with success, the ajax call, then the window.open opens a new window, what has no $_POST data, this is why OP get this error message.
If he want to use the same data what he posted in my_data then he need to add it to the URL and use $_GET.
I think the misunderstood was what #HoangHieu wrote and me pointed:
yes. in new window – Xahed Kamal
And if you want to use response, then use
success: function(reponse) {
window.open('preview.php?my_data=' + response);
},
and then use $_GET['my_data'] in new window.
Your construct:
data: "my_data=" + my_data,
Is wrong. It should be:
data: {my_data: $my_data},
And I changed your JS variabale to $my_data, so it's less confusing.

how to run php function without reloading the page

I am a newbie to php
<?php
getDBData(){
//log the call
$fetchedData = myDbCode.fetchData();
return
}
?>
<script type="text/javascript">
dbData = <?php echo json_encode(getDBData()); ?>
</script>
As observed in the log that getDBData get called only once during the page loading and later on even with dbData = <?php echo json_encode(getDBData()); ?> this code the call to getDBData() doesn't happen.
Any idea why the call to getDBData() happening only on page load and not thenafter
How to call getDBData() from javascript
You don't actually understand, how it works.
Javascript is a client-side language, which means, that it executes in web browser.
PHP is server-side which mean it executes on server.
While handling request, first PHP is executed, that the response is returned to user, and then Javacript executes.
To communicate between client and server you can use ajax requests, which are basically simple http requests but without reloading whole page.
You should use Ajax for that. I.e. you have a php file which returns the output of the function:
// data.php
<?php
function getDBData(){
//log the call
$fetchedData = myDbCode.fetchData();
return $fetchedData;
}
echo getDBData();
?>
// html file
<script type="text/javascript">
var getDBData = function(callback) {
$.ajax({
url: "data.php"
}).done(callback);
}
var dbData = <?php echo json_encode(getDBData()); ?>
getDBData(function(data) {
dbData = data;
})
</script>
The code above uses jQuery.
you can used AJAX for get server side php vaue into javascript variable read this ajax example and implement it.
// Launch AJAX request.
$.ajax(
{
// The link we are accessing.
url: jLink.attr( "href" ),
// The type of request.
type: "get",
// The type of data that is getting returned.
dataType: "html",
error: function(){
ShowStatus( "AJAX - error()" );
// Load the content in to the page.
jContent.html( "<p>Page Not Found!!</p>" );
},
beforeSend: function(){
ShowStatus( "AJAX - beforeSend()" );
},
complete: function(){
ShowStatus( "AJAX - complete()" );
},
success: function( strData ){
ShowStatus( "AJAX - success()" );
// Load the content in to the page.
jContent.html( strData );
}
}
);
// Prevent default click.
return( false );
}
);
You can do it through ajax.
Here is a link here to do it with jquery : using jquery $.ajax to call a PHP function
use jquery
$.ajax({
url: 'yourpage.php',
type: 'POST',
data:'',
success: function(resp) {
// put your response where you want to
}
});
You can't directly call PHP functions from javascript.
You have to "outsource" the getDBDate to an own .php file where you output the json_encoded string and call this file with ajax and get the output of the page.
The easiest to do AJAX requests in javascript is to use the JQuery Library: http://api.jquery.com/jQuery.ajax/

ajax wont execute php function

I'm trying to create a login form with ajax, but the php event handler never start, if i use the METHOD POST form, the function works without a problem.
I have debugg the function, and the ajax form is sending httprequest.
Any ideas?
this is my ajax.
$(document).ready(function() {
$('#login').click(function() {
var login_email = $('#login_email').val();
var login_password = $('#login_password').val();
$.ajax({
url: 'core/manageusers.php',
type: 'POST',
data: {
login:login_email,
login_email:login_email,
login_password:login_password
},
success: function() {
location.reload();
}
});
});
});
Eventhandler.
if(isset($_POST['login']))
{
include_once('core/class.users.php');
$email = $_POST['login_email'];
$password = $_POST['login_password'];
}
login:login_email,
login_email:login_email,
login_password:login_password ,
},
That wayward comma at the end of login_password:login_password will break it, but probably not your only problem
remove ',' from the end of 'login_password:login_password ,'
You have a syntax error in the creation of ajax request :
data: {
login:login_email,
login_email:login_email,
login_password:login_password **,**
},
remove this comma
Works as designed: If you are retrieving Data in PHP with $_POST, nothing will happen if you are accessing with a GET Request.
The AJAX actually sends POST as from your code above.

CodeIgniter AJAX: POST not working, GET works fine

Fiddling inside CodeIgniter and trying to get a grip on it all as I've never worked with AJAX before.
For some reason, my AJAX is working perfectly when I use the GET method, but if I switch it over to the POST method, it stops working.
My JS:
$(document).ready(function(){
$('.love').click(function(event) {
$.ajax({
type: 'GET',
url: base_url + '/ajax/love_forum_post',
data: { post_id: 2, user_id: 1, ajax: 1 },
});
return false;
});
});
And my CONTROLLER:
function love_forum_post()
{
$post_id = $this->input->get('post_id');
$user_id = $this->input->get('user_id');
$is_ajax = $this->input->get('ajax');
if ($is_ajax)
{
$this->load->model('forums_model');
$this->forums_model->add_love($post_id, $user_id);
}
// If someone tries to access the AJAX function directly.
else
{
redirect('', 'location');
}
}
If I switch the type to 'POST' inside my JS and then catch it on the other end with $this->input->post() it doesn't work.
Any suggestions?
I have tested your code in 2 scenarios:
first - without csrf protection, and I see no reason for your code not to run properly.
To be able to test it easier, append $.ajax call with success response.
Something like this
success: function(response) {
alert(response);
}
And add response to your love_forum_post method.
echo print_r($this->input->post(), true);
This would give you clean view of what it going on in your method.
In my installation everything works just fine.
Second scenario is with csrf protection.
In this case add new param to your post object.
<?php if ($this->config->item('csrf_protection') === true) : ?>
post_data.<?php echo $this->security->get_csrf_token_name()?> = '<?php echo $this->security->get_csrf_hash()?>';
<?php endif ?>
This would make CI accept post from this url.
Hopefuly it would help.
Cheers
By any chance you have csrf_protection enabled?
If yes you need to send the token and the value key as post parameter along with post request.
Try to use this
$post_data = $_POST;
and print the post data using this
print_r($post_data);die();
and you can see there if you catch the post data;
Gudluck!!

Categories