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);
}
Related
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.!
there is array in while loop please check with code below
<?php
$addItemSql = "SELECT * from tbl_invoice_services where col_cust_id='$getID' ORDER BY col_service_id";
$addItemResult = mysqli_query($db, $addItemSql);
while ($addItemRow = mysqli_fetch_assoc($addItemResult)) {
?>
<tr>
<td>
<input type="hidden" id="col_service_product1" name="col_service_product1[]" value="<?php echo $addItemRow['col_service_product']; ?>">
</td>
</tr>
<?php} ?>
and want to post those array value to php
ajax code
$('.saveInvoice').on('click', function (ev) {
$.ajax({
url: "saveInvoce.php",
type: "POST",
data: {
col_service_product1:$('#col_service_product1').val()
},
success: function (data) { }
});
});
try this demo code
file1
<?php
$i=0;
while ($i<5) {
?>
<tr>
<td>
<input type="hidden" id="col_service_product1" name="col_service_product1" value="<?php echo $i; ?>">
</td>
</tr>
<?php $i++; } ?>
<button value="Save Invoice" class="saveInvoice">Save Invoice</button>
<script type="text/javascript" src="../library/q.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.saveInvoice').click(function () {
var arr=[];
var data=document.getElementsByName("col_service_product1");
for(var i=0;i<data.length;i++){
arr[i]=data[i].value;
}
$.ajax({
url: "saveInvoce.php",
type: "post",
data: {col_service_product1:arr},
success: function (data) {
alert(data);
}
});
});
});
</script>
file2
<?php
$data=$_POST['col_service_product1'];
//code for save data in table
foreach($data as $value){
echo $value; //query here
}
I have a basic signup/ login page that submits the data to the SQL database with php. However, I would like the page not to redirect on submission with help of jQuery AJAX (either successful or not).
This is what I currently have and it is not working. It doesn't show any error messages.
HTML - signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Signup</title>
<meta charset="utf-8">
</head>
<body>
<form>
<table>
<tbody>
<tr>
<td>
<input type="text" name="first" placeholder="First Name" id="first">
</td>
</tr>
<tr>
<td>
<input type="text" name="last" placeholder="Last Name" id="last">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Signup" id="signup">
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
JavaScript - signup.js
function submit() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize(),
success: function() {
console.log("Signup was successful");
},
error: function() {
console.log("Signup was unsuccessful");
}
});
});
}
$(document).ready(function() {
submit();
});
PHP - signup.php
<?php
include_once "db_connect.php";
$post_FirstName = $_POST['first'];
$post_LastName = $_POST['last'];
$addData = "INSERT INTO details (firstname, lastname) VALUES ('$post_FirstName', '$post_LastName')";
if ($conn->query($addData) === TRUE) {
echo "Working";
} else {
echo "Not working";
}
?>
Here is the JSFiddle.
I hope you guys can help. Thanks in advance :)
If you are using ajax no need to use input type as submit use button.
$(document).ready(function() {
$("#signup").click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize()
success: function() {
console.log("Signup was successful");
}
error: function() {
console.log("Signup was unsuccessful");
}
});
});
Also change here
$post_FirstName = $_POST['first']; // name is `first` not `firstname`
You have some brakes and parentheses not properly closed
function submit() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize(),
success: function() {
console.log("Signup was successful");
},//here
error: function() {
console.log("Signup was unsuccessful");
}
});});//here
}
$(document).ready(function() {
submit();
});
No need to call submit function. Just this will do, (you missed comma and closing tag):
<script>
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $('form').serialize(),
success: function() {
console.log("Signup was successful");
}, //You missed this
error: function() {
console.log("Signup was unsuccessful");
}
});
}); //You missed this
</script>
here is my view
<html>
<body>
<form method="post" name="myForm1" id="myForm1" enctype="multipart/form-data" >
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="submitbutton" type="submit">
</form>
<div id="abc"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> //no need to specify the language
$(document).ready(function() {
$('#myForm1').on("submit",function(e) {
//var form = $(this);
//dataString = $("#myForm1").serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('form_controller/insert_into_db'); ?>",
data: $(this).serialize(),
//dataType: "json",
success: function(data){
// top.location.href = "<?php echo site_url('form_controller/callform'); ?>";
//$.each(data.results, function(){
// $("#abc").append('<div><b>' + id.id + '</b></div><hr />');
//});
/*var site_url = "<?php// echo site_url('form_controller/callform/') ?>";
site_url = site_url +"/" + id;
$("#abc").load(site_url);*/
<?php //foreach(): ?>
var site_url = "<?php echo site_url('form_controller/callform'); ?>";
var mydata=window.JSON.stringify(data.trim());
alert(mydata);
//site_url = site_url +"/" +data.id;
alert(site_url);
$("#abc").load(site_url);
//$('#abc').html(data);
var item = data;
alert(item.id);
}//,
//error: function() { alert("Error posting feed."); }
});
});
});
</script>
</body>
</html>
controller
function index(){
$this->load->view('submit_form');
}
function callform($id){
$this->load->view('view_form',$id);
}
public function insert_into_db(){
$this->load->helper('url');
$this->load->model('form_model');
$data= $this->form_model->insertQ();
$this->output->set_output(json_encode($data));
}
}
model
<?php
class Form_model extends CI_Model{
function insertQ(){
$email = $this->input->post('email');
$text = $this->input->post('qText');
$this->db->query("insert into form (email,text) values('$email','$text')");
$this->load->database();
$query = $this->db->query("SELECT MAX(id) AS id FROM form");
return $query->result();
}
}
when insert record into database there is a auto increment id. I need to get that particular id
from database and return it to the success function in ajax. then I need to load another page
into a div and print that id on newly loaded content.here the problem is
in view I couldn't get data into variable.for site_url
You can get the inserted id
$id = $this->db->insert_id();
I'm having trouble getting ajax to work with jquery and codeigniter. I've followed multiple tutorials but nothing seems to work. I'm trying to implement an upvote button that sends post data using ajax to be inserted into a db. Any help is much appreciated.
The code from my view:
<pre>
<?php foreach($query->result() as $row): ?>
<div>
<form action="" method="post">
<input type="hidden" name="story_id" value=<?php echo $row->id; ?>>
<input type="submit" name="story_id" class="button" id="submit_btn" value=<?php echo $row->id;?>>
</form>
</div>
<?php endforeach; ?>
</pre>
The jquery script I'm using:
<pre>
<script type="text/javascript">
$(document).ready(function(){
$(".button").click(function(){
var form_data = {
story_id: $(this).val()
};
$.ajax({
url: "<?php echo base_url('cyoa/upvote'); ?>",
type: 'POST',
data: form_data,
success: function()
{
$("#upvote").hide();
}
});
return false;
});
});
</script>
</pre>
Best way is to serialize your form data and send that to the server:
<script type="text/javascript">
$(document).ready(function(){
$(".button").click(function(){
var form_data = $("#myform").serialize();
$.ajax({
url: "<?php echo base_url('cyoa/upvote'); ?>",
type: 'POST',
data: form_data,
success: function()
{
$("#upvote").hide();
}
});
return false;
});
});
</script>
To access the form, give it a id:
<form id="myform" action="" method="post">
I strongly suggest to look at this plugin (and use it) :
JQuery Form Plugin
You can use form serialization to pass on data to php as below
First Give ID "storyform" to your form tag
$.ajax({
url: "<?php echo base_url('cyoa/upvote'); ?>",
type: 'POST',
data: $("#storyform").serialize(),
success: function()
{
$("#upvote").hide();
}
});
try using json objects,
view....
<pre>
<?php foreach($query->result() as $row): ?>
<div>
<form action=" controller_name/upvote" method="post">
<input type="hidden" name="story_id" id = "story_id" value=<?php echo $row->id; ?>>
<input type="submit" name="story_id" class="button" id="submit_btn" value=<?php echo $row->id;?>>
</form>
</div>
<?php endforeach; ?>
</pre>
Then your controller,
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controller_name extends CI_Controller {
function __construct()
{
parent::__construct();
//loading libraries
$this->load->helper(array('form','url'));
$this->load->library('form_validation');
}
//##############################################################################
function upvote(){
//setting validation rules
$this->form_validation->set_rules('story_id', 'story Id', 'required|xss_clean');
if ($this->form_validation->run() == true){
//if validations ok, send the data to database
$this->load->model('your_model');
$params = ($this->input->post('story_id');
$query = 'INSERT INTO table_name (story_id) VALUES(?)';
$result = $this->your_model_name->method_name($query,$params);
echo '{"validation_result": "passed"}';
}
else{
$output = '{"story_id":"'.form_error('story_id').'"}';
echo $output;
}
}
}
?>
Then Your java script file
$(document).ready(function(){
$('#submit_btn').live('click',function(){
var form_data = {
$story_id: $('#story_id').val()
};
$.ajax({
type: "POST",
url: baseurl+"controller_name/upvote",
dataType: "json",
data : form_data,
success:
function(data){
if(data.validation_result == "passed"){
$("#upvote").hide();
}
else{
//form_validation errors
}
}
});
return false;
});
});