inserting data into database using jquery ajax submit button codeigniter - javascript

i am trying to insert data into the database using the codeigniter framework, i tried many solutions i couldn't find a problem ., can somebody suggest me the proper answer after adding $this->model->('contact_model'); my page is blank
my controller pages.php
<?php
class pages extends CI_Controller{
function index{
$this->load->model('contact_model');
$this->load->view('pages/index');
}
}
?>
enter code here
my view index.php
<form id="submit" action="<?php echo site_url();?>/models/contact_model">
<input type="text" id="name" >
<input type="email" id="email" >
<textarea placeholder="Message" id="message"></textarea>
<button type="button" id="submit1">Send</button>
<a id="ack"></a>
</form>
my model contact_model.php
<?php
class contact_model extends CI_Model{
function insert_entry()
{
$data = array(
'name' => 'name' ,
'email' => 'email' ,
'message' => 'message');
$this->db->insert('contactus', $data);
}
}
?>
custom.js file
$("#submit1").click(function){
$.post($("#submit").attr("action"),
$("#submit :input").serializeArray(),
function(data)
{
$("div#ack").html(data);
});
$("#submit1").submit(function(){
return false;
// window.location.href="/application/models/";
});
});

try this :3
this is ajax to post data in page to models ...
$.ajax({
url : "<?php echo base_url();?>/pages/",
type : 'POST',
data :{
"name":$("#nametags").val(),
//more in here
},
success : function(data) {
});
in controler
class pages extent CI_Controller{
function index() {}
function insert_data(){
//call function insert data
$data = array(
'name' => 'name' ,
'email' => 'email' ,
'message' => 'message');
$this->db->insert('contactus', $data);
}
}
your url is: /insert_data

in action url first parameter won't be model it would be controller name
like follwoing <?php echo site_url();?>/controller_name/method_name
in your case use <?php echo site_url();?>/pages/
$.ajax({
url : "<?php echo site_url();?>/pages/insert_data",
type : 'POST',
data :{"name":$("#name").val(),"email":$("#email").val(),"message":$("#message").val()},
success : function(data) {
$("div#ack").html(data);
});
and create a function in controller
function insert_data()
{
$this->load->model('contact_model');
$this->contact_model->insert_entry();
}

Related

Ajax request not running used in codeigniter 4 [duplicate]

I am using codeigniter-4 version and trying to auto search in nav bar. I'm trying to send data in post method into controller using ajax. But its not work. And codeigniter 4 don't described details for ajax. below my code sample
input box is -
<input class="form-control mr-sm-2" type="search" placeholder="<?= lang('nav.search'); ?>" aria-label="Search" name='s' id="seachBox">
ajax code is -
$.ajax({
url:<?= base_url('search'); ?>,
headers:{'X-Requested-With':'XMLHttpRequest'},
data:{query:query},
success:function(data){
alert(data);
}
});
and my controller is -
<?php
class Search extends BaseController
{
public function __construct()
{
helper(['common_helper','aws_helper']);
}
public function index(){
echo 'string';
}
}
?>
route is -
<?php
$routes->get('/search', 'Search::index');
?>
Here is the sample code of ajax. (Make sure that you have defined route/controller method for search url)
$.ajax({
url:<?php echo base_url('search'); ?>,
type: 'post',
dataType:'json',
data:{query:query},
success:function(data){
alert(data);
}
});
CI4 Code to get the request data
if ($this->request->isAJAX()) {
$query = service('request')->getPost('query');
var_dump($this->request->getPost('query'));
}
Also, make sure to update csrf token on every request if you are not reloading a page on success. Also, you need to return csrf token in method.
So in that case your method will look like -
if ($this->request->isAJAX()) {
$query = service('request')->getPost('query');
//var_dump($this->request->getPost('query'));
return json_encode(['success'=> 'success', 'csrf' => csrf_hash(), 'query ' => $query ]);
}
So in that case your ajax code will look like -
$.ajax({
url:<?php echo base_url('search'); ?>,
type: 'post',
dataType:'json',
data:{query:query},
success:function(data){
var result = JSON.parse(data);
$("input[name='csrf_test_name']").val(result['csrf']);
}
});

calling function in codeigniter controller using ajax not working

I have a codeigniter website, where I have done an add to cart function, on button click the product is added to cart after page reloads which is working fine, I did the following code in controller:
public function buy($id)
{
$color= $this->input->post('color');
$size=$this->input->post('size');
$product = $this->product->find($id);
$item = array(
'id' => $product->id,
'name' => $product->pname,
'quantity' => 1
);
if(!$this->session->has_userdata('cart')) {
$cart = array($item);
$this->session->set_userdata('cart', serialize($cart));
} else {
$index = $this->exists($id);
$cart = array_values(unserialize($this->session->userdata('cart')));
if($index == -1) {
array_push($cart, $item);
$this->session->set_userdata('cart', serialize($cart));
} else {
// $cart[$index]['quantity']++;
// $this->session->set_userdata('cart', serialize($cart));
$this->session->set_flashdata("Error","Product Already In Cart !");
redirect($_SERVER['HTTP_REFERER']);
}
}
$this->session->set_flashdata("Success","Product Added To Cart Successfully !");
redirect($_SERVER['HTTP_REFERER']);
}
Now I am trying to call this function using ajax so that the product is added to cart without page reload. I did the following code:
$("#change").submit(function() {
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});
<form action="" method="post" id="change">
<input type="hidden" value="<?php echo $product->id; ?>" id="prod">
<input type="submit" value="switch">
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
However it's not adding to cart, it simply reloads the page. Can anyone please tell me what is wrong in here?
Because the form is still submitting, you can use preventDefault();
$("#change").submit(function(e) {
e.preventDefault();
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});

getting the value of a array from controller to view with ajax in codeigniter

I am creating a status update system where i need to upload a image as well as show it when it uploads all using ajax but when i send the image it goes to the database but i cannot access the image in the ajax return
here is the code
<div class="tab-pane fade" id="tabs-2">
<?php echo form_open_multipart('',["id"=>"formupload","name"=>"formupload"]); ?>
<p class="formUnit"> <i class="active_pic"></i>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<button class="uibutton" type="button" id="upload_pic" style="width: 230px; height: 150px;">Upload Picture</button><span id="status"></span>
<?php echo form_upload(["name"=>"imagefile","id"=>"upload_pic" ]); ?>
<ol class="controls clearfix">
<?php echo form_submit(['name'=>'submit','value'=>'Submit',"class"=>"btn btn-primary"]); ?>
</ol>
</p>
<p id="files"></p>
<?php echo form_close(); ?>
</div>
now ajax
jQuery('#formupload').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
var url= '<?php echo base_url("user/postData_image"); ?>';
formData.value
jQuery.ajax({
type: "POST",
url:url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data)
{
console.log(data);
$('#output_post').attr('src',data);
},
error: function(data){
//error function
}
});
});
now controller
public function postData_image()
{
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'jpg|gif|png|jpeg',
'max_size' => 10000000000000,
'max_width' => 1024000000,
'max_height' => 7680000000,
];
$this->load->library('upload', $config);
$this->upload->initialize($config);
$imagefile="imagefile";
if(!$this->upload->do_upload($imagefile))
{
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/profile',compact('upload_error'));
}
else
{
$post = $this->input->post();
//print_r($post);
unset($post['submit']);
$upload_data = $this->upload->data();
$file_name=$_FILES['imagefile'];
$this->load->model('Pmodel');
$post_data=$this->Pmodel->post_data_image($post,$file_name);
$post['data']=$post_data;
echo $image_path= base_url("uploads/".$upload_data['raw_name'].$upload_data['file_ext']);
return $post;
}
}
model
public function post_data_image($arr,$arra)
{
$id=$arr['id'];
$image=$arra['name'];
$data=array('image'=>$image);
$query=$this->db->insert('post_status',['user_id'=>$id,'image'=>$image]);
return $query;
}
but how to return the value that is generated after insert in the database using ajax
You want to output your post as json so jquery can interpret it.
echo json_encode($post);
To your ajax function add:
dataType: 'json'
And then data will be an array you can use.
Thanx to #Callombert i got the answer for what i was looking i wanted to return the value and 'echo json_encode('$image_path) or $post would return the value in the json form thus you cacn access it in your view
for someone else looking for an answer just add echo json_encode($image_path);
To your ajax function add:
dataType: 'json'
this would get you working.

Double Records Added After Enabling Client Side Validation And Submitting form in Yii

I have a following simple form in Yii that is submitted by AJAX:
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'application-form',
'enableAjaxValidation' => true,
'enableClientValidation' => true,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
'onsubmit'=>"return send();"
),
'clientOptions'=>array('validateOnSubmit'=>true)
)); ?>
<div class="row">
<?php echo $form->labelEx($model, 'name'); ?>
<?php echo $form->textField($model, 'name', array('size' => 60,'maxlength' => 255)); ?>
<?php echo $form->error($model, 'name'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
And function for submitting:
function send (){
var data_form=$("#application-form").serialize();
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->createUrl('admin/application/create') ?>",
dataType:'json',
data: data_form,
success: function (data, textStatus, jqXHR) {
console.log(data);
alert("success",textStatus);
},
error: function (jqXHR, textStatus, errorThrown) {
// console.log( errorThrown);
}
});
return false;
}
My create controller:
public function actionCreate()
{
$model = new Application;
$model->setScenario('create');
$this->performAjaxValidation($model);
if (isset($_POST['Application'])) {
if ( $model->save()){
echo CJSON::encode(array('success' => 'true','id'=>$model->id));
Yii::app()->end();
}
}
$this->render('create', array(
'model' => $model
));
}
Filed name is required and that is only validation for now. When I try to submit form without field name inputted, validation messages appear as they supposed to do in Yii. But when I fill form correctly, my model is inputted twice in database. If I remove following property:
'clientOptions'=>array('validateOnSubmit'=>true)
model gets saved correctly (only one time), but no validation messages appear.
How can I get default validation messages in Yii to appear, when I submit my form via ajax and model not to be saved twice. I need to submit form this way, because I will return model id in Ajax response for processing in JavaScript.
I searched the web for this and tried all suggestions, but none of them work.
Thank you all!
I solved by adding 'afterValidate'=>'js:function(form,data,hasError){ send(form,data,hasError); and removing 'onsubmit'=>"return send();" line. Now it shows validation errors and only saves model once.
Check this post for more info.

insertion into cart does when page refreshes in codeigniter with ajax

I am adding items into cart with ajax in codeigniter.
My problem is that the cart got updated when i refreshes page. I have ajaxify it to prevent page refresh. but its not happening. My code is right and there is no error. but still its not working.
my controller code is
public function add_to_cart()
{
$item_id = $this->input->post('item_id');
$item_name = $this->input->post('item_name');
$item_price = $this->input->post('item_price');
$data = array(
'id' => rand(5,1000),
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
$this->cart->insert($data);
}
my view code is
function insert()
{
var item_id=$("#item_id").val();
var item_name=$("#item_name").val();
var item_price=$("#item_price").val();
var dataString = "&item_id=" + item_id + "&item_name=" + item_name + "&item_price=" + item_price;
$.ajax({
type: "POST",
url: "http://localhost/wah/cart_test/add_to_cart",
data: dataString,
success: function()
{
alert('hello');
}
});
}
<form id="form">
<input type="hidden" id="item_id" name="item_id" value={{data.id}}> <input type="hidden" id="item_name" name="item_name" value={{data.item_name}}> <input type="hidden" id="item_price" name="item_price" value={{data.price}}>
<p>Add to Cart</p>
</form>
the concept of the cart is to add the cart array in a session
so the php will not feel the changes until you reload the page
so you have to append the table with javascrip
// in controller
public function add_to_cart()
{
$item_id = $this->input->post('item_id');
$item_name = $this->input->post('item_name');
$item_price = $this->input->post('item_price');
$data = array(
'id' => rand(5,1000),
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
$this->cart->insert($data);
echo json_encode($data) ;
}
// in your javascript
$.ajax({
type: "POST",
url: "http://localhost/wah/cart_test/add_to_cart",
data: dataString,
success: function(data)
{
// just replace YOUR-TABLE-ID with table id
//and complete the tr you want to append
var tr = "<tr><td>"+data.id+"</td><td>"+data.name+"</td></tr>";
$("#YOUR-TABLE-ID tr:last").after(tr);
}
});
What is happening when you try to use $item_id instead radnom number:
$data = array(
'id' => $item_id,
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);

Categories

Resources