Problem with jquery load function - php

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);
}
});
}

Related

JSON Response is Undefined

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().

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.

Multiple entries added to a single variable?

I am trying to delete separate messages from a users inbox on my website. The user can go to the inbox, turn on the Delete Messages function which will show an extra HTML checkbox. This checkbox will then update the database to delete each message.
The messages and delete function are shown using the code below:
<p>
<a href="<?php echo 'http://basecentre.co.uk/', $message["username"]; ?>">
<img alt="" align="left" hspace="20" height="50" width="50"
src="<?php
echo 'http://basecentre.co.uk/userimages/',
$message["dp"];
?>">
</a>
<font color='<?php if ($message['unread']) echo '#FF0000'; ?>'>
<strong> <?php echo $message['first_name']; ?>
<?php echo $message['last_name']; ?> (
<?php echo date('d/m/Y H:i:s', $message['date']); ?>):
</strong>
</font>
<br />
<input type="checkbox" name="messageid" value="<?php echo $message['id']; ?>">
<?php echo $message['text']; ?>
</p>
The code to process the information is still being worked on, however I have hit a snag. The variable shows only ONE message id when it should actually show a list of all message id's that have been marked. Here is the processing code:
<?
/// DELETE MESSAGES
if (isset($_POST['delmessages'])) {
$delmessage_id = $_POST['messageid'];
echo $delmessage_id;
exit();
}
?>
How can I configure the variable to show more than one message id at a time ? Any ideas would be helpful. Thanks!
instead of
... name="foo"...
in your inputs, you need to use
... name="foo[] "
and all values will be in array $_POST[" foo"]

Print content of a div inside a foreach loop

I have a foreach loop in php. Now I need to print the content of a div for each record separately what I have now is the following:
<script type="text/javascript">
function printContent(div_id) {
var DocumentContainer = document.getElementById("<?php echo $route->flightnum;?>");
var html = '<html><head>' +
'</head><body style="background:#ffffff;">' + DocumentContainer.innerHTML +
'</body></html>';
var WindowObject = window.open("", "PrintWindow", "width=1000,height=1000,top=0,left=0,toolbars=no,scrollbars=yes,status=no,resizable=yes");
WindowObject.document.writeln(html);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
//WindowObject.close();
document.getElementById('print_link').style.display = 'block';
}
</script>
Then I have the following div:
<div id="brief_print" style="margin-left: 15px">
.
.
.
.
.
</div>
And perhaps a link like this:
<a class="glow" style="text-decoration: underline;" href="javascript:printContent('<?php echo $route->flightnum;?>')"id='print_link'>Open in new window for printing</a>
My problem is that when I hit the link I don't get anything in return. Please tell me where I'm wrong.
Thanks
The entire codes:
<?php
foreach($allroutes as $route)
{
?>
<tr>
<td onclick="$('#details_<?php echo $route->flightnum;?>').toggle('slow')">P</td>
<td style="padding:5px 10px" ALIGN="center"><?php echo $route->depicao;?></td>
<td style="padding:5px 10px" ALIGN="center"><?php echo $route->arricao;?></td>
<td style="padding:5px 10px" ALIGN="center"><?php echo $route->aircraft; ?></td>
<td style="padding:5px 10px"ALIGN="center"><?php echo $route->distance;?></td>
</tr>
<tr >
<td colspan="14"><div align="center">
<table cellspacing="0" width="100%" id="details_<?php echo $route->flightnum;?>" style="display:none">
<tr><th style="padding:5px 10px"><div align="center">Flight Details</div></th></tr>
<tr><td>
<section>
<?php
if(!isset($_GET['newwindow']))
{
?>
<a class="glow" style="text-decoration: underline;" href="javascript:printContent('<?php echo $route->flightnum;?>')"id='print_link'>Open in new window for printing</a>
<script type="text/javascript">
function printContent(div_id)
{
var DocumentContainer = document.getElementById("<?php echo $route->flightnum;?>");
var html = '<html><head>'+'</head><body style="background:#ffffff;">'+ DocumentContainer.innerHTML+ '</body></html>';
var WindowObject = window.open("", "PrintWindow","width=1000,height=1000,top=0,left=0,toolbars=no,scrollbars=yes,status=no,resizable=yes");
WindowObject.document.writeln(html);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
//WindowObject.close();
document.getElementById('print_link').style.display='block';
}
</script>
<?php
}
?>
<div id="brief_print" style="margin-left: 15px">
<pre>
<b>Departing</b> : <?php echo $schedule->depname ?>
<b>Arriving</b> : <?php echo $schedule->arrname ?>
<b>Equipment</b> : <?php echo $schedule->fullname;?>
<b>Alternate</b> : <?php echo $alternate1; ?>
<b>Alternate</b> : <?php echo $alternate2; ?>
<b>Alternate</b> : <?php echo $alternate3; ?>
</pre>
</div>
</section>
</td></tr>
</table>
</div>
<?php
}
?>
There are some big problems with your code. You don't seem to understand what is happening when and where. Let me try to explain.
When a client goes to a website, their browser sends a request for the page to your hosting server. Your host server executes the PHP code, producing the source code for the page to be sent to the client's browser. So the page is not sent back to the client's browser until after PHP has completely finished executing. No JavaScript code has executed at this point.
Once the page is sent to the browser (and PHP is done), that's when JavaScript takes over. JavaScript executes on the client-side.
So, once you understand this, you'll realize that you obviously cannot call PHP from JavaScript without making a new request to the server.
Try opening your page in a browser and view the source. You will see that you are defining the JS function printContent() once for every loop iteration. You are also missing closing tags for your second <tr> and <td> tags (add an extra </td></tr> after your last </div>). Perhaps you'll realize all the other problems when you view the source to see what your PHP code is producing.

Permanent changes with "onclick" handler?

I'm attempting to modify an app for facebook that uses php and javascript.
It allows a user to send gifts to each other's wall. When a gift is received, it show's on the app's notification page for that user.
The problem: after a gift is accepted, it still shows on the notifications page. I suppose because it was deemed necessary in order for the point system as well as the history functions to operate properly. It appears that gifts older than 30 days are no longer displayed. I tried to permanently change the date of the gift after it's accepted.
Can anyone please suggest possible ways to:
Option 1. After the gift is accepted, permanently change it to a different image to inform the user "you have already accepted this". Without removing it from the database.
Option 2. Remove the gift from the page (or prevent it from being displayed) after it's accepted...without deleting it from the database. .hide and display:none; are not viable options because the gift will be displayed again...every time the page loads.
Option 3. Last and least desired option, remove the gift from the page and database as well.
The original code for that page is below. The part of the code that I'm guessing needs to be modified is located between the asterisk dividers. I hope it's not too difficult to follow :-/
Thanks for your time.
<?php
if(!isset($facebook))
{
$user_id=$_POST['user_id'];
}
else
{
$user_id=$user_info['UserID'];
}
$news_limit=$current_time-2592000;
$history_query=mysql_query("SELECT * FROM ".$exchange_table." WHERE Time>'$news_limit'
AND ReceiverID='$user_id' ORDER BY Time DESC");
$history_num=mysql_num_rows($history_query); ?>
<div style="font-size:14px;width:720px;padding:10px;<?php echo $background_one; ?>"
align="left">
<div style="font-weight:bold;font-size:16px;color:#6f6f6f;">
<?php echo $nav_info['home']; ?>
</div>
<div style="width:100%;margin-top:10px;" align="center">
<img src="<?php echo $app_info['image_url']; ?>divider.gif">
<img src="<?php echo $app_info['image_url']; ?>divider.gif">
<img src="<?php echo $app_info['image_url']; ?>divider.gif">
</div> <?php
if($history_num>0)
{
$gift_query=mysql_query("SELECT GiftID,Name,Image FROM ".$gift_table." WHERE
Type='1'");
while($gift_info=mysql_fetch_assoc($gift_query))
{
$gift_array[$gift_info['GiftID']]['name']=$gift_info['Name'];
$gift_array[$gift_info['GiftID']]['image']=$gift_info['Image'];
} ?>
<div style=""> <?php
$i=1;
while($history_info=mysql_fetch_assoc($history_query))
{ ?>
<div style="margin-top:10px;">
<div style="float:left;width:75px;">
<img src="<?php echo
$app_info['upload_url'].$gift_array[$history_info['GiftID']]['image']; ?>"
style="width:75px;height:75px;">
</div>
<div style="float:left;margin-left:10px;">
<span style="font-size:18px;"><span id="month<?php echo $i; ?>"></span> -
Gift Received!</span><br>
You received a(n) <b><?php echo $gift_array[$history_info['GiftID']]
['name']; ?></b> from <b><fb:name uid='<?php echo $history_info['FacebookID']; ?>'
linked='false'></fb:name></b>!<br>
**************************************************************
<input id="share_button<?php echo $i; ?>" onclick="shareFeed('<?php echo
$gift_array[$history_info['GiftID']]['image']; ?>','<?php echo $history_info['GiftID'];
?>','<?php echo $gift_array[$history_info['GiftID']]['name']; ?>')" type="image" src="
<?php echo $app_info['image_url']; ?>share_button.png"
onmouseover="convert('share_button<?php echo $i; ?>','share_hover.png')"
onmouseout="convert('share_button<?php echo $i; ?>','share_button.png')"
style="height:29px;margin-top:5px;">
</div>
**************************************************************
<br style="clear:both;">
</div>
<script>
var date_text="";
var time_date=new Date();
var monthNames=
["January","February","March","April","May",
"June","July","August","September","October","November","December"];
time_date.setTime(<?php echo $history_info['Time']*1000; ?>);
document.getElementById('month<?php echo $i; ?
>').innerHTML=monthNames[time_date.getMonth()]+" "+time_date.getDate();
</script> <?php
$i++;
} ?>
</div> <?php
}
else
{ ?>
<div style="font-size:14px;font-weight:bold;margin-top:20px;" align="center">
No giftss received over the past 30 days.
</div> <?php
} ?>
</div>

Categories