php json data return jquery - php

Looking for a best solution:
$.getJSON("InsertData.php", {fullName:val1, course_id:course_id, occupation:val2}, function(data) {
$.each(data, function(i, user) {
//alert(user.aryA.status);
if(user.aryA.status == 'true'){
currentPosition = 2;
checkData();
nextSlide();
}else{
nextSlide();
}
});
})
Here is php code:
mysql_select_db("db", $con);
$Query="SELECT * from table WHERE fullName='".$fullName."' and course_id='".$cid."'";
$result = mysql_query($Query);
$totalRecords = mysql_num_rows($result);
if($totalRecords) {
while ($row = mysql_fetch_array($result)) {
$returnData[]=array( //for Json data array
'userName' => $row['fullName'],
'aryA' => array(
'status' => $row['status']
)
);
}
}
if(!$totalRecords) {
$insertQuery="INSERT INTO table (fullName,course_id,occupation) VALUES ('".addslashes($fullName)."','".addslashes($cid)."','".addslashes($d3)."')";
$result1 = mysql_query($insertQuery);
}else{
if($stat == "true"){$value = 1;}
}
mysql_close($con);
echo json_encode($returnData);
So In first case when I hit the php through jquery it saves data in database but give me error or length. Because $returnData is empty. Is there a way if $totalRecords is false, how to send json_encode to say there is no data or any value through json_encode to my jQuery function.
Thanks in advance.

Just setup an else statement, and add a 'success' key to your array:
if($totalRecords){
while ($row = mysql_fetch_array($result)) {
$returnData[]=array( //for Json data array
'success'=>'true',
'userName' => $row['fullName'],
'aryA' => array(
'status' => $row['status']
)
);
}
}else{
$returnData = array('success'=>'false');
}
Then check the value of 'success' in your jQuery.
Also, you really shouldn't be using mysql_*.

$returnData = array(); //add this
$totalRecords = mysql_num_rows($result);
if($totalRecords) {
while ($row = mysql_fetch_array($result)) {
$returnData[]=array( //for Json data array
'userName' => $row['fullName'],
'aryA' => array(
'status' => $row['status']
)
);
}
}
else
{
$returnData[] = 'no Record'; //add this
}

Related

Loop return one result in conditioner query

I am trying to fetch data from database in code-igniter .Bur this loop return only one loop .
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
You need to define $userdatas=array(); outside the loop. It is inside the loop that's why it overrides the data and returns the last record.
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
$userdatas = array();
foreach($userchatData as $key => $userdata){
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] =$userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
Hope this will help you :
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[$key]['chat_id'] = $userdata['chat_id'];
$userdatas[$key]['chat_from'] = $userdata['chat_from'];
$userdatas[$key]['created_date'] = $userdata['created_date'];
}
/*print_r($userdatas); output here*/
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
}
echo json_encode($data);

ajax request returns an unexpected output with the correct output

This is the output I get from ajax request to php pdo:
[{"sys_id":"1","task":"qwe","task_date":"11\/30\/2017 8:49 PM","task_person":"qwe","task_status":"0"},{"sys_id":"2","task":"asd","task_date":"11\/30\/2017 9:54 PM","task_person":"asd","task_status":"0"}]null
As shown there is an excess null value which I cant figure out where it is coming from my code is:
function selecttask(action) {
$.ajax({
type: 'POST',
url: '../include/demo.php',
dataType: "json",
data: {
action: action
},
success: function(data) {
}
}).done(function(data) {
});
}
selecttask("selectall");
My demo.php is:
<?php
include_once("crud.php");
//include_once("../config/config.php");
//$con = new connect_pdo();
$crud = new Crud();
$action = $_POST['action'];
$data = $_POST['data'];
switch (strtolower($action)):
case("selectall"):
$table = "list_tbl";
$selectall = $crud->selectall($table);
echo json_encode($selectall, JSON_UNESCAPED_UNICODE);
break;
case("add"):
$table = "list_tbl";
$insert = $crud->insert($table,$data);
echo json_encode($insert, JSON_UNESCAPED_UNICODE);
break;
endswitch;
?>
Then crud is:
<?php
include_once("../config/config.php");
class Crud extends connect_pdo {
public $_con;
function __construct() {
parent::__construct();
$this->_con = $this->dbh();
}
public function selectall($table_name) {
$queryselectall = "Select * from {$table_name}";
$selectall = $this->_con->prepare($queryselectall);
if ($selectall->execute()) {
if ($selectall->rowCount() > 0) {
$result = $selectall->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
}else{
echo array('error'=> TRUE, 'message'=> 'No result found.');
}
}
}
public function insert($table_name, $res) {
parse_str($res, $data);
$limit = count($data);
$ctr = 0;
$columns = "";
$values = "";
foreach ($data as $key => $value) {
$ctr++;
$columns.= "{$key}";
$values .= ":{$key}";
if ($ctr < $limit) {
$columns.= ",";
$values .= ",";
}
}
$query = "INSERT INTO {$table_name} ({$columns})VALUES({$values})";
try {
$create = $this->_con->prepare($query);
foreach ($data as $key => $value) {
$keys = ":{$key}";
$create->bindValue($keys, $value, PDO::PARAM_STR);
}
if ($create->execute()) {
$lastinserted_id = $this->_con->lastInsertId();
echo array('error' => FALSE, 'message' => 'Data added successfully.', 'lastinserted_id' => $lastinserted_id, 'query' => $query);
} else {
echo array('error' => TRUE, 'message' => 'Execution failed, please contact system support!');
}
} catch (Exception $ex) {
echo array('error' => TRUE, 'message' => $ex);
}
}
}
?>
From the above code I cant determine where the null is coming from.
Did I miss something that is why null is coming as result of ajax request
Probably a better architecture for your Crud class to handle DB interactions by running the queries and returning the results as an array (or throwing an exception if anything exceptional happens). Then your demo.php script can just get the array from the Crud class method and handle the output (json encoding, response output).

merging two array into single inside json_encode for android

I have to combine two array into single inside Json encode. my code is,
// Controller
$email = $this->input->get('email');
$pass = $this->input->get('password');
$enc_pass = 0;
$get_pass = $this->select->selectData($email);
if(!empty($get_pass)) {
foreach($get_pass as $password)
$enc_pass = $password['user_password'];
$dec_pass = $this->encrypt->decode($enc_pass);
if($pass == $dec_pass) {
$details = array('tag' => 'login', 'status' => 'true');
echo json_encode(array_merge($get_pass, $details));
}
else {
$details = array('tag' => 'login', 'status' => 'false', 'error_msg' => 'Incorrect Email or Password');
echo json_encode($details);
}
}
else {
$details = array('tag' => 'login', 'status' => 'false', 'error_msg' => 'Incorrect Email or Password');
echo json_encode($details);
}
// Model
public function selectData($email) {
$query = $this->db->query('SELECT * FROM tbl_user WHERE email = "'.$email.'"');
$count = $query->num_rows();
if($count > 0)
return $result = $query->result_array();
else
return 0;
}
Now the output for the above code is,
{"0":{"user_id":"1","user_name":"Jithin Varghese","user_email":"jithinvarghese111#gmail.com","user_phone":"9947732296","user_status":"1"},"tag":"login","status":"true"}
Required output is,
{"user_id":"1","user_name":"Jithin Varghese","user_email":"jithinvarghese111#gmail.com","user_phone":"9947732296","user_status":"1","tag":"login","status":"true"}
How to get the required output. I have tried a lot. How to implement this.
Thankyou.

I need help in json response in php

Here is my code:
<?php
while ($row = mysqli_fetch_assoc($searching_user))
{
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response["error"] = FALSE;
$response["service_name"] = $salon_name;
echo json_encode($response);
}
?>
after this I'm getting the response in this format
{"error":false,"service_name":"Mike
salon"}{"error":false,"service_name":"Michel salon"}
{"error":false,"service_name":"Michel salon"}{"error":false,"service_name":"Mike Salon"}
{"error":false,"service_name":"Etta Salon"}
I simply want this response like this
[ {"error":false,"service_name":"Mike
salon"},{"error":false,"service_name":"Michel
salon"},{"error":false,"service_name":"Michel
salon"},{"error":false,"service_name":"Mike Salon"},
{"error":false,"service_name":"Etta Salon"}]
Kindly help me to get a proper response form for json .
Thanks
Don't json_encode() the single results, but put them into an array and finally json_encode() that:
<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response[] = [
'error' => FALSE,
'service_name' => $salon_name,
// you may want to add more attributes here...
];
}
echo json_encode($response);
I personally suggest to shorten this:
<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
$response[] = [
'error' => FALSE,
'service_name' => ucfirst($row['service_name']),
'salon_id' => $row['id'],
'salon_address' => ucwords($row['address']),
'salon_area' => ucwords($row['area']),
'salon_city' => ucwords($row['city']),
'salon_specialty' => ucwords($row['specialty']),
'img' => $row['image_url'],
];
}
echo json_encode($response);
You are trying to encode single results, Try to create a array will all the results and encode it out side the loop.
while ($row=mysqli_fetch_assoc($searching_user)) {
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response["error"] = FALSE;
$response["service_name"]=$salon_name;
// Added this line
$responses[] = $response;
}
//Encode all results
echo json_encode($responses );

Codeigniter result array return only one row

Am trying to encode an array to json for use with jquery.
This is the function from my model
function get_latest_pheeds() {
$this->load->helper('date');
$time = time();
$q = $this->db->select("user_id,pheed_id,pheed,datetime,COUNT(pheed_comments.comment_id) as comments")
->from('pheeds')
->join('pheed_comments','pheed_comments.P_id=pheeds.pheed_id','left')
->group_by('pheed_id')
->order_by('datetime','desc')
->limit(30);
$rows = $q->get();
foreach($rows->result_array() as $row) {
$data['user_id'] = $row['user_id'];
$data['pheed_id'] = $row['pheed_id'];
$data['pheed'] = $row['pheed'];
$data['comments'] = $row['comments'];
$data['datetime'] = timespan($row['datetime'],$time);
}
return $data;
}
And this is from my controller
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
echo json_encode($data);
return false;
}
}
It returns only 1 row from the database when I run the code in the browser.
Please help me out
You are overwriting data in every iteration !!
Use something like
$data[] = array(
'user_id' => $row['user_id'];
'pheed_id' => $row['pheed_id'];
'pheed' => $row['pheed'];
'comments' => $row['comments'];
'datetime' => timespan($row['datetime'],$time);
) ;
This is good but your syntax should be 'user_id' => $row['user_id'], for each element of the array

Categories