how can i post data in Codeigniter using Ajax - php

How can i post data in Codeigniter using Ajax, am so confused this is the first time i do ajax and Codeigniter together
here is my ajax code
i tried to send the data to the controller method ;
This is my ajax
$(document).ready(function(){
$('#register_form').submit(function(evt){
var postData = $(this).serialize();
$.ajax({
url: baseURL+"admin/Products/add_product",
type:'post',
data:{productData:postData},
success:function(data){
}
});
});
});
this is my form
<?php $attribute = array( 'id'=>'register_form','form-horizontal'); ?>
<?php echo form_open('admin/products/add_product',$attribute); ?>
<?php echo form_label('product title'); ?>
<?php echo form_input($data_product_title); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product description'); ?>
<?php echo form_textarea($data_product_description); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product price'); ?>
<?php echo form_input($data_product_price); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_label('product quantity'); ?>
<?php echo form_input($data_product_quantity); ?>
<h6 style="color: red" class="require_error">this filed is required</h6>
<?php echo form_submit($data_3); ?>
<?php echo form_close(); ?>

Hope this will help you :
Your ajax script should be like this : , make sure your URL is correct
$(document).ready(function(){
$('#register_form').submit(function(evt){
var postData = $(this).serialize();
$.ajax({
url : baseURL+"admin/Products/add_product",
type:'post',
data: postData,
success:function(data)
{
console.log(data);
}
});
evt.preventDefault();
});
});
In your add_product method get post values like this :
public function add_product()
{
print_r($this->input->post()); // to print all post values
exit;
}
For more : https://www.codeigniter.com/user_guide/libraries/input.html

`$('#add').click(function() {
var form_data = {
subject_name: $('#subject_name').val(),
section: $('#section').val(),
grade: $('#grade').val()enter code here
};
$.ajax({
url:"<?php echo site_url('ViewCourses/SavingData');?>",
type:'POST',
data: form_data,
success: function(msg) {
if (msg == 'Yes')
document.location.reload(true);
else if (msg == 'No')
document.location.reload(true);
else
$('#alert-msg').html('<div class="alert alert-danger">' + msg+'</div>');
}
});
return false;
});`
add Its Button Id Pe Use Of Onclick Function For Submit values With Ajax
form_data All Form Fields Of the Form

Related

how to built ajax tabs in wordpress?

I try to display the departments in my website as tabs, when click one tab it will display the data related to this department according to department_id.
I try this code Execute php function only when clicked (wordpress) but I need the tabs number to be dynamic.
<div class="tabs">
<ul>
<?php
$arr1=array(2,3,5,10,22,25,27,28,29,30);
$arr2=array("dep1","dep2","dep3","dep4",
"dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++){?>
<li><a href="#tab" id="<?php echo $arr1[$i]; ?>"><?php echo
$arr2[$i];?>
</a></li>
<?php } ?>
</ul>
</div>
<div id="tab" class="section">
</div>
functions.php:
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here I print data according to $dept_id **/
die();
}
?>
script.js:
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab').html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });
it dose not work, it displays data only for one tab.
console.log(tab_id) ----> it display the id for the first tab clicked
and did not change when click another tab.
You need to echo the output from the tabsfunction and also add the die() at end of the function like below :
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id=$_GET[id];
/** Here display data according to $dept_id **/
echo 'output';
die();
}
Hope it helps.
can you please correct your tab list code.
<div class="tabs">
<ul>
<?php
$arr1 = array(2,3,5,10,22,25,27,28,29,30);
$arr2 = array("dep1","dep2","dep3","dep4","dep5","dep6","dep7","dep8","dep9","dep10");
for($i=0;$i<10;$i++)
{
?>
<li><?php echo $arr2[$i];?></li>
<?php
}
?>
</ul>
</div>
<?php for($i=0;$i<10;$i++)
{
?>
<div id="tab<?php echo $arr1[$i]; ?>" class="section">
</div>
<?php
}
?>
Also return proper response on ajax request.
<?php
add_action('wp_ajax_tabsfunction', 'tabsfunction');
add_action('wp_ajax_nopriv_tabsfunction', 'tabsfunction');
function tabsfunction() {
$dept_id = $_GET[id];
echo $dept_id; // this just dispay requsted id as tab content here you can add your logic for dynamic content based on id
die();
}
?>
And your script js look like this
jQuery(document).ready(function() {
jQuery('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = jQuery(this).attr('id');
console.log(tab_id);
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'tabsfunction', id: tab_id}),
success: function(data){
jQuery('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
} });}); });

refresh an included page

I have a page index.php
Inside of it is a friendlist that updates the db with a button click without refreshing the page. Now I want that only the friendlist refreshs so its updated
<html>
<body>
<?php
include ("friendlist.php");
?>
</body>
</html>
friendlist.php:
<script>
function adduser() {
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "addfriend.php",
data: data,
dataType: "html",
success: function(data)
{
//refresh myFriendlist or requser so its updated
}
});
}
</script>
<div id="myFriendlist" class="friendlist-content">
<?php if(!empty($request)) { ?>
<div id="req">
<h2 id="reqh">Anfragen</h2>
<?php foreach($request as $row) {
$row['userAname'] = (strlen($row['userAname']) > 5) ? substr($row['userAname'], 0, 5) . '...' : $row['userAname'];
?>
<div id="requser">
<a class="reqimg" style="padding:0px;" href="user.php?id=<?php echo ($row['id']);?>">
<img class="reqpb" src="./users/<?php echo ($row['userAid']); ?>/pb.jpg" alt="Bild nicht gefunden" onerror="this.src='./img/no_pb.png';"></img>
</a>
<a class="reqnm" style="padding:0px;" href="user.php?id=<?php echo ($row['userAid']);?>"><?php echo $row['userAname']; ?></a>
<img id="aimg" src="./img/accepticon.png">
<form id="adduserform" name="adduserform">
<input type="hidden" id="reqid" name="reqid" value="<?php echo $row['userAid'];?>" />
<input type="hidden" id="reqnm" name="reqnm" value="<?php echo $row['userAname'];?>" />
</form>
<img id="aimg" src="./img/dntaccepticon.png">
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
How can I do that?
You can refresh an external file using ajax. For example, if you had a div with the id "friendslist" you could refresh its contents this way:
$.ajax({
url: "friendlist.php"
}).done(function(response) {
$( '#friendslist' ).html( response );
});
The documentation for ajax is on the jQuery site here: http://api.jquery.com/jquery.ajax/.
If you can make "addfriend.php" to return the new complete list of users, so that would be:
<?php foreach($request as $row) {
$row['userAname'] = (strlen($row['userAname']) > 5) ? substr($row['userAname'], 0, 5) . '...' : $row['userAname'];
?>
you could use that response, which you will receive when you do the AJAX call, to refresh the friendlist, using the jquery HTML function (http://api.jquery.com/html/)
you can follow this code but not tested
first update your index.php
<html>
<body>
<div id="friendlist">
<?php
include ("friendlist.php");
?>
</div>
</body>
</html>
then update your addfriend.php as like
<?php
// your code here
// then include your frindlist.php content
include 'yourpath/frindlist.php'
?>
then update your javascript code like this
function adduser() {
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "addfriend.php",
data: data,
dataType: "html",
success: function(data)
{
$('#friendlist').html(data);
}
});
}

How to get div value dynamically with jquery and php

I have to get the value of something when I press an accordion div. This div=" accordion" has this structure:
<div class="accordion">
<? if ($_SESSION[SITE]['user']['id'] == $message['yp_from']) { ?> <div class="row"><span class="bold">From: </span> <span>Me</span>
<span class="grey9"> <?= $this->tools_lib->date_format($message['yp_time']); ?></span>
<? } else { if ($message['yp_state_from'] == 0) {?>
<div class="row"><span class="bold">From: </span><span><?= $this->tools_lib->name_separate($message['yp_name']) ?></span>
<div id="idMens<?= $message['id'] ?>" style="display:none;" class="showNew"><?= $message['id'] ?></div></span>
<h5 id="new"> New </h5>
<?} else { ?>
<div class="row"><span class="bold">From: </span><span><?= $this->tools_lib->name_separate($mensaje['yp_name']) ?></span>
<? }
} ?>
</div>
<p><?= $message['yp_message'] ?><p>
</div>
I want to get · $mensaje['id'] · value from the "div id="idMens"". I was trying to do it with jquery. but I have problems to get the correct value, it always take the first item value, I mean the last dinamically typed.
Im trying to use this jquery code. but I think is not well formed code..
<script>
$(document).ready(function(){
$('.accordion').find('div').click(function(){
$(this).next().slideToggle();
$('.showNew').on('click', function() {
var idm =this.id;
});
var form_data = {
to: $('#',idm).html()
}
$.ajax({
url: _baseurl+""+_lang+"/messages/updateState/", // ruta del controlador y accion
type: 'POST',
data: form_data,
success: function(data){
$('#new').hide();
}
});
}).next().hide();
});
</script>
Thank you!
Finally I did it. I'm fool... it was so easy. I was in the wrong way.
I did it creating other function:
function changeState(id){
var form_data = {
to: id
}
$.ajax({
url: _baseurl+""+_lang+"/messages/updateState/", // ruta del controlador y accion
type: 'POST',
data: form_data,
success: function(data){
$('#new').hide();
}
});
}
And calling it in the first div. with onclick. I pass the dinamic id as a parameter and therefore I can use it well.
Thank you

Reload Specific <div> of page during ajax call

I got stuck on the following issue. the issue is, I want to reload particular div of my page that also contain PHP script. My javaScript function is
function select_dayoff() {
jQuery('#loader').css('display','block');
var site = "<?php echo SITE_NAME.ROOT_FOLDER_NAME ?>"+"fschedules/dayoff";
jQuery.ajax({
type: "POST",
url: site,
data: "&fulldate="+MyDayoff.dayof,
success: function(msg){
jQuery('#loader').css('display','none');
}
});
}
and DIV is:
<span id="fill_available_time">
<?php $form->create(MEMBER_DAYOFF,array('id'=>'saveCancelDay','name'=>'saveCancelDay', 'type' => 'post', 'url'=>'/fschedules/dayoff')); ?>
<div class="profile">
<?php
if(!empty($dayoff_time)){
foreach($dayoff_time as $key => $val){
$res_dayoff_time[$val[MEMBER_DAYOFF]['dayoff']] = $val[MEMBER_DAYOFF]['dayoff'];
}
//echo $form->input('id_state',array('label'=>'','type'=>'select','id'=>'state_id', 'options'=>#$res_business_state, 'empty'=>'Please select...' ,'class'=>'required'));
//echo '<h2>Select date for cancel dayoff</h2>';
echo $form->input('dayoff_time', array('label'=>'','type'=>'select','id'=>'dayoff_time', 'options'=>$res_dayoff_time, 'empty'=>'Please select...' ,'class'=>'required' ,'onchange'=>'','style'=>'margin-left: 14px;'));
echo $form->submit('Cancel Dayoff', array('type'=>'submit','name'=>'saveCancelDay','id'=>'saveCancelDay'));
}else{
echo '<h2>No Dayoff is registered.</h2>';
}
?>
</div>
<?php $form->end(null); ?>
</span>
I want to refresh this DIV during above Ajax call.
Thanks in advance for any help.
create a html file xyz.html and add the html code
<?php $form->create(MEMBER_DAYOFF,array('id'=>'saveCancelDay','name'=>'saveCancelDay', 'type' => 'post', 'url'=>'/fschedules/dayoff')); ?>
<div class="profile"><?php
if(!empty($dayoff_time)){
foreach($dayoff_time as $key => $val){
$res_dayoff_time[$val[MEMBER_DAYOFF]['dayoff']] = $val[MEMBER_DAYOFF]['dayoff'];
}
//echo $form->input('id_state',array('label'=>'','type'=>'select','id'=>'state_id', 'options'=>#$res_business_state, 'empty'=>'Please select...' ,'class'=>'required'));
//echo '<h2>Select date for cancel dayoff</h2>';
echo $form->input('dayoff_time', array('label'=>'','type'=>'select','id'=>'dayoff_time', 'options'=>$res_dayoff_time, 'empty'=>'Please select...' ,'class'=>'required' ,'onchange'=>'','style'=>'margin-left: 14px;'));
echo $form->submit('Cancel Dayoff', array('type'=>'submit','name'=>'saveCancelDay','id'=>'saveCancelDay'));
}else{
echo '<h2>No Dayoff is registered.</h2>';
}
?></div>
<?php $form->end(null); ?>
function select_dayoff() {
jQuery('#loader').css('display', 'block');
var site = "<?php echo SITE_NAME.ROOT_FOLDER_NAME ?>"
+ "fschedules/dayoff";
jQuery.ajax( {
type :"POST",
url :site,
data :"&fulldate=" + MyDayoff.dayof,
success : function(msg) {
jQuery('#loader').css('display', 'none');
$('#fill_available_time').load('xyz.html')
}
});
}

Jquery, ajax and problem with load

This is the HTML part:
div id="messages">
<div class="messages">
<?php if(isset ($unread)) { ?>
<p>You have <?php echo $unread?> unread messages.</p>
<?php } ?>
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
<?php } ?>
<?php } ?><!-------- end of if $message-------->
</div><!------ end of div .messages--------->
</div><!------ end of div #messages--------->
and JQ:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>");
});
});
}
});
return false;
});
Code is working, but when it comes to the load nothing is being shown. I did
load("<?php echo site_url('messages/show') ?>", function() {
alert('Load was performed.');
});
and there was an alert, and when I look page source I can see that the content has been changed, but it is not displayed.
When you view the source of a page that has been loaded via AJAX, it will never update. You will need to inspect the DOM in order to see what has changed.
The reason is because the content is not actually on the page and is being dynamically added to the page.

Categories