Showing the result of my controller on the page - php

I would like to show the result from controller to view page in ajax codeigniter. This is my code I have used in my project. How to edit to show the result as table in the page. will you please help me to edit the code
<head>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content=' + textcontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
}
else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/Ajaxcontroller/getAttendence",
data: dataString,
cache: true,
success: function (html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="container">
<div class="main">
<form method="post" name="form" action="">
<textarea style="width:500px; font-size:14px; height:60px; font-weight:bold; resize:none;" name="content" id="content"></textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
</div>
</body>
this is my controller
public function getAttendence()
{
if($this->input->post() && $this->input->is_ajax_request()){
$credentials=array(
'category' => $this->input->post('content'),
);
$this->load->model('Ajaxmodel');
if($this->Ajaxmodel->selectAttendence($credentials)){
$data['result']=$this->Ajaxmodel->selectAttendence($credentials);
echo json_encode($data);
}
}
else{
$this->load->view('Salarycontrol');
}
}

$data['result'] = "here is your model";
Then send it to view:
$this->load->view('your_view_here', $data);

I saw that your controller echoed a json_decoded php array:
echo json_encode($data);
So your output is a json string. So in your success you have to use that JSON string. Convert that JSON string to a JavaScript object.
success: function (html) {
var res = JSON.parse(html);
// now your result contains exactly the same things as the php array `$data` you decoded in the controller
}
Note that I’m assuming that json_encode($data) is the only thing being printed by the controller.
If something else is printed, JSON.parse() will give you error.

In controller you have to use "echo" statement to show HTML in our view page.
For example:
//Ajax example with my code
$('#suppliers').change(function()
{
var sup_id = $(this).val();
if(sup_id != ''){
$.ajax({
url:BASE_URL+"orders/get_suppliers_details",
type:'POST',
data:{sup_id : sup_id},
success:function(result)
{
if(result){
$("#show").html(result);
}else{
echo "something went wrong.";
}
}
});
}
});
public function get_suppliers_details(){
$sup_id = $this->input->post('sup_id');
$sup_address = $this->orders_model->get_supplier_address_byId($sup_id);
echo $sup_address[0]['address']."_".$sup_address[0]['supplier_type'];
exit;
}
this will displayed at " id show div"
another way:
public function get_suppliers_details()
{
$sup_id = $this->input->post('sup_id');
$data['result'] = $this->orders_model->get_supplier_address_byId($sup_id);
echo $this->load->view('orders/get_details.php',$data);
}
get_detail.php
<table>
<tr>
<td>Address</td><td><?php echo $result['address']; ?></td>
</tr>
</table>
you can do what ever you want in get_details.php , It will displayed at "show div";
Sorry for my English.
Thank you.!

Related

Post and display data on the same page using PHP (MVC) AJAX

I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}

Ajax html input value appears empty

I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};

Ajax Insert Code Igniter

I have a form that will insert into table 'tags' using ajax. I was able to add manually but not without reloading the page.
This is my controller Controller (tags.php)
class Tags extends CI_Controller{
function __construct(){
parent:: __construct();
$this->load->model('tags_model');
$this->load->helper('form');
$this->load->helper('url');
}
function index(){
$data['tags']=$this->tags_model->get();
$this->load->view('tags/index',$data);
}
function add()
{
$this->tags_model->save();
return true;
}
}
?>
This is my view('index.php')
<script src="<?php echo base_url('assets/js/jquery.js');?>"></script>
<?php
foreach ($tags as $t){
echo '<span>';
echo $t['id'].':';
echo $t['title'];
echo '-';
echo '</span>';
}
?>
<form id="comment" method="post">
<?php echo form_input('title','text is here....');?>
<label> </label><input type="submit" value="Submit" />
</form>
<!-- here is the script that will do the ajax. It is triggered when the form is submitted -->
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tags/add",
data: dataString,
return false; //stop the actual form post !important!
success: function(data)
{
alert('Successful!');
}
});
return false; //stop the actual form post !important!
});
});
</script>
Model
<?php
class Tags_model extends CI_Model{
function __construct()
{
parent:: __construct();
$this->load->database();
}
function save()
{
$title=$this->input->post('title');
$data=array(
'title'=>$title
);
$this->db->insert('tags',$data);
}
function get(){
$query=$this->db->get('tags');
return $query->result_array();
}
}
?>
code seem to be okay to me. I can insert normally but not in ajax . Any help is welcome.
Remove the return false that is inside your jquery ajax call.
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tags/add",
data: dataString
success: function(data)
{
alert('Successful!');
}
});
return false; //stop the actual form post !important!
});
});
I did like in this tutorials and now workings
http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-day-8-ajax/
now my view is like that
<script src="<?php echo base_url('assets/js/jquery.js');?>"></script>
<?php
foreach ($tags as $t){
echo '<span>';
echo $t['id'].':';
echo $t['title'];
echo '-';
echo '</span>';
}
?>
<?php echo form_open('tags/add');?>
<?php echo form_input('title','text is here....','id="title"');?>
<?php echo form_submit('submit', 'Submit', 'id="submit"'); ?>
<?php echo form_close();?>
<!-- here is the script that will do the ajax. It is triggered when the form is submitted -->
<script type="text/javascript">
$('#submit').click(function() {
//var title = $('#title').val();
var form_data = {
title: $('#title').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('tags/add'); ?>",
type: 'POST',
data: form_data,
success: function() {
alert('added Successfully');
}
});
return false;
});
</script>
instead of
url: "<?php echo base_url('tags/add'); ?>",
I also had to switch to
url: "<?php echo site_url('tags/add'); ?>",
Controller
public function added()
{
$data['name']=$this->input->post('name');
$data['address']=$this->input->post('address');
$re=$this->model->add('aa',$data);
if($re)
{
?>
<script> alert("inserted");</script>
<?php
}
else
{
?>
<script> alert("not insert");</script>
<?php
}
//redirect('Myconn/insert');
}
JS Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#form1").on('submit',(function(e) {
var name = $("#name").val();
var address = $("#address").val();
e.preventDefault();
// document.getElementById("submit").value="Sending.....";
$.ajax({
url: "<?php echo base_url(); ?>Myconn/added",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html)
{
$("#feed_m").after(html);
//document.getElementById("submit").value="submit.";
document.getElementById('name').value='';
document.getElementById('address').value='';
}
});
}));
});
</script>
HTML Code
<div id="feed_m"></div>
<form method="post" id="form1" action="">
<table >
<tr>
<td>name</td>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<td>address</td>
<td><input type="text" id="address" name="address"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" id="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
Controller
public function added()
{
$data['name']=$this->input->post('name');
$data['address']=$this->input->post('address');
$re=$this->model->add('aa',$data);
if($re)
{
?>
<script> alert("inserted");</script>
<?php
}
else
{
?>
<script> alert("not insert");</script>
<?php
}
}
Model
public function add($table,$data)
{
return $this->db->insert($table,$data);
}

Delete record using jquery ajax but table is loaded again

I am deleting records using jQuery and Ajax. The code I wrote deletes a record but the HTML table is loaded again, which means the page refreshes which I want to avoid.
Here is my code:
comment.php
<script type="text/javascript">
$(document).ready(function(){
function loadList(){
$.ajax({
url: "load_list.php",
cache: false,
success : function(html){
$(".name_list").html(html);
}
});
}
loadList();
$("#Submit").click(function() {
if($(":text").val().length==0)
{
// $(this).next().html("Field needs filling");
$(":text").after('<span class="errorkeyup">Field cannot be empty</span>');
//return false;
success = false;
}
else
{
var name=$("#name").val();
var message=$("#message").val();
$.ajax({
type:"post",
url:"save_list.php",
data:"name="+name+"&message="+message,
success:function(data){
loadList();
}
});
return false;
}
});
$(".delete_button").on("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var id = $(this).attr("id");
/*var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){*/
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(){
loadList();
}
});
// }
return false;
});
});
</script>
</head>
<body>
<div id="form">
<form method="post" name="form" action="">
<div id="content">
Name : <input type="text" name="name" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
</div>
<input type="button" value="Submit" id="Submit">
</form>
</div>
<div class="name_list"></div>
</body>
loadlist.php
<?php
include('connection.php');
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<table border="1">';
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td>
<a id='".$row['id']."' href=delete.php?id=".$row['id']."&type=Delete class=delete_button>Delete</a></td>";
echo"<td>
<a id='".$row['id']."' href=comment.php?id=".$row['id']."&type=edit class=edit_button>Edit</a></td>";
echo '</tr>';
$i++;
}
echo'</table>';
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: comment.php");
}
?>
When you do the $.ajax() call for $('.delete_button'), you shouldn't call your loadList() function there because that is what reloads the table, instead you should just remove the one entry that's deleted from the table.
Perhaps you can remove it with something similar to this, placed inside the delete button success callback:
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function()
{
$(this).parent().parent().remove();
}
});
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: comment.php");
}
?>
in this code remove line
header("location: comment.php");
Final code would be,
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
echo '1';
} else {
echo '0';
}
exit;
?>
In delete function, after executing delete query, you need to echo '1' or '0'. Lets say echo '1'; when deleted successfully and echo '0' when delete not succeed. So based on 1 or 0 you can remove those deleted row from table by ,
$(".delete_button").on("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var obj = $(this);
var id = obj.attr("id");
/*var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){*/
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(response){
if(response == '1') {
obj.parent.remove();
}
}
});
// }
return false;
});

PHP and javascript POST

I have the following code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript">
</script>
<script type="text/javascript">
function displayTweet(){
var i = 0;
var limit = $("#twitter-results > div").size();
var myInterval = window.setInterval(function () {
var element = $("#twitter-results div:last-child");
$("#twitter-results").prepend(element);
element.fadeIn("slow");
i++;
if(i==limit){
window.setTimeout(function () {
clearInterval(myInterval);
});
}
},2000);
}
$("form#twittersearch").submit(function() {
twitterq = $('#twitterq').attr('value');
$.ajax({
type: "POST",
url: "search.php",
cache: false,
data: "twitterq="+ twitterq,
success: function(html){
$("#twitter-results").html(html);
displayTweet();
}
});
return false;
});
});
</script>
</head>
<div class="twitter_container">
<form id="twittersearch" method="post" action="">
<input name="twitterq" type="text" id="twitterq" />
<button type="submit">Search</button>
</form>
<div id="twitter-results"></div>
</div>
</html>
/***************THIS IS search.php***************************/
<?php
include('twitterapi.php');
if($_POST['twitterq']){
$twitter_query = $_POST['twitterq'];
$search = new TwitterSearch($twitter_query);
$results = $search->results();
foreach($results as $result){
echo '<div class="twitter_status">';
echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
$text_n = toLink($result->text);
echo $text_n;
echo '<div class="twitter_small">';
echo '<strong>From:</strong> <a href="http://www.twitter.com/'.$result->from_user.'">'.$result->from_user.'</a&glt;: ';
echo '<strong>at:</strong> '.$result->created_at;
echo '</div>';
echo '</div>';
}
}
?>
Why is it that when I do a var_dump($_POST['twitterq']) it is always NULL?
UPDATE:
firebug gave me this, not sure how to fix it though:
That is because you are not providing the data properly. It should be:
data: ({twitterq: twitterq}),
You are sending data in the form of JSON. You are not using URL parameters , so there is no need of '='. if you have more than one parameters, you will simply separate them with commas.

Categories