JSON Response is Undefined - php

I have a issue with JSON response. In am getting undefined values in JSON response. Here is my JS and PHP Code. I have tried every thing but still it giving me undefined value and when I try to console(response) then it displaying complete html.
Here is the Code Of JS and PHP
//Custom JS To Show Modal Update Box
function updateStudentShow($id){
$.ajax({
method:"GET",
url:"view.php",
data:{id:$id},
datatype:"JSON",
success:function(data){
$("#update_name").val(data.name);
$("#update_about").val(data.des);
alert(data.name);
console.log(data);
}
});
$("#update").modal("show");
}
//PHP CODE
<?php
include("connect.php");
$response=array();
if(isset($_GET['id'])){
$id=mysqli_real_escape_string($_GET['id']);
$q="select * from student_details where id='$id'";
}
else{
$q="select * from student_details";
}
$result_students=mysqli_query($con,$q);
while($row_students=mysqli_fetch_assoc($result_students)){
if(isset($_GET['id'])){
$response=$row_students;
}
else{
$id=$row_students['id'];
$name=$row_students['name'];
$des=$row_students['des'];
$image=$row_students['image'];
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $des; ?></td>
<td><img width="60" height="60" src="<?php echo $image; ?>"></td>
<td style="width:20%;">
<a href="javascript:void(0)" onclick="deleteStudent(this.id)" id="<?php echo $id; ?>">
<span style="padding-right:10%;" class="glyphicon glyphicon-trash"></span>
</a>
<a href="javascript:void(0)" onclick="updateStudentShow(this.id)" id="<?php echo $id; ?>">
<span style="padding-right:10%;" class="glyphicon glyphicon-pencil"></span>
</a>
<span class="glyphicon glyphicon-download-alt"></span>
</td>
</tr>
<?php } } ?>
<!--Loop Closed-->
<?php
if(isset($_GET['id'])){
$response=json_encode($response);
echo $response;
}
if(mysqli_num_rows($result_students)==0){
?>
<tr>
<td colspan="5">No Records</td>
</tr>
<?php } ?>

You are outputting the data as html table before echoing your json response.
Your jquery is expecting json only.
To test the output of your script, simply visit the php script in a browser and add the id parameter
http://host/.../view.php?id=1
Overall I think you need to split your code into two files.
One that delivers the javascript and interface.
One that delivers the data (json)
lets call the html output file view.php and the data output file data.php
view.php will contain the javascript which will use data.php in the ajax call to get its json data.
data.php will contain the code to retrieve records from the database and output them as json.

You can't use json_encode() on a table row. Notice up near the top of your html/php, you're doing $row_students=mysqli_fetch_assoc($result_students) followed by $response=$row_students; and then at the bottom you're doing $response=json_encode($response);. See the documentation for json_encode(), which says that the argument value that you pass to json_endcode() can be any type except a resource.
It then links you to the appendix, where you can find out what counts as a resource. The response from mysqli_fetch_assoc() is indeed a resource. It can't be passed to json_encode().

Related

update table row and save in database in php codeigniter

I am making a table from a database and want to add an Edit/delete button to each row update or delete a specific row from the database. I have successfully added working "delete" button but I have no idea how could I update data in table <td> in view and send it to controller.
Here is my code:
view file
<table class="table table-striped">
<tr>
<td>name</td>
<td>age</td>
<td>gender</td>
<td>class</td>
<td>roll no.</td>
</tr>
<?php foreach($record as $r): ?>
<tr>
<td><?php echo $r->name; ?></td>
<td><?php echo $r->age; ?></td>
<td><?php echo $r->gender; ?></td>
<td><?php echo $r->class; ?></td>
<td><?php echo $r->roll no; ?></td>
<td><a href="" >Edit</a>
<a href="<?php echo base_url()."student/deleteRow" ?id="$r->name">"
onclick="return confirm
('Are you sure to Delete?')"><i class="icon-trash"></a></td>
</tr>
<?php endforeach; ?>
</table>
Controller Function
public function deleteRow(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$this->student_model->rowDelete($id);
redirect($_SERVER['HTTP_REFERER']);
}
}
I don't know how can I now insert an input field to update table row without effecting previous view. Any suggestion would be helpful.
To Edit the Studen data you need to pass an id or uniue column name to the data base to get that student data.
First Set the student id in <a href=""> tag.
<td><a href="<?= base_url('student/edit_student') ?>/$r->id" >Edit</a>
Then When you click on the edit it will take you to the controller. You can get the third url parameter direct in as show in the controler code:
You can also use get as shon
Your Controller should be:
public function edit_student($id){
$student_data = $this->student_model->get_student_data($id);
$this->load->view('your_view',['student_data'=>$student_data)]);
}
Here is you model which get the id form controllr and find the student data and passit to back to the controller:
Your Model should be:
public function get_student_data($id){
$this->db->select('*');
$this->db->from('your_table_name');
$this->db->where('id',$id);
$query = $this->db->get();
$student_data = $query->$row_array();
if(isset($student_data) && !empty($student_data)){
return student_data;
} else {
return FALSE;
}
}
Form controller you pass the data to the view.
On View Side:
<?php
// Just to ensure the data. Comment it after testing
echo "<pre>";
print_r($student_data);
echo "</pre>";
?>
<form action="<?= base_url('student/update_student') ?>/<?= $student_data['id'] ?>">
<input name="your_column_name" value="<?= $student_data['your_column_name'] ?>">
// Try to do the same for all you column.
<input type="submit" value="updata">
</form>
Here is the controller for update the data
public function update_student($id){
$student_data = $this->input->post();
$status = $this->student_model->update_student($id,$student_data);
if($status == TRUE){
$this->load->view('your_view');
// Your Success view
} else {
// Your view if fail to update
$this->load->view('your_view');
}
}
Here is the model for update the data
public function get_student_data($id,$student_data){
$this->db->where('id',$id);
$this->db->update('your_table_name',$student_data);
if($this->db->affected_rows() == 1){
return TRUE;
} else {
return FALSE;
}
}
Very similar to what you have done for delete. Something like this:
<td>
<a href="" >Edit/Delete</a>
<!-- This should be another method in Student controller -->
<i class="icon-trash"><!-- I changed order of edit and delete -->
</td>
I need to warn you for CSRF. If you don't implement better security here, anyone pointing to that link would be able to edit or delete data.
Check Security class in documentation and how to set hidden value so that way you would ensure that only one who has already requested that page was able to edit/delete rows.
<td><a href="<?php echo base_url();?>controller_name/function_name/<?php echo $edit_id;?>" >Edit</a></td>
another way
<td><a href="<?php echo base_url();?>controller_name/function_name?id=<?php echo $edit_id;?>" >Edit</a></td>
You can use any one according to your requirement.

how to delete a row in database using codeigniter

hye, i'm trying to do 'delete function' for my modul. i've tried so many different ways for this. but it come out no result, some come with error.
this is my controller (named expert.php) :
public function remove() {
$siri = $this->uri->segment(3);
$this->Kepakaran_m->delete($siri);
$this->view();
}
siri is the a field name (column name) in my table. it it primary key.
this is my model (named Kepakaran_m.php):
function delete($siri) {
$this->dbsmk->where('siri', $siri);
$this->dbsmk->delete('kexpt003pakar');
if ($this->dbsmk->affected_rows() == 1) {
return TRUE;
}
return FALSE;
}
kexpt003pakar is the table name.
so my view is this (named kepakaran.php):
<tbody>
<?php if(empty($kepakaran)) { ?>
<tr>
<td colspan="8">Pengguna tidak mempunyai rekod kepakaran!</td>
</tr>
<?php } else {
$num = 0;
foreach ($kepakaran as $list_kepakaran) {
$num++;
?>
<tr>
<td><?php echo $num; ?></td>
<td><?php echo $list_kepakaran->kategori; ?></td>
<td><?php echo $list_kepakaran->bidang; ?></td>
<td><?php echo $list_kepakaran->spesifik; ?></td>
<!-- untuk keluarkan tahap -->
<td><?php
if($list_kepakaran->tahap=='1'){
echo "Sederhana";
}elseif ($list_kepakaran->tahap=='2') {
echo "Tinggi";
}elseif ($list_kepakaran->tahap=='3') {
echo "Sangat Tinggi";
}
?>
</td>
<!-- done untuk keluarkan tahap -->
<td><?php echo $list_kepakaran->biltahun; ?></td>
<td>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#tambahkepakaran"><i class="glyphicon glyphicon-pencil"></i></button>
<i class="glyphicon glyphicon-trash"></i>
</td>
</tr>
<?php }} ?>
</tbody>
so the delete button is in this area >>siri; ?>" type="button".....
i hope your answer will help me to discover this up. thank you :)
What's the error? I think you just need to modify your codes becomes:
<i class="glyphicon glyphicon-trash"></i>
Then it should be ok.
In order to use uri segment..do not forget to call url helper in autoload.php
english is not my native language.
For solve your problem, you can check a lot of things.
Did you forget to load model in your controller ?
Try to dump value of $siri in your remove function and show response on your network tab in chrome devTools for example.
If you don't call your controller, look at side of your href or open Application/config/routes.php for use routing and add this $route['expert/remove/(:num)']['GET'] = "expert/remove/$1";
If $siri is empty look at the side of $this->uri->segment(3);
Verify if you load correctly the helper.
For that, go to Application/config/autoload.php and see if url is in helper $autoload['helper'] = array('url','security','language', 'form', 'text');

Image links change to an image that exists

This is a really bizarre issue that I've been having.
It happens to images that seem to have a name that is similar to something else.
For instance, if I have an image named image0001.png and I try to display an image with the source of image0010.png - which doesn't exist - then the image does not display as nothing, or fire onerror image, instead it displays as image0001.png which does exist.
I have no idea how to to fix this because I don't really know what is going on.
I am using the following code to fetch results from the database and produce a table with item details.
<?php while ($row = $retval->fetch_array()) { ?>
<tr>
<td>
<?= $row['id']; ?>
</td>
<td>{$row['name']}</td>
<td>
<a href="/path/to/item/<?= $row['id']; ?>.php">
<img src="/images/<?= $row['id']; ?>.jpg" onerror="this.src='/images/error.png';">
</a>
</td>
<td><?= $row['description']; ?></td>
</tr>
<?php } ?>
Sounds like mod_speling is enabled on your server.
Requests to documents sometimes cannot be served by the core apache server because the request was misspelled or miscapitalized. This module addresses this problem by trying to find a matching document, even after all other modules gave up.
Documentation
You can try to disable this apache module in a .htaccess file:
CheckSpelling Off
The obvious other alternative is to use file_exists, removing the reliance of JavaScript and ensuring that the image is shown if it exists or an error image if not.
<?php while ($row = $retval->fetch_array()) { ?>
<tr>
<td>
<a href='/path/to/item/<?= $row['id']; ?>.php'><?= $row['id']; ?></a>
</td>
<td>{$row['name']}</td>
<td>
<a href='/path/to/item/<?= $row['id']; ?>.php'>
<?php if (file_exists("/images/{$row['id']}.jpg")) { ?>
<img src="/images/<?= $row['id']; ?>.jpg" />
<?php } else { ?>
<img src="/images/error.png" />
<?php } ?>
</a>
</td>
<td><?= $row['description']; ?></td>
</tr>
<?php } ?>

PHP foreach loop outside loop

I'm trying to wrap my head around PHP and variable scope. Take a look at the following:
<?php foreach ($data as $tip) { ?>
<tr>
<td><?php echo $tip['id']; ?></td>
<td><?php echo $tip['title']; ?></td>
<td class="delete"><i class="icon-cross"></i></td>
</tr>
<?php } ?>
This just runs a foreach loop that pulls some information out of the database and displays it in a table. The last table cell has an icon in it for deleting that article. What I'm trying to do is have a modal popup that asks for conformation to delete that specific article but I cannot tie the tip id with the delete button because the modal window sits outside the loop. How can I go about accessing the individual id?
Do this :
<?php foreach ($data as $tip) { ?>
<tr>
<td><?php echo $tip['id']; ?></td>
<td><?php echo $tip['title']; ?></td>
<td class="delete" onclick="deleteArticle(<?php echo $tip['id'] ?>)">
<a href="#deleteModal" class="modal">
<i class="icon-cross"></i>
</a>
</td>
</tr>
<?php } ?>
<script>
function deleteArticle(id){
// now you can do what ever you want to do with this id
}
</script>
There is a built it javascript function called "confirm".
If you're using JQuery (And I assume you are) try this:
$('.delete').click(function(){
var check = confirm("Are you sure you want to delete this article?");
if(check)
{
// you code here
}
else return false;
});

Problem with jquery load function

I have a page where I use the jquery load function to load data from a php file. The problem is that it does not always return the correct number of results. I have tried receiving the data straight from the php file and that worked perfectly. What could cause this problem with the load function?? It should only return a max of 5 entries.
s_showLoader();
$("#s_content").load("sdata.php", {s_page:1, user:fbusername}, s_hideLoader);
The show and hide loader functions just show and hide a gif loader. page is the page of pagination to display and user is just used to verify the user is logged in.
UPDATE 1:
Here is example of what the sample return looks like. It is in a while loop and is generated for each entry that is returned.
<table border="0">
<tr><td width="500">
<?php if($s_rows['name']){ echo $s_rows['name']; }else{ echo "User"; } ?><?php echo " | <a id='s_datedata".$s_idnum."'>".$s_rows['date']."</a>"; ?>
<div class="s_label<?php echo $s_idnum; ?>"><?php echo $s_display; ?></div>
<br>More Info...<br>
<div class="list_con" id="s_condata<?php echo $s_idnum; ?>"><?php echo $s_rows['content']; ?></div>
<div class="list_tags" id="s_contags<?php echo $s_idnum; ?>"><?php echo $s_rows['tags']; ?></div>
</td>
<td width="10" align="right"><!-- delete button if correct user is logged in-->
<?php
if($user && ($fbuser == $s_rows['fb_id']) ){
//show delete button
?>
<img src="close-icon.png" title="Click here to delete your listing" class="delopt" id="<?php echo $s_idnum; ?>" onclick="return del_list(<?php echo $s_rows['id']; ?>,<?php echo $s_rows['fb_id']; ?>)" height="25" width="25" alt="delete" border="0">
<?php
}else{
//echo $fbuser."|".$rows['fb_id'];
}
?>
</td>
</tr>
</table>
UPDATE 2:
This is the only POST variable in the php file. The rest of the data comes from the standard facebook api.
$s_page_num = floor($_POST['s_page']);
You can use html content instead of load.
function Load_Content() {
$.ajax({
url: 'yourfilename.php',
cache: false,
data: "s_page="+s_page_value,
success: function (html) {
$("#s_content").html(html);
}
});
}

Categories