Data values passed from json is not recognized in CI Controller - php

This code should be working fine, as far as i can tell but for some reason it's not working. Can somebody please help me?!! T_T
js script:
$.ajax({
type: 'POST',
url: '<?=base_url()?>/folder_name_ajax/unit_vacancy',
dataType: 'json',
data:{unit_id:unit_id, unit_landlord_id:unit_landlord_id, unit_stat:unit_stat},
beforeSend: function(){
},
success: function(response){
console.log(response);
alert('Unit status successfully updated.');
}
});
Controller:
function unit_vacancy()
{
$this->load->model('modelAjax');
$unit_id = mysql_real_escape_string($this->input->post('unit_id'));
$unit_landlord_id = mysql_real_escape_string($this->input->post('unit_landlord_id'));
$unit_stat = mysql_real_escape_string($this->input->post('unit_stat'));
$xplod_stat = explode('-',$unit_stat);
$this->modelAjax->update_unit_vacancy();
}
Model:
function update_unit_vacancy()
{
$unit_id = mysql_real_escape_string($this->input->post('unit_id'));
$unit_landlord_id = mysql_real_escape_string($this->input->post('unit_landlord_id'));
$unit_stat = mysql_real_escape_string($this->input->post('unit_stat'));
$xplod_stat = explode('-',$unit_stat);
$result = $this->db->query("SELECT COUNT(ID) AS count FROM ".TBL_PREFIX."".UNIT_VACANT_TBL." WHERE unit_id = '$unit_id' ");
$count = $result->num_rows();
if($count == 0)
{
$result = $this->db->query("INSERT INTO ".TBL_PREFIX."".UNIT_VACANT_TBL."
(
unit_id,
landlord_id,
status
)
VALUES
(
'$unit_id',
'$unit_landlord_id',
'insert'
)
");
}
else
{
$result = $this->db->query("UPDATE ".TBL_PREFIX."".UNIT_VACANT_TBL."
SET
status = 'update'
WHERE
unit_id = '$unit_id'
");
}
}
I can't seem to understand what i did wrong here!!!

You are not echo(ing) anything in your controller as i see.? Where is your json? Is your update_unit_vacancy() returning the json? If yes then echo it.
echo $this->modelAjax->update_unit_vacancy();
And check your console too for the response of the ajax. Would recomment you one more thing though, change the below line:
url: '<?=base_url()?>index.php/rentdaddy_ajax/unit_vacancy',

Related

e.preventDefault / return false breaks ajax script firing properly

I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];

Get 2 variables from Ajax call in php

I am trying to get 2 variables from ajax in php. With one variable its working fine. New to ajax, so I am not sure how will I include a second variable. As of now I am getting the msg_count with out any issues. My ajax script is below:
function addmsg(type, msg) {
$('#msg_count').html(msg);
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "notification/select.php",
async: true,
cache: false,
timeout: 50000,
success: function(data) {
addmsg("new", data);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
};
$(document).ready(function() {
waitForMsg();
});
select.php script is below:
$sql = "SELECT * from notification where tousername='$tousername' and isread = 0";
$result = $con->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$not=$row['notification'];
echo $not;
I am able to pass the $count properly. I need to pass $not also to the ajax. How will I do that?
My edited php script to use it with a WHILE Loop is as follows:
$result= mysqli_query($con,"SELECT * from notification where tousername='$tousername' and isread = 0");
while($row = mysqli_fetch_array($result)) {
$count = $result->num_rows;
$not=$row['notification_msg'];
$res=[];
$res['count'] = $count;
$res['not'] = $not;
echo json_encode($res);
Like #guradio said, set dataType : 'json' inside ajax properties and json_encode data that you want to pass into success block like following code :
$.ajax({
....
....
dataType : 'json', // added here
success : function ( data ) {
// access data from response
// access it using data.count, data.not
console.log(data)
// just called like original code
// passed on result `data`
addmsg( type, data );
// the rest of the code
}
...
});
function addmsg(type, msg){
// access it using msg.count, msg.not
console.log(msg.count)
$('#msg_count').html(msg);
}
In Php :
$sql = "SELECT * from notification where tousername='$tousername' and isread = 0";
$result = $con->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
$not=$row['notification'];
// added here
echo json_encode( array( 'count' => $count, 'not' => $not ) );
Edited : This depend on how you want to store the data and populate it
// defined container outside loop
$res = [];
while($row = mysqli_fetch_array($result)) {
$count = $result->num_rows;
$not=$row['notification_msg'];
array_push( $res, array( 'count' => $count, 'not' => $not ) );
}
echo json_encode($res);
Suggestion(credited to guradio):
Must be noted that, there is not necessary to add async : true inside ajax properties as the default behavior of Ajax is asynchronous and the default value of that is TRUE unless you wanna it to be false, but not recommended.

receive multiple values from db using ajax

i know how to validate form using it for 1 field. But i would like enter code and take back multiple values from my db. exmp: price, quantity etc.
It is posible to do using ajac?
php file:
$sql = "SELECT * FROM database WHERE code='$field_code'";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$query=sqlsrv_query($conn, $sql, $params, $options);
$row = sqlsrv_fetch_array($query);
if ($row == true)
{
$code = ($row['code']);
$life = ($row['life']);
$agree = ($row['agree']);
}
echo $code;
echo $life;
echo $agree;
?>
And script is:
$("#field_code").change(function() {
$("#message").html("<img src='pictures/ajax_loader.gif' width='26px' height='26px' /> checking...");
var data1 = $("#field_code").val();
$.ajax({
type: 'POST',
url: 'validation.php',
data: $('form').serialize(),
success: function validate(code) {
if (data == ? ) {
to do something
} else {
to do something
}
How to receive all 3 values from php file?
}
})
you need to use json encode for this
$values[]= array('code'=>$row['code'],
'life'=>$row['life'],
'agree'=>$row['agree']);
echo json_encode($values);
and in ajax
var data = jQuery.parseJSON(data);
and access values like data.life,data.code and data.agree

PHP Jquery JSON catching

Here's my php responding to my jQuery calls.
<?php
if ( isset( $_POST['icnumber']) && $_POST['icnumber'] != '' ) {
$custic = $_POST['icnumber'];
$response = array();
$response['status'] = 'false';
$sql ="SELECT * FROM ctrl_cust WHERE cust_ic='$custic'";
$raw = mysql_query($sql,$link) or die('Query 1 '.mysql_error());
if ( $data = mysql_fetch_assoc( $raw ) ) {
$response['status'] = 'true';
$response['custid'] = $data['cust_id'];
$response['custname'] = $data['cust_name'];
}
header("Content-Type: application/json", true);
echo json_encode($response);
}
?>
and here's the jQuery
$(function() {
$('#icnumber-form').submit(function() {
var icno = $('#icnumber').val();
$.ajax({
type : 'POST',
url : 'php/create_process.php',
data : icno,
dataType: 'json',
success : function(data){
console.log(data);
},
beforeSend:function(){
$('.cust-exist-view').fadeIn();
}
});
return false;
})
});
The thing is, console.log returns NULL, but when I submit the form without javascript enabled, it returns this :
{"status":"true","custid":"00001","custname":"John"}
I wonder what is the problem...I've been running around in circles for hours...Help me please?
icnumber is not getting post, change data: icno, to data: {icnumber: icno}, and try

how to update PHP variable with Jquery Ajax?

I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});

Categories