I have this dropdown menu using form_helper in CodeIgniter:
<?php if($materialType): ?>
<?php
$material_options = array();
foreach($materialType as $rows){
$material_options[$rows->id] = $rows->category;
}
echo form_dropdown('materialType',$material_options,'','id="materialType"');
?>
<?php endif; ?>
<div id="materials"></div>
The code above is inside a <form> tag and I have this script:
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<script>
$(document).ready(function(){
$(document).on('change','#materialType',function(){
loadthis();
});
function loadthis(){
var ID = $('#materialType').val();
var dataString = 'id='+ ID ;
$.ajax({
type: "POST",
url: base_url + "index.php/admin/get_material",
data: dataString,
cache: false,
success: function(data)
{
$('#materials').html(data);
}
});
}
loadthis();
});
</script>
And here is the code that is being loaded:
<div id="materials">
<?php if($materials): ?>
<table>
<th>Name</th>
<th>Description</th>
<?php foreach($materials as $row): ?>
<tr>
<td><?php echo $row->mname; ?></td>
<td><?php echo $row->mdesc; ?></td>
<td>
<button class="try" value="<?php echo $row->id; ?>">Add</button>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<div class="alert alert-error" style="width:300px;">No Resource Available!</div>
<?php endif; ?>
$(document).on('click','.try',function(){
alert($(this).val());
return false;
});
And what i want is if the Add button is being click I can get the ID,mname and store it until the form is submitted.
How can I do that using .data() in jquery? or Any ideas on how to store it until the form is being submit.
I didn't thoroughly look at your code, but I noticed when you print your table rows in a loop you have the id="try" assigned to all of the rows. the html id-attribute is a unique identifier so the JS that is alerting the value will only return the value of the first id it will find (at least that's what i think). Try to use a class instread of an id and then use this in your js.
$(document).on('click','.try',function(){
alert($(this).val());
return false;
});
Related
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
I successfully fetch the data from the database. The problem is that, I want to display the results using Ajax request. The results/Output which displayed twice, I mean the *first output which displayed through Ajax (#the bottom of index.php), and the Second output displayed through PHP ECHO (**#**the bottom of the page). What can I do to get a single output through Ajax without adding another file and without refreshing the page?
index.php
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="javas.js"></script>
</head>
<body>
<div id="table_content"></div>
<?php
include ("db.php");
error_reporting(~E_NOTICE);
function ShowForm($AnswerCommentId) {
echo '<form id="myForm">';
echo '<input id="user" name="user" />';
echo '<textarea id="text" name="text"></textarea>';
echo sprintf('<input id="ParentId" name="ParentId" type="hidden" value="%s"/>', ($AnswerCommentId));
echo '<button type="button" OnClick=SendComment()>Comment</button>';
echo '</form>';
}
$query="SELECT * FROM `comm` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId'])) $AnswerId = $_REQUEST['AnswerId'];
else $AnswerId = 0;
$i=0;
while ($mytablerow = mysqli_fetch_row($result)){ $mytable[$i] = $mytablerow; $i++; }
function tree($treeArray, $level, $pid = 0) {
global $AnswerId;
foreach($treeArray as $item){
if ($item[1] == $pid){
echo sprintf('<div class="CommentWithReplyDiv" style="margin-left:%spx;">',$level*60);
echo sprintf('<p>%s</p>', $item[2]);
echo sprintf('<div>%s</div>', $item[3]);
if ($level<=2) echo sprintf('Reply', $item[0]);
if ($AnswerId == $item[0]) echo sprintf('<div id="InnerDiv">%s</div>', ShowForm($AnswerId));
echo '</div><br/>';
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable,0,0);
?>
Comment
<div id="MainAnswerForm" style="display:none;width:40%; margin:0 auto;"><?php ShowForm(0); ?></div>
<div id="AfterMainAnswerForm"></div>
<script>
$(document).ready(function(){
$("#Link").click(function () {
$("#InnerDiv").remove();
$("#MainAnswerForm").slideToggle("normal");
return false;
});
});
</script>
</body>
Page.php
<?php
include ("db.php");
$user = $_POST['user'];
$text = $_POST['text'];
$ParentId = $_POST['ParentId'];
$action = $_POST['action'];
if ($action=="add") $query= mysqli_query($conn,"INSERT into `comm` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())");
?>
Javas.js
function show_messages(){
$.ajax({
url: "index.php",
cache: false,
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "page.php",
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
show_messages();
}
});
return false;
}
OK I think its more simple than you think
while you're using .html() it should change all the content of your div but while you're using <div id="table_content"></div> then the <?php ?> your code will show both - one appended to the div and under it the one which echoed by php ... so instead of using
<div id="table_content"></div>
<?php ?>
just wrap the <?php ?> inside the div
<div id="table_content">
<?php ?>
</div>
Alternative way: by using jquery wrapAll() but while Id must be unique you'll need to .remove() the #table_content element first then wrap all your code inside a new #table_content div .. see the example below
$(document).ready(function(){
$('#table_content').remove();
$('.CommentWithReplyDiv').wrapAll('<div id="table_content"></div>');
});
#table_content{
margin : 50px;
background : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table_content"></div>
<div class="CommentWithReplyDiv">1</div>
<div class="CommentWithReplyDiv">2</div>
<div class="CommentWithReplyDiv">3</div>
<div class="CommentWithReplyDiv">4</div>
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);
}
});
}
EDIT: thanks everyone for your help. It still doesn't work though.
This script works fine if i change the table to an ordered list. (tr = ol and td = li) That's why i really think the issue comes from the append part of the code. Any ideas?
Everything seems to work fine except for the "load more" button that disappears after it's been clicked. The new posts load but the users cannot click on the button again to load more posts. I've looked on SO but couldn't find a fix for my issue.
If I remove this line:
$("#more"+ID).remove();
then the button does show up but the gif image keeps on loading forever and the button is not clickable...
Here's the index.php code:
<table id="update_list" >
<tbody>
<?php
$result=query("SELECT * FROM postlist ORDER BY postid DESC LIMIT 9");
foreach ($result as $row)
{
$postid=$row['postid'];
$post=$row['post'];
?>
<tr id="<?php echo $postid ?>">
<td>
<?php echo $post; ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<div id="more<?php echo $postid; ?>" class="morebox">
more
</div>
</div>
</body>
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="/loading.gif" />');
$.ajax({
type: "POST",
url: "loadmore.php",
data: "lastpost="+ ID,
cache: false,
success: function(html){
$("#update_list >tbody").append(html);
$("#more"+ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
</script>
</html>
Here is the loadmore php page:
<?php
include("includes/config.php");
if(isset($_POST['lastpost']))
{
$lastpost=$_POST['lastpost'];
$result=query("SELECT * from postlist WHERE postid < '$lastpost' ORDER BY postid DESC
LIMIT 5");
foreach ($result as $row){
$postid=$row['postid'];
$post=$row['post'];
?>
<tr id="<?php echo update$postid ?>">
<td>
<?php echo $post; ?>
</td>
</tr>
<?php } ?>
<div id="more<?php echo $postid; ?>" class="morebox">
more
</div>
<?php }?>
Any tips on what i'm doing wrong here ?
Thanks !
Try this:
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).find("a").hide().insertAfter('<img src="/loading.gif" />'); //hide a link and insert image after it
$.ajax({
type: "POST",
url: "loadmore.php",
data: "lastpost="+ ID,
cache: false,
success: function(html){
$("#update_list >tbody").append(html);
$("#more"+ID).find("img").remove(); // remove img
$("#more"+ID).find("a").show(); //and show link
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
You are removing the load more button after button clicked
$("#update_list >tbody").append(html);
//$("#more"+ID).remove(); remove this line
When using jQuery AJAX in cakePHP 1.3, the AJAX response includes the full layout rather than just the array with dataset from the model. How to I prevent this whole page from being rendered? I have tried to use $this->autoRender = false; and $this->layout = 'ajax', but this did not solve the problem. It actaully produced no response in the returned data.
My controller action is:
public function search() {
if (empty($this->data)) {
} else {
// $this->autoRender = false;
// $this->layout = 'ajax';
$request = $this->data;
$this->set('data', $this->Event->search($request['Event']['search']), 'host');
}
}
And my view is:
<!-- app/views/events/search.ctp -->
<h1>Corporate Events</h1>
<form method="post" action="search">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
<p><?php echo $html->link("Add Event", "/events/add"); ?>
<table>
<tr>
<th style='width:100px'>Id</th>
<th style='width:100px'>Title</th>
<th style='width:100px'>Host</th>
<th style='width:100px'>Description</th>
<th style='width:100px'>Action</th>
</tr>
<div id= "results"></div>
<?php foreach ($data as $event): ?>
<tr>
<td><?php echo $event['id']; ?></td>
<td>
<?php echo $html->link($event['event_title'],'/events/view/'.$event['id']);?>
</td>
<td><?php echo $event['host']; ?></td>
<td><?php echo $event['description']; ?></td>
<td>
<?php echo $html->link(
'Delete',
"/events/delete/{$event['id']}",
null,
'Are you sure?'
)?>
<?php echo $html->link('Edit', '/events/edit/'.$event['id']);?>
</td>
</tr>
<?php endforeach; ?>
</table>
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var searchString = $("#search_box").val();
var data = {'data[Event][search]':searchString};
if(searchString) {
$.ajax({
type: "POST",
url: "/events/search",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
Thanks!
I don't understand your question well, but this will help you with displaying to your view without the layout being echoed wholly.
Put this on the javascript inside the view,
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var searchString = $("#search_box").val();
if(searchString) {
$.ajax({
url: "/events/search/" + searchString,
beforeSend: function() { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(data){ // this happens after we get results
$("#results").show();
$("#results").append(data);
}
});
}
return false;
});
});
</script>
Then use the code below for your controller,
public function search($data=null) {
$this->autoRender = false;
//your code here;
return $data;
}
I would recommend having another function do the results and rendering them. Make a function called update_results. Following examples assumes you have request handler and jquery in place.
Simple Example:
//Controller
function search()
{
//search filters
$locations = $this->Event->Location->find('list',array('order'=>'Location.name'));
//set vars for view
$this->set(compact( 'locations'));
}//search
function update_results()
{
//location filter
if(!empty($this->data['Event']['location_id']))
$conditions['Event.location_id']=$this->data['Event']['location_id'];
$results=$this->Event->find('all',array('conditions'=>$conditions,'limit'=>15));
//debug($conditions);
$this->set('results',$results);
}//update result
//Views
//search.ctp
<?php echo $form->create('Event',array('action'=>'search'));
echo $this->Form->input('Event.location_id', array('label'=>'Location','empty'=>TRUE));
echo $js->submit('Find Trainings', array('update' => '#trainingresults','url'=> array('controller'=>'events', 'action'=>'update_results')));
echo $form->end(); ?>
<?php
echo $html->div('trainingresults',null,array('id'=>'trainingresults'));
echo '</div>';
?>
//update_results.ctp
<?php
$timestamp=date('r');
echo "<h4>Search Results ($timestamp)</h4><br/>";
if(empty($results))
{
echo "<p class='well'><strong>No Trainings found. Try different search criteria.</strong></p>";
}
else
{
foreach($results as $display)
{
//Event Info
$location=$display['Location']['name'];
echo $location;
}//for
}//else
?>