CodeIgniter Json Ajax Database insertion is not working - php

I have tried to solve this issue, here i am inserting dynamic inputbox box values into database including their title. But not working...
Inputbox dynamic generation: (This works well)
$('#myTable tbody').append("<tr><td>"+rno+"</td><td>"
+item.stdname+"</td><td><input type='text' name='stdmark[]' class='mark' title='"+item.stdid+"' style='padding: 0px; width: 50px;'/></td></tr>");
Ajax to Send these values into controller:
$('#marklist').submit(function(e){
//var mark = 10;
jsonObj = [];
$("input[class=mark]").each(function() {
var id = $(this).attr("title");
var subjectmark = $(this).val();
item = {}
item ["stdid"] = id;
item ["mark"] = subjectmark;
jsonObj.push(item);
});
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>office/addmark",
data: {senddata :JSON.stringify(jsonObj)},
dataType: "json",
processData:false,
contentType:false,
cache:false,
async:false,
success:
function(retrived_data){
}
});
e.preventDefault();
});
Controller:
public function addmark()
{
$marks = json_decode($this->input->post('senddata'), true);
$this->load->Model('wtcmodel');
foreach($marks as $row)
{
$data = array(
'stdid' => $row->stdid,
'mark' => $row->mark
);
$this->wtcmodel->adddata($data);
}
}
Model:
public function adddata($data)
{
$this->load->database();
$this->db->insert('table_info',$data);
}

you can post input data using this method.
var stdid = $('input[name="stdmark[]"]').map(function(){
return $(this).attr('title');
}).get();
var marks = $('input[name="stdmark[]"]').map(function(){
return this.value;
}).get();
$.ajax({
type: 'POST',
url: 'users.php',
data: {
'stdid[]': stdid,
'marks[]':marks
},
success: function() {
}
});
You can access stdid[] and marks[] variable as array directly in controller.
Controller
public function addmark()
{
$stdid = $this->input->post('stdid');
$marks = $this->input->post('marks');
$this->load->Model('wtcmodel');
foreach($stdid as $key => $row)
{
$data = array(
'stdid' => $stdid,
'mark' => $marks[$key]
);
$this->wtcmodel->adddata($data);
}
}

why did't use Jquery serialize function : http://api.jquery.com/serialize/
$('#marklist').submit(function(e){
e.preventDefault();
//var mark = 10;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>office/addmark",
data: $(this).serialize(),
dataType: "json",
processData:false,
contentType:false,
cache:false,
async:false,
success:
function(retrived_data){}
});
});
or you can use param : http://api.jquery.com/jquery.param/

Related

Send ajax - check and confirm

how can i make ajax to check first for result and if any result found to ask for confirm and than to do something ?
$(".btn-delete").click(function(){
var url = "index.php?route=catalog/product/delete&user_token={{user_token}}";
var id = $('input[name*=\'selected\']:checked');
$.ajax({
url: url,
data: id,
dataType: 'json',
success: function(data){
}
});
});
Controller:
if (isset($this->request->post['selected']) && $this->validateDelete()) {
foreach ($this->request->post['selected'] as $product_id) {
$this->model_catalog_product->deleteProduct($product_id);
}
Model:
public function deleteProduct($product_id) {
$checkPreporuchaniProducts = $this->db->query("SELECT product_id FROM oc_preporuchani_category");
$checkid = array();
foreach ($checkPreporuchaniProducts->rows as $PreporuchaniProducts) {
$getId = unserialize($PreporuchaniProducts['product_id']);
foreach ($getId as $id) {
if ($product_id == $id) {
echo "yes: $id<br>";
}else {
echo "no: $id<br>";
}
}
}
Actually i did it with 2 ajax one that check result and another to confirm
$(".btn-delete").click(function(){
var urlcheck = "index.php?route=catalog/product/checkBeforeDelete&user_token={{user_token}}";
var urldelete = "index.php?route=catalog/product/delete&user_token={{user_token}}";
var urldeleteSpecial = "index.php?route=catalog/product/deleteSpecial&user_token={{user_token}}";
var id = $('input[name*=\'selected\']:checked');
$.ajax({
url: urlcheck,
data: id,
type: 'POST',
dataType: 'json',
success: function(data){
if (data.delete == null) {
if (confirm("This product is not used you can delete it")) {
$.ajax({
url: urldelete,
data: id,
type: 'POST',
dataType: 'json',
});
}
}else {
if (confirm("!!! WARNING: Product is used as SPECIAL if delete will effect other system as well !!!")) {
$.ajax({
url: urldeleteSpecial,
data: id,
type: 'POST',
dataType: 'json',
});
}
}
}
})

serializeArray not sending the data

This is a sample of the php and javascript.
<form id="image-comment" method="post" action="includes/insert_image_comment.php">
<textarea id="comment-area" name="comment-area"></textarea>
</form>
// javascript
$("#image-comment").submit(function(event) {
event.preventDefault();
var action_url = event.currentTarget.action;
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({imageid: id});
$.ajax({
url: action_url,
type: 'post',
data: params,
success: function(data) {
alert(data);
}
});
});
// insert_image_comment.php
echo $get_image = $_POST['imageid'];
$comment = $_POST['comment-area'];
When echoing $_POST['imageid'] i get an error 'Undefined index: imageid'.
When echoing $_POST['comment-area'] it's ok.
Why one works and the other not?
Thanks
Try to use the format that serializeArray uses: Example:
$("#image-comment").submit(function(event) {
event.preventDefault();
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({name: 'imageid', value: id}); // this one
$.ajax({
url: document.URL,
type: 'POST',
data: params,
success: function(data) {
alert(data);
}
});
});

Call Ajax Again in for loop

I want to request ajax many time in for loop . But it only return 1 value . result.ID. Can anyone help me?
$('#show').html('');
var min = parseInt($('#number_coupon_from').val());
var max = parseInt($('#number_coupon_to').val());
var total_time = parseInt($('#time_coupon').val())*1000;
var randcoupon = Math.floor(Math.random()*(max-min+1)+min);
var timetb = total_time/randcoupon;
var random = 0;
var i,j;
for(i=0;i<randcoupon;i++)
{
for(j=random;j>=0;j--)
{
if(j==0)
{
$.ajax({
url: 'backend/publish_auto/update',
type: 'post',
data: {},
dataType: 'json',
success: function (result)
{
if(result.st)
{
$('#show').append('Update Coupon ID: '+result.ID+'<br />');
}
}
});
}
}
}
});
Thank you !!
use async:False to get ajax response one by one
$.ajax({
url: 'backend/publish_auto/update',
async: false,
type: 'post',
data: {},
dataType: 'json',
success: function (result)
{
if(result.st)
{
$('#show').append('Update Coupon ID: '+result.ID+'<br />');
}
}
});

Access Data from Database with Ajax

I have tried just about every solution and I know my database returns values if i hard code in the php so the issues is returning the values or determining if it is actually sent as post. It gets to the success function and alerts Worked but I am getting undefined for Item ID.
$(document).ready(function() {
$('.check').click(function(){
alert("Step1");
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "GET",
url: "XXX.PHP",
data: { "ID": thisID},
cache: false,
async:true,
datatype: "json",
success: function(data)
{
alert("WORKED");
alert(data.ItemID);
}
});
});
});
Here is the PHP
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
function retrieve($ID)
{
$stmt = $mysqli->query("SELECT * FROM database1.menu WHERE ItemID = $ID");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
You could try something like this. Not sure if this is what you need.
$(".check").click(function(event){
event.preventDefault();
var $this = $(this);
var thisID = $this.attr('id');
$.ajax({
type: "POST",
url: base_url + "url.php",
data: {
id: thisID
},
dataType: "text",
cache:false,
success:
function(data){
alert(data);
}
});
return false;
});

Print json from mysql

Hi all I have a site developed in codeigniter.
In some function I have to retrieve data from mysql and print the result in javascript because is an ajax call.
Thi is my php function to retrieve data:
public function getCityByNameOnly($name) {
$query = $this->db->query('SELECT * FROM city WHERE name LIKE "%'.$name.'%" ');
$city = array();
foreach ($query->result() as $row)
array_push($city, $row);
return json_encode($city);
}
}
And this is my ajax call:
$('#ricerca-ajax').keyup(function(){
var val = $(this).val();
if (val.length>2){
var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
$.ajax({
url: site_url_city,
type: "POST",
data: {search: val},
dataType: "text",
success: function(data) {
console.log(data);
for(var i=0;i<data.length;i++)
{
$('#msgid').append(data[i].name_en + '<br> ');
}
}
});
}
})
I append the result into a div but is always undefined.
This is the console.log of my created json:
{"id":"125","name_it":"Lèsina (Hvar)","name_en":"Hvar","nation_id":"23","region_id":"0","active":"1"},{"id":"127","name_it":"Trogir (Traù)","name_en":"Trogir","nation_id":"23","region_id":"0","active":"1"},{"id":"1088","name_it":"Città del Capo","name_en":"Cape Town","nation_id":"101","region_id":"0","active":"1"}]
How to print this json into my success function in javascript?
Thanks
change the datatype:"json" in the ajax will solve the issue
$('#ricerca-ajax').keyup(function(){
var val = $(this).val();
if (val.length>2){
var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
$.ajax({
url: site_url_city,
type: "POST",
data: {search: val},
dataType: "json",
success: function(data) {
console.log(data);
for(var i=0;i<data.length;i++)
{
$('#msgid').append(data[i].name + '<br> ');
}
}
});
}
})

Categories