store form data in mysql database using ajax in codeigniter - php

Edit:
It was a problem with localhost and I think with the htaccess file. Although I couldn't make it in localhost, the script is running fine on the web host.
I want to store my form data in to the database using ajax in codeigniter. The problem is that everything is fine, except I'm getting a 500 server internal error.
My contoller:
public function order()
{
$order = $this->main_model->order($_POST);
if($order)
{
return true;
}
else
{
return false;
}
}
my model:
function order($options = array())
{
$options = array(
'client_Name' => $this->input->post('oName'),
'client_Phone' => $this->input->post('oPhone')
);
$this->db->insert('md_orders', $options);
return $this->db->insert_id();
}
and of course I'm using stepsForm script and this is the js code I have:
var theForm = document.getElementById( 'theForm' );
new stepsForm( theForm, {
onSubmit : function( form ) {
var form_data = {
oName: $('#oName').val(),
oPhone: $('#oPhone').val(),
};
$.ajax({
url: "<?php echo base_url() . 'main/order/'; ?>",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
}
} );
and this is the HTML code:
<form id="theForm" class="simform" autocomplete="off">
<ol class="questions" id="questions">
<li>
<span><label for="oName">Your name:</label></span>
<input class="finput" id="oName" name="oName" type="text"/>
</li>
<li>
<span><label for="oPhone">Your Phone Number:</label></span>
<input class="finput ltr" data-validate="number" id="oPhone" name="oPhone" type="text"/>
</li>
</ol>
</form>
and the error I'm getting is :
POST http://localhost/123/main/order/ 500 (Internal Server Error)
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and nothing is stored in the database. What am I doing wrong?!

Try to check your input in controller before send it to model, although it is not mandatory. In your model you need just feed of your array. So you can just set name of parameter.
Your model something like this:
public function order($options) {
$data = array();
$data['client_Name'] = $options['oName'];
$data['client_Phone'] = $options['oPhone'];
$this->db->insert('md_orders', $data);
if($this->db->affected_rows() > 0) {
return $this->db->insert_id();
else {
return false;
}
}
Your controller something like this:
public function order() {
$order = $this->main_model->order($this->input->post());
if( $order !== false ) {
echo "Inserted!";
} else {
echo "Not inserted!";//These are your ajax success function msg parameter
}
}
Also, I can't see the logic of form parameter inside onSubmit property's function( form ). Maybe you could remove it?

In your view,place the following code in your script,please...
one_field = $('#one_field').val();
second_field = $('#second_field').val();
$.ajax({
type:"post",
data:{one_field:one_field, second_field:second_field},
url :'<?=base_url("directory/controller_name/your_method_name")?>',
success: function(data)
{
alert("success");
}
});
Now the place the following in your controller.
function your_method_name()
{
$your_data = array(
"table_field_1" => $this->input->post('one_field'),
"table_field_2" => $this->input->post('second_field')
);
$last_id = $this->your_model->insert_data_function($your_data);
if(isset($last_id)
{
//your code
}
else
{
//your code
}
}
In your Model,place the following.
public function insert_data_function($your_data)
{
$this->db->insert("your_table",$your_data);
return $this->db->insert_id(); //will return last id
}

Instead of using base_url() in your JS, you should try and use site_url()
Your CodeIgniter website runs through the index.php file.
The base_url() function will return the URL to your base directory.
The site_url() will return the URL to your index.php file.
Your form is trying to access "http://localhost/123/main/order" when it should be trying "http://localhost/123/index.php/main/order"
Hope this helps.
Edit
You should also have a look at the form helper.
https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html

Related

use ajax call to load a view codeigniter

I am trying to load a view through ajax passing in a post variable through controller following is my ajax call:
$('#image_id').on('click',function(){
var image_id = $('#image_id').val();
alert(image_id);
if(image_id != '')
{
alert('called');
$.ajax({
url:"<?php echo site_url('Site/load_add')?>",
method:"POST",
dataType: "html",
data:{add_id:image_id},
success:function(data)
{
window.location.href = "<?php echo site_url('Site/load_add')?>";
}
});
}
else
{
alert('Error');
}
});
I am using the add_id to retrieve data from the database in my controller below:
public function load_add()
{
$this->load->model('Product_model');
$data['advert_data']=$this->Product_model->get_specific_add($this->input->post('add_id'));
$array_info2 = array(
"title" => "View Add"
);
$this->load->view('include/header', $array_info2);
$this->load->view('include/navbar_logged_in');
$this->load->view('Site/site_load_add',$data);
$this->load->view('include/footer');
}
I am getting an error at the point of data retrieval from DB, as the model does not have the add_id. Following is my model code
public function get_specific_add($image_id)
{
$this->db->select('adverts.title,adverts.item_condition,adverts.add_type,adverts.address,adverts.price,adverts.negotiable,adverts.product_description,adverts.create_time, users.first_name,users.last_name,users.mobile,users.email,users.image_name');
$this->db->from('adverts,countries,states,cities,users');
$this->db->where('adverts.id= $image_id_new');
$this->db->where('adverts.country_id=countries.id');
$this->db->where('adverts.city_id=states.id');
$this->db->where('adverts.area=cities.id');
$this->db->where('adverts.user_id=users.id ');
$this->db->where('adverts.id= $image_id');
$query = $this->db->get();
return $query->result();
}
Appreciate if someone can help me on this. The page i am trying to load is Site/site_load_add. Thanks
You've call same url with both GET|POST, First call POST is ok, but in GET that's your error.
$.ajax({
// first call is OK!
url:"<?php echo site_url('Site/load_add')?>",
method:"POST",
dataType: "html",
data:{add_id:image_id},
success:function(data)
{
// BUG HERE, This's a GET call and with No query string
// Will `$this->input->post('add_id')` found nothing.
window.location.href = "<?php echo site_url('Site/load_add')?>";
}
Thank you all for the support, I got this sorted by passing the ID of the advert a below:
public function load_add($id)
{
$this->load->model('Product_model');
$data['advert_data'] = $this->Product_model->get_specific_add($id);
$data['adverts'] = $this->Product_model->get_adverts();//get database query output to the array
$array_info2 = array(
"title" => "View Add"
);
$this->load->view('include/header', $array_info2);
$this->load->view('include/navbar_logged_in');
$this->load->view('Site/site_load_add', $data);
$this->load->view('include/footer');
}
Thanks

Ajax request return success message but data does not insert into database

I am sending a ajax request it also returning success message but data is not inserting. Basically it is a link, when I will will click on the link then ajax will send a request to controllers and in database it increase the value with the previous value by 1. I have tried pass huge times but failed. This is a codignator project. It will grateful if you kindly help.
Ajax File :
$(document).ready(function(){
$("#like").click(function(e){
e.preventDefault(); // <------this will restrict the page refresh
var post_id = $(this).prop('rel');
$.ajax({
url: "http://localhost/ci_website/index.php/site/add_like",
type: 'POST',
data : post_id,
dataType: 'json',
success: function(res) {
if (res.success) {
alert(res.msg);
} else {
alert(res.msg);
}
}
});
return false;
});
});
View File :
<a id="like" class="like_btn" rel="<?php echo $blog['blog_id'];?>" href="<?php echo site_url('site/add_like') . '/' . $blog['blog_id'];?>">Like</a>
Controller File :
public function add_like()
{
header('Content-Type: application/json');
if ($this->input->is_ajax_request()) {
$post_id = $this->uri->segment(3);
$this->db->set('post_like', '`post_like` + 1', FALSE);
$this->db->where('blog_id', $post_id);
$add_post_view = $this->db->update('wb_blog');
if ($add_post_view) {
die(json_encode(array('success' => true, 'msg' => 'Your Like has been sent successfully.')));
} else die(json_encode(array('success' => false, 'msg' => 'Something bad happened!!! Please, try again.')));
}
}
update
check with
if ($this->db->_error_message()) {
return FALSE; // Or do whatever you gotta do here to raise an error
} else {
return $this->db->affected_rows();
}`
You aren't calling the function, you're only loading the function, and since the loading of the file succeeded, it returns true.
After defining the function try calling it and see if that does work.
url: "http://localhost/ci_website/index.php/site/add_like/"+post_id,
I have add 'post_id' after the link. This is work fine. I did not define the exact id against which the row of the table will be affected.

Asynchronously query the database by using ajax and jquery and post the result back in codeigniter View

I've struggeled alot with this .
I wanna send an ID in the CI model and get the returned value via CI controller
My view is
<script type="text/javascript">
function showsome(){
var rs = $("#s_t_item option:selected").val();
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
contentType: 'json',
data: {item_id: rs},
success: function(output_string){
//$('#result_area').val(output_string);
alert(output_string);
}
});
}
</script>
My Controller method is
public function get_unit_item()
{
$received = $this->input->post('item_id');
$query = $this->units_model->get_unit_item($received);
$output_string = '';
if(!is_null($query)) {
$output_string .= "{$query}";
} else {
$output_string = 'There are no unit found';
}
echo json_encode($output_string);
}
And my model function responsible
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() >0 ){
$j = $result->row();
return $j->unit_item_info ;
}
}
Html codes
<?php $id = 'id="s_t_product" onChange="showsome();"';
echo form_dropdown('product_id[]', $products, $prod,$id); ?>
I tried to use the id only but failed to fire so passing a function onchange seems to pick the item and fire
Using firebug I can see that the post request sends item_id=2 but the response length is 0 and with php result code 302
POST
RESPONSE
How can I achive this?(The model is loaded on the contructor)
Do slighly change your controller and model:
// Model
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() > 0 ) {
$j = $result->row();
return $j->unit_item_info ;
}
else return false;
}
// Controller
public function get_unit_item()
{
$received = $this->input->post('item_id');
$return = array('status'=>false);
if( $query = $this->units_model->get_unit_item($received) ) {
$return['status'] = true;
// Add more data to $return array if you want to send to ajax
}
$this->output->set_content_type("application/json")
->set_output(json_encode($return));
}
Check returned values in JavaScript:
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
dataType: 'json',
data: {item_id: rs},
success: function( response ){
if( response.status === true ) {
alert('Everything Working Fine!');
console.log( response );
}
else alert('Something went wrong in query!');
}
});
After trying various approaches I have finally found what really is the problem and i think this might be the problem for all with the 302 found error. In this project (server) there're two systems within the same root and each has got its own codeigniter files. As seen above i was using
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
url : base_url+ '/' + controller+ '/get_unit_item',
as the value for url but i tried to put the full url from the base and it worked so now it is
url: '<?php echo base_url(); ?>index.php/en/items/get_unit_item',
. I think for any one with the redirect issue the first thing to check is this

Search for a table within a database in Laravel 4 PHP Framework

I am trying to set up search for a table within database in mine within the Laravel 4 PHP Framework. I am using jquery to accomplish this. I have a table "artists", that I am trying to allow a user to search through. I have a model "Artist.php", and a controller "SearchController.php" that I am using to control the logic. Finally, I have a view "search.blade.php" that I am using as the user facing file. Here is the relevant code:
SearchController.php:
public function show_search() {
$limit = 10;
if(isset($_GET['mode']) && !empty($_GET['mode'])) {
switch($_GET['mode']) {
case 'autocomplete':
if(isset($_GET['keywords']) && !empty($_GET['keywords'])) {
$query = htmlspecialchars($_GET['keywords']);
$query = mysql_real_escape_string($query);
$results = Artist::search_artists($query);
$data = array();
$i = 0;
if(isset($results) && !empty($results)) {
foreach($results as $result) {
if (strlen(strstr($result->stage_name, 'artists')) == 0) {
if($i < $limit) {
$data[$i] = $result;
$i++;
}
}
}
}
exit;
}
break;
}
}
return View::make('search.search');
}
Artist.php:
public static function search_artists($query) {
$search_artists = DB::table('artists')
->where('artists.stage_name', 'LIKE', $query)
->orderBy('created_at', 'DESC')
->get();
return $search_artists;
}
search.blade.php:
<input type="text" class="search" id="inputSearch" /><br />
<div id="divResult"></div>
<script type="text/javascript">
$(function(){
$(".search").keyup(function() {
var inputSearch = $(this).val();
var data = {mode : 'autocomplete', keywords : inputSearch};
if(inputSearch!='') {
$.ajax({
type: "GET",
url: "/search/search",
data: data,
cache: false,
success: function(html) {
console.log(html);
$("#divResult").html(html).show();
}
});
}
return false;
});
});
</script>
I call all of this with the route:
Route::get('/search/search', array('uses' => 'SearchController#show_search'));
When I run this and I type things into the search box, I see in the javascript console it reads:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
and the results don't display under the search box. Any idea what could be going wrong? Thank you for your help.
The javascript warning is caused by your return false;. If you need it (doesn't seem necessary for the keyup event unless you want to catch the enter key), you should do something like:
$(".search").keyup(function(e) {
e.preventDefault(); // prevent the default action of the event
I am not familiar with Laravel, but it seems to me that you are not getting any results because you are not doing anything with the $data variable in your controller.
I would guess you need something similar to:
return View::make('search.search', $data);
to pass the variable to your view.

php - codeigniter ajax form validation

Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.
I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.
Here's my code so far:
my view
// If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy ?>
<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
<label for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</p>
<p>
<label for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</p>
...
my controller
public function add($id){
// set validation rules in CI native
$rules = $this->product_model->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === true) {
// get post data and store them in db
$data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
$this->product_model->save($data, $id);
// no errors - data stored - inform the user with display success-div
} else {
// validation failed - inform the user by showing the errors
}
//load the view
$this->load->view('admin/products/add', $data);
}
and here’s the js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
// console.log(value);
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response); // how to output success or the errors instead??
}
});
return false; //disable refresh
});
});
How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view??
From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).
EDIT I did some changes to my application, here's the code so far:
the controller
public function manage($id = NULL){
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create(initialize inputs empty) a new one
if (isset($id) === true) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model_model->make_new();
}
if (isset($_POST['general_settings'])) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description'));
$this->product_model->save($data, $id);
$status = true;
} else {
// validation failed
$status = validation_errors();
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($status);
exit;
}
redirect('admin/product');
}
//if (isset($_POST['attributes_settings'])) { the same thing here }
// load the view
$this->load->view('admin/products/manage', $data);
}
and the js
success: function(response) {
//console.log(response);
if (data.status === true) {
$('#ajaxResults').addClass('alert alert-success').html(response);
} else {
$('#ajaxResults').addClass('alert alert-error').html(response);
};
}
But I'm having some issues
Although I get the error messages from validation_errors() as an alert-error when there are no errors I get the true in an alert-error too, insted of alert-success.
2.how should I return the success message too? eg. a message saying "Saves were done!".
Althought in a non-ajax-request the data are stored in the database, in case fo ajax the don't store. Any ideas What may be wrong???
HTML:
<div id="ajaxResults"></div>
Javascript ajax:
success: function(response) {
$('#ajaxResults').text(response);
}
this script you've wrote is only if the validation succeeds, right?
Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.
You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.
So your PHP will looks like:
return "0 " . $errorMessage;
and
return "1 " . $successMessage;
and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.
Use this way i hope this will work for you
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function ajax_call()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"expense/home/get_expense",
data: "userid=" + ids,
success: function(result){
$("#your_div_id").html(result);
}
});
}
</script>

Categories