Problem with ajax using symfony 1.4 - ajax

I have a very strange problem when I using ajax in symfony 1.4. I've used the jobeet example (day 18) but it doesn't work
This is my indexSuccess.php
<script type="text/javascript" >
$(document).ready(function(){
$('#buscador').keyup(function(key)
{
if (this.value.length >= 3 || this.value == '')
{
$('#per').load( $(this).parents('form').attr('action'),
{ query: this.value + '*' });
}
});
});
</script>
<h1>Lista de personas</h1>
<p>Busque o cree registros de personas en el sistema (Estudiantes, funcionarios, docentes).</p>
<form action="<?php echo url_for('personas/index')?>">
<table>
<tr>
<td><input type="text" name="buscar" id="buscador"/></td>
<td><img src="/images/iconos/Search.png"/></td>
</tr>
</table>
</form>
<p style="font-size: 11px;color: gray;">Digite un nombre, apellido o número de identificación para buscar</p>
<div class="per" id="per">
<?php echo include_partial('personas/buscaPersonas',array('personass'=>$personass)); ?>
</div>
The jquery script detects characters in the input, when I write 3 or more characters it should load the div with id='per'. Here is my personasAction.class.php
public function executeIndex(sfWebRequest $request)
{
$this->personass = array();
if($request->isXmlHttpRequest())
{
$this->personass = $this->getRoute()->getObjects();
return $this->renderPartial('personas/buscaPersonas', array('personass'=> $personass));
}
}
When I load the page I dont want to see any result. So, when I do a ajax call, I should reload the partial "_buscaPersonas.php" with all results (just for try), but I load the _form.php partial.
This is my partial:
<table>
<?php foreach($personass as $personas): ?>
<tr>
<td colspan="5" class="tituloTD"><?php echo $personas->getNombre(); ?></td>
</tr>
<tr>
<th>Numero identificación: </th><td><?php echo $personas->getNumeroid() ?></td>
<th>Email: </th><td><?php echo $personas->getEmail(); ?></td>
<td> <img src="/images/iconos/editar.png"/></td>
</tr>
<?php endforeach; ?>
</table>
I've trying to find where is the problem but I not get it. When I use the button for normal search it works, load the correct partial but whit ajax load other partial.
Please somebody knows what is my error.
thanks

I think this due to the path of your load ajax function:
$('#per').load( $(this).parents('form').attr('action'),
{ query: this.value + '*' });
$(this).parents('form').attr('action') is certainly a wrong value.
Try this :
url_for('personas/index')

Finally I find the error. I dont know what happen but if I send data with the load function I have and error. So I had to send the data using the url, and is works:)
if (this.value.length >= 3 || this.value == '')
{
$('#per').load( "<?php echo url_for('personas/index')?>"+"?query="+this.value);
}

Related

Request tracker REST API: Web Interface to Create New Tickets

I previously had a custom form that users could fill out to place work orders, and once they hit submit, it would create a new ticket with all the information and add it to one of the RT queues.
We previously used Mason to do this, but now we've moved to WordPress and would like to redo this in a cleaner way using PHP.
I read through the API documentation and reviewed this thread along with many others posted on Stack Overflow. I know how to connect to RT and create new tickets via command line and cURL, but I can't seem to figure out how to do so using the web interface on submit. I would really appreciate if someone could give me some pointers on where to start.
Thanks
Edit:
Thank you for the response. Below is the form I've made which interacts with a our SQL database to pull some information and I need it to create a new ticket with all the information on submit. Should I create a new php file similar to [this][2] and include it as a form action?
<form action="<?php echo $_SELF; ?>";
method="post"
id="woForm"
name="woForm"
enctype="multipart/form-data"
>
<input type="hidden" name="session_id" value="<?php echo session_id(); ?>">
<input type="hidden" name="Queue" value="<?php echo $queue; ?>">
<input type="hidden" name="id" value="new">
<input type="hidden" name="Status" value="new">
<input type="hidden" name="Owner" value="10">
<table width="450" align="center" border="0" cellpadding="0" cellspacing="5">
<tr><td align="left" colspan="2">
<h2><?php echo $name; ?></h2>
<p>Please note that all fields except for <b>Ext:</b>, <b>CC:</b> and <b>Attachments:</b> are <span class="required">required</span>.
You cannot submit a request for assistance using this form unless all the required
fields have been completed.</p>
<h2 style="color:red;">Please enter information for the INDIVIDUAL needing assistance</h2>
</td>
</tr>
<?php
// Get all of the customFields
$query1 = "select * from CustomFields where disabled='0' and sortOrder != 0 order by sortOrder ASC;";
$result1 = mysql_query($query1) or die ("dead3: ".mysql_error());
// Go through each custom field
while($row1 = mysql_fetch_array($result1)) {
// Get the information about that field
$count = 0;
$fieldId = $row1['id'];
$name = $row1['Name'];
// $postname is in a very specific format, and will become the name of the field in the form
// where the data for this custom field is entered. In order to submit a ticket into rt, the
// name of the field MUST be in this format.
$postName = "Object-RT::Ticket--CustomField-".$fieldId."-Values";
?>
<!-- Create a row in the table for this custom field -->
<tr>
<!-- Create a column with the name of the custom field -->
<td align="right" class="requestformlabel"><label class="required"><?php echo $name; ?>:</label></td>
<!-- Create a column for the input field -->
<td class = "requestformtd">
<?php
// If the custom field is department or building, we need a pull-down menu
if($name=="Department" || $name=="Building") { ?>
<!-- start of the pull-down menu -->
<select name="<?php echo $postName; ?>">
<?php
// Get all of the possible values for the customField from the database
// Added option to exclude sort order 9999. See ticket #40665 for more info.
$query3 = "SELECT * FROM CustomFieldValues WHERE CustomField='$fieldId' AND SortOrder != '9999' ORDER BY SortOrder ASC";
$result3 = mysql_query($query3) or die ("dead4: ".mysql_error());
// Go through each possible value for the custom field
while($row3 = mysql_fetch_array($result3)) {
// Get the information on the custom field value from the database
$tmp = $row3['Name'];
$description = $row3['Description'];
// If the custom field value was already selected
if($tmp == $_POST["$postName"]) {
// Insert the option into the pull-down menu and mark it as selected in the form
echo "<option value='$tmp' selected='selected'>$description</option>";
// otherwise
} else {
// Only insert it as an option in the pull-down menu
echo "<option value='$tmp'>$description</option>";
}
}
?>
</td></tr>
<?php
// If the name of the custom field is operating system, we want radio buttons
} else if ($name == "Operating System") {
// Get all the possible values for this field form the database
$query4 = "select * from CustomFieldValues where CustomField='$fieldId' order by sortorder asc";
$result4 = mysql_query($query4) or die ("dead5: ".mysql_error());
// For each customfield value
while($row4 = mysql_fetch_array($result4)) {
// Get the description of the customfieldvalue from the database
$osName = $row4['Description'];
// If the customfieldvalue has already been selected
if ($osName == $_POST["$postName"]) {
// Put the radio button into the form and mark it as checked
echo "<input type='radio' name='$postName' value='$osName' checked='checked'>$osName";
// Otherwise
} else {
// Put the radio button into the form
echo "<input type='radio' name='$postName' value='$osName'>$osName";
}
} ?>
</td></tr>
<?php
// If the name of the custom field is ip adress, we want a disbaled text box. This is because while we want the user to see their ip adress, we do not want them to be able to change it.
} else if ($name == "IP_Address"){
?>
<input name="<?php echo $postName; ?>" size="40" value='<?php
echo $_SERVER['REMOTE_ADDR']; ?>' readonly></td></tr>
<?php
// If it's the hostname variable
} else if ($name == "Host_Name"){
?>
<input name="<?php echo $postName; ?>" size="40" value='<?php echo gethostbyaddr($_SERVER['REMOTE_ADDR']); ?>' readonly></td></tr>
<?php
// Otherwise, create a text box for the custom field.
} else {
?>
<input name="<?php echo $postName; ?>" size="40" value='<?php echo $_POST["$postName"]; ?>'></td></tr>
<?php } // end else statement
} // end while loop
?>
<tr>
<td class="requestformlabel" align="right"><label class="required">Your E-mail Address:</label></td>
<td align="left" class="requestformtd"><input name="Requestors" size=40 value="<?php echo $_POST['Requestors']; ?>"></td>
</tr>
<tr>
<td class="requestformlabel" align="right"><label class="required">Confirm Your E-mail Address:</label></td>
<td align="left" class="requestformtd"><input name="Requestors_2" size=40 value="<?php echo $_POST['Requestors_2']; ?>"></td>
</tr>
<tr>
<td class="requestformlabel" align="right"><label class="fields">Cc:</label></td>
<td align="left" class="requestformtd"><input name="Cc" size=40 value="<?php echo $_POST['Cc']; ?>"></td>
</tr>
<tr>
<td align="right"><p> <br/> </p></td>
<td align="right"><span class="ccnote">(Separate multiple email addresses with commas.)<br/> </span></td>
</tr>
<tr>
<td class="requestformlabel" align="right"><label class="required">Short Problem Summary:</label></td>
<td align="left" class="requestformtd"><input name="Subject" size=40 maxsize=100 value="<?php echo $_POST['Subject']; ?>"></td></tr>
<tr>
<td class="requestformlabel" align="right"><label class="required">Decribe the issue below:</label></td>
<td align="left" class="requestformtd"><textarea
class="messagebox" cols=35 rows=15 wrap="hard" name="Content"><?php echo $_POST['Content']; ?></textarea>
</td>
</tr>
<?php
//if session has attachments
if($_SESSION['attach'] != '') {
?>
<!-- row for existing attahcments -->
<tr>
<!-- column that states these are the current attachments, and tells the user what to do if
they wish to remove an attachment. -->
<td class="requestformlabel" align="right">Current Attachments:<br/>
<span class="ccnote">(Check box to delete)</span>
</td>
<!-- coulmn that lists the attachments -->
<td class="requestformtd" align="right">
<?php
// Go through each file in $_SESSION['attach']
while (list($key, $val) = each($_SESSION['attach'])) {
// Get the name of the file
$attName = $val['name'];
// Create a checkbox to mark the file as needing to be removed from the list
echo "<input type='checkbox' name='DeleteAttach-$attName' value='1'>$attName<br/>";
} // end while loop
?>
</td>
</tr>
<?php // end if for attachments
}
?>
<tr>
<td class="requestformlabel" align="right"><label class="fields">Attachments:</label></br>
<span class="ccnote">Max. attachment size: 50MB.</span></td>
<td align="right" colspan="2" class="requestformtd">
<input type="file" name="Attach">
<br/>
<input type="submit" name="AddMoreAttach" value="Add More Files">
</td>
</tr>
<tr>
<td align="left"><input type="submit" name="submit" value="Submit Request"></td>
<td> </td>
</tr>
</table>
</form>
Edit 2:
Thanks. Using the documentation and code from this repo I created a new file called new_ticket.php with the following content:
<?php
if($_POST['action'] == 'call_this') {
require_once 'RequestTracker.php';
$url = "www.test.com/rt/REST/1.0/";
$user = "user";
$pass = "password";
$rt = new RequestTracker($url, $user, $pass);
$content = array(
'Queue'=>'9',
'Requestor'=>'test#example.com',
'Subject'=>'Lorem Ipsum',
'Text'=>'dolor sit amet'
);
$response = $rt->createTicket($content);
print_r($response);
}
?>
I also made of copy of RequestTracker.php from the same Github repo.
In the file where the form is located, I added the following script and added create_ticket() as an action to the onclick property of submit button. But this doesn't seem to be working. I tried logging something to the console to see how far the code gets, the create_ticket() function is being called properly but anything that comes after $.ajax({ ... above will not appear to the console. I also tried putting some console logs in my new_ticket.php file but that doesn't log anything either, so what am I doing wrong?
<script>
function create_ticket() {
$.ajax({
url:"new_ticket.php", //the page containing php script
type: "POST", //request type
data:{action:'call_this'},
success:function(result){
alert(result);
}
});
}
</script>
PS: I'm using ajax because I need to run the PHP code onclick and this can't be done directly as it would in Javascript.
Probably the easiest approach is to look at the PHP examples in the REST documentation on the Request Tracker wiki. You don't mention the version of RT you are using, but the REST interface has been stable so this should work with most versions.

Password failing using Bcrypt

So far bcrypt has had no problems until now. For some reason the following password won't work. UIO78349%^&(]\\';= This is the first time I've had a password not work and I hope somebody has an explanation. I hunted the net and read about the character limit but this is well below that. Not sure if it makes any difference but the user input for password is going through mysqli_real_escape_string.
First batch of code where the login form is located:
<?php
session_start();
?>
<html>
<body>
<form method="post" action="sidebar-signin-block.php">
<table width="90%" border="0" align="center" bgcolor="white">
<tr>
<td bgcolor="ffffff" colspan="2" align="center"><h2>User Login</h2></td>
</tr>
<tr>
<td align="right">Email:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="login" value="Login"></td>
</tr>
<tr>
<td colspan="2" align="center"><h3 style="margin-top:7px;">Forgot Password?</h3></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2" align="center"><div style="padding-top:5px;"><span style="font-size:20px;">Don't have an account?<br />Sign Up is <em>quick</em> and <em>easy</em>!</span></div></td>
</table>
</form>
<?php
// Connecting to the database and making the Bcrypt functions available
include("admin/includes/connect.php");
include ("lib/password.php");
// Gathering and sanitizing user login input
if(isset($_POST['login'])){
$email = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['email']) :((trigger_error ("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
$pass = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['password']) : ((trigger_error ("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
// Checking the database records for the user login input
$hash_query = "select nonadmin_user_pass from nonadmin_user_login where email='$email'";{
$run_query = mysqli_query($conn, $hash_query);}
while ($row = mysqli_fetch_assoc($run_query)) {
$fetch_pass = $row['nonadmin_user_pass'];
}
// If the user email and password matches we start a session
if ((password_verify($pass, $fetch_pass)) == 1){
// Verifying user login success with splash page then sending user back to the home page
$_SESSION['email']=$email;
echo "<script>window.open('login-success.php','_self')</script>";}
// When the user login fails an alert is given to inform them
else {
echo "<script>alert('Email or password is incorrect please try again')</script>";
echo "<script>window.open('index.php','_self')</script>";}
}
?>
</body>
</html>
Here the js.
<script>$(document).ready(function(){
$("#login").click(function(){
var email = $("#email").val();
var password = $("#password").val();
// Checking for blank fields.
if( email =='' || password ==''){
$('input[type="text"],input[type="password"]');
$('input[type="text"],input[type="password"]');
alert("Please fill all fields.");
}else {
$.post("log-me-in.php",{ email1: email, password1:password},
function(data) {
if(data=='Invalid Email.......') {
$('input[type="text"]');
$('input[type="password"]');
alert(data);
}else if(data=='Email or Password is wrong please try again.'){
$('input[type="text"],input[type="password"]');
alert(data);
} else if(data=='Successfully Logged in.'){
window.location.reload();
$("form")[0].reset();
$('input[type="text"],input[type="password"]');
alert(data);
} else{
alert(data);
}
});
}
});
});</script>
Here's the php being called:
<?php
session_start();
// Connecting to the database and making the Bcrypt functions available
include("admin/includes/connect.php");
include ("lib/password.php");
$email=$_POST['email1']; // Fetching Values from URL.
$password= ($_POST['password1']);
// check if e-mail address syntax is valid or not
//$email = filter_var($email, FILTER_SANITIZE_EMAIL); // sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
//if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
//echo "Invalid Email.......";
//}else{
// Matching user input email and password with stored email and password in database.
$result = mysqli_query($conn, "SELECT * FROM nonadmin_user_login WHERE email='$email'");
$data = mysqli_fetch_array($result);
$bcrypt_pass = $data['nonadmin_user_pass'];
$email_match = $data['email'];
if (password_verify ($password, $bcrypt_pass) == 1 AND $email == $email_match) {
$_SESSION['email']=$email;
echo "Successfully Logged in.";
}
else{
echo "Email or Password is wrong please try again";
}
//}
?>
Here is the user registration code where the password initially gets entered before mail verification:
<html>
<head>
<title>Register at Recycling Kansas City</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/styles/register-user.css" media="all">
<!-- ie compatibility -->
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<![endif]-->
<!--[if lt IE 9]>
<script src="Site/javascript/bootstrap/html5shiv.js"></script>
<![endif]-->
<meta content="recycling kansas city, recycling centers, recycling locations" name="keywords">
<meta content="Recycling Kansas City is an efficient resource to help you quickly find a recycle center that is nearby. Use our map to find locations and accepted items." name="description">
</head>
<h1 class="center">Why register at Recycling Kansas City?</h1>
<p>By registering here you will gain access to additional features. Once registered you can create your own custom profile, submit and comment on blog articles, advertise your products or services and have the choice to opt in for email announcements.</p>
<p>All of your information will be securely stored in our database and you can delete your account at any time. Also, rest assured that we will never share any of your submitted details with anyone ever.</p>
<form method="post" action="register-user.php">
<table width="520" border="10" align="center" bgcolor="white">
<tr>
<td bgcolor="ffffff" colspan="2" align="center"><h1>Registration</h1></td>
</tr>
<tr>
<td align="right">Email</td>
<td><input type="text" name="email" size="53"></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input type="password" name="pwd" size="53"></td>
</tr>
<tr>
<td align="right">User Name:</td>
<td><input type="text" name="name" size="53"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="register" value="Register"></td>
</tr>
</table>
</form>
</html>
<?php
include ("../admin/includes/connect.php");
include ("../lib/password.php");
$con = new mysqli("localhost", "$username", "$password", "$database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST['register'])){
$email = trim(mysql_escape_string($_POST['email']));
$nonadmin_user_pass = trim(mysql_escape_string($_POST['pwd']));
$password = password_hash($nonadmin_user_pass, PASSWORD_BCRYPT);
$nonadmin_user_name = trim(mysql_escape_string($_POST['name']));
$query_verify_email = "SELECT * FROM nonadmin_user_login WHERE email ='$email' and verified = 1";
$verified_email = mysqli_query($con,$query_verify_email);
if (!$verified_email) {
echo ' System Error';
}
if (mysqli_num_rows($verified_email) == 0) {
// Generate a unique code:
$hash = md5(uniqid(rand(), true));
$query_create_user = "INSERT INTO `nonadmin_user_login` (`email`, `nonadmin_user_pass`, `nonadmin_user_name`, `hash`) VALUES ('$email', '$password', '$nonadmin_user_name', '$hash')";
$created_user = mysqli_query($con,$query_create_user);
if (!$created_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($con) == 1) { //If the Insert Query was successfull.
$subject = 'Activate Your Email';
$headers = "From: admin#recyclingkansascity.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$url= 'http://recyclingkansascity.com/includes/register-verify.php?email=' . urlencode($email) . "&key=$hash";
$message ='<p>To activate your account please click on Activate buttton</p>';
$message.='<table cellspacing="0" cellpadding="0"> <tr>';
$message .= '<td align="center" width="300" height="40" bgcolor="#000091" style="-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;
color: #ffffff; display: block;">';
$message .= '<a href="'.$url.'" style="color: #ffffff; font-size:16px; font-weight: bold; font-family: Helvetica, Arial, sans-serif; text-decoration: none;
line-height:40px; width:100%; display:inline-block">Click to Activate</a>';
$message .= '</td> </tr> </table>';
mail($email, $subject, $message, $headers);
echo '<p class="center">A confirmation email
has been sent to <b>'. $email.' </b></p><p class="center">Please <strong>click</strong> on the <strong><em>Activate</em> Button</strong> to Activate your account.</p> ';
} else { // If it did not run OK.
echo '<div>You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
}
}
else{
echo '<div>Email already registered</div>';}
}
?>
So far never a hiccup on any password until the password at the top of the post? Weird if you ask me.
Remove all calls to mysqli_real_escape_string() for password input, the functions password_hash() and password_verify() accept even binary input and are not prone to SQL-injection. I assume this already solves your problem. Escaping should be done as late as possible and only for the given target system, so the function mysqli_real_escape_string() should only be called to build an SQL query.
Then the function password_verify() already returns a boolean, no need to compare it with == 1.
if (password_verify($pass, $fetch_pass))
{
...
}
If this doesn't solve your problem, i would make sure that every page uses UTF-8 as file format and defined it in the header.

Joomla - pagination bar not showing up

I'm trying to get pagination working in my joompla component admin page (table of records from database).
I'm using the standard method found on the net, so in my view class I have:
function display($tmpl=NULL)
{
$this->tabela = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
...
and then in my default template for this view:
<tfoot>
<tr>
<td colspan="7" >
<?php echo $this->pagination->getListFooter(); ?>
</td>
</tr>
but the pagination is not showing up. In the place where it should occur I can only see this (in website's HTML):
<div class="pagination pagination-toolbar">
<input type="hidden" name="limitstart" value="0">
</div>
How can I get this pagination work?

Ajax page fails with undefined variable error message

I'm just trying to write my first ajax enabled page. Needless to say, I've run into a problem. And I think it reveals a fundamental misunderstanding of how ajax is supposed to work.
Here's a description of what i'm trying to accomplish.
I have a page with a table containing records from my database. When the user clicks on my refresh button, i want to requery the database for all records and display them without refreshing the page.
Here's my controller:
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('date');
$this->load->helper('url');
}
public function index()
{
$this->load->model('locations_model');
$emess = '';
$data['clienthistory'] = $this->locations_model->get_locations();
$data['main_content'] = 'dashboard';
$this->load->view('includes/template', $data);
$this->output->enable_profiler(TRUE);
}
public function index2()
{
echo('inside the getlatest method');
$this->load->model('locations_model');
$data['clienthistory'] = $this->locations_model->get_locations();
//build HTML table to send back to view
$data['latestdashboardHTML']= "<table class='table table-bordered table-striped'><thead>";
$data['latestdashboardHTML']=$data['latestdashboardHTML'] & "<tr><th>IP</th><th>Name</th><th>Last Updated</th></tr></thead><tbody>" ;
foreach ($data['clienthistory'] as $histitem)
{
$data['latestdashboardHTML'] = $data['latestdashboardHTML'] & "<tr>";
$data['latestdashboardHTML'] = $data['latestdashboardHTML'] & "<td>" & $histitem['network'] & "</td>";
$data['latestdashboardHTML'] = $data['latestdashboardHTML'] & "<td>" & $histitem['name'] & "</td>";
$data['latestdashboardHTML'] = $data['latestdashboardHTML'] & "<td>" & $histitem['lastupdated'] & "</td>";
$data['latestdashboardHTML'] = $data['latestdashboardHTML'] & "</tr>";
}
$data['latestdashboardHTML'] = $data['latestdashboardHTML'] & "</tbody></table>";
$data['main_content'] = 'dashboard';
echo ($data['latestdashboardHTML']) ;
$this->load->view($data['main_content'] );
}
}
And here's the code in my view:
<h2>Client Dashboard</h2>
<br/><p>
<?php echo form_open('Dashboard/index');
echo form_submit('submit', 'Refresh Data', 'id="submit" class="btn-primary"');
?>
</p>
<div class="row-fluid">
<div class="span12" id="ajaxcontainer">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>IP</th>
<th>Name</th>
<th>Last Updated</th>
</tr>
</thead>
<tbody>
<?php foreach ($clienthistory as $histitem): ?>
<tr>
<td><?php echo $histitem['network'] ?></td>
<td><?php echo $histitem['name'] ?></td>
<td><?php echo $histitem['lastupdated'] ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</div>
</div><!--/row-->
<?php
echo form_close();
?>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bs-transition.js"></script>
<script src="../assets/js/bs-alert.js"></script>
<script src="../assets/js/bs-modal.js"></script>
<script src="../assets/js/bs-dropdown.js"></script>
<script src="../assets/js/bs-scrollspy.js"></script>
<script src="../assets/js/bs-tab.js"></script>
<script src="../assets/js/bs-tooltip.js"></script>
<script src="../assets/js/bs-popover.js"></script>
<script src="../assets/js/bs-button.js"></script>
<script src="../assets/js/bs-collapse.js"></script>
<script src="../assets/js/bs-carousel.js"></script>
<script src="../assets/js/bs-typeahead.js"></script>
<script type="text/javascript">
$('#submit').click(function() {
alert('here');
$.ajax({
url:"<?php echo site_url('Dashboard/index2'); ?>",
type: 'POST',
success: function(msg) {
alert(msg);
$('#ajaxcontainer').replaceWith(msg);
}
});
return false;
});
</script>
Problem:
the first time through, the page loads properly. all records show up with the correct values. But when i try the refresh button, the javascript executes, calls the index2 method.. but then it fails in the view on line 22 - which is where I'm trying to loop through the clienthistory array.
The error message is: Undefined variable: clienthistory.
SO here's my question. I thought the way ajax worked was that it only updated a section of the page. So I guess I don't understand why it's "redo-ing" this part of the view.
Can someone explain what I'm doing wrong, and more importantly, if my understanding of ajax is correct. I'd also prefer it if i could combine the two methods into one... i tried but had some problems so I ended up just copying index() to index2() and just working with that.
The other behavior that I'm noticing is that the title "Client Dashboard" as well as the button is showing up twice when execute the ajax method.
Thanks.
I found my problem. In index2() i'm loading the view again.
i shouldn't reload the view. i just need to pass the html string to the caller.
this in part resolves my problem.
so specifically in my controller i replaced:
$this->load->view($data['main_content'] );
with
return $htmlstring;
where $htmlstring contains the same string as $data['latestdashboardHTML']
the other problem is that i needed to specify the dataType that i was expected back from the controller.
so i added the following line to my .ajax function:
dataType: 'html'
Finally, I read online somewhere that it's not a good idea to have the controller create any HTML. this is supposed to be the job of the view.
i guess i will try to pass an array from controller to view. and then have the jquery code recreate the contents of my div.
thanks

Waiting message on slow redirection

I have the following code:
<?PHP
if (isset($_POST['submit'])) {
header("Location: http://mysite.com");
}
?>
<form name="form1" action="" method="post">
Name: <input name="name" type="text">
<input type="submit" value="submit" name="submit">
</form>
The problem is that when I submit the form the redirection to mysite.com takes too long time, 5-10s.
I would like to display a messege "Loading... Please wait" och show an animated image so that I know that something is happening.
How do I do in javascript och ajax?
I don't know if it's possible (but I don't think so) but you could add exit(); after setting the header so the rest of the script isn't executed and sent to the browser. That could reduce the time a bit.
What you could try is to do the redirection with javascript instead of a http header.
<?php if (isset($_POST['submit'])): ?>
<script>
alert('Loading... Please wait');
document.location.href = 'http://mysite.com';
</script>
<?php endif; ?>
5-10 secs to submit the page. First of all try to figure out why it is taking that much time.
ANyways, If you just want to see some message when you press submit button, then simply you can add any div ( with initially hidden ). And on click of submit button you can show this div.
See the sample code:
<?PHP
if (isset($_POST['submit'])) {
header("Location: http://mysite.com");
}
?>
<div id='loadingDIV' style='display: none;'></div>
<form name="form1" action="" method="post">
Name: <input name="name" type="text">
<input type="submit" value="submit" name="submit" onclick='showLoadingAndSubmit();'>
</form>
function showLoadingAndSubmit(){
document.getElementById ('loadingDIV').innerHTML = 'Form submitting. Please wait...';
document.getElementById ('loadingDIV').style.display = 'block';
return true;
}
you should have something like this
the loading has image GIF moving until the ajax request end and then the loading become hidden
where result has the database result grid search on screen
<tr valign="top">
<td id="results" colspan="8" align="center" width="100%" height="250px">
</td>
</tr>
<tr valign="top" id="loading" style="display:none;">
<td colspan="8" width="100%" align="center">
<img name="loading_image" src="images/loading.gif" border="0" width="214" height="200">
</td>
</tr>
function search(tableEvent){
try
{
document.getElementById('loading').style.display="";
var params = 'formAction=' + document.mainForm.formAction.value;
params += '&tableEvent=' + tableEvent;
params += '&txtActionDivisionDesc=' + document.mainForm.txtActionDivisionDesc.value;
createXmlHttpObject();
sendRequestPost(http_request,'Controller',false,params);
ValidationResult();
}
catch(e)
{
alert(e.message);
}
}
function ValidationResult()
{
try
{
if (http_request.readyState == 4)
{
var errors = http_request.responseText;
errors = errors.replace(/[\n]/g, '');
if (window.ActiveXObject)
{// code for IE
xmlRecords=new ActiveXObject("Microsoft.XMLDOM");
xmlRecords.loadXML(errors);
}
else
{
xmlRecords=document.implementation.createDocument("","",null);
parser=new DOMParser();
xmlRecords=parser.parseFromString(errors,"text/xml");
}
document.getElementById('loading').style.display="none";
document.getElementById('results').innerHTML = errors;
http_request = false;
}
}//end try
catch(e)
{
document.getElementById('results').innerHTML = errors;
return;
}
}

Resources