Jump to content

B_CooperA

Members
  • Posts

    57
  • Joined

  • Last visited

Posts posted by B_CooperA

  1. I don't have any experience working with CakePHP, but in the example you followed: 

     

     

    Create users_controller.php in your app/controllers folder with following codeset.

    <?php
    class UsersController extends AppController
    {
    var $name='Users';
    function index()
    {
    }
    }

    ?> 

     

     

    Since the error is pretty straightforward, you should check that you have named your controller right. 

  2. My goal is to load the actual content of my views and change the browsers URL without reloading the page. However, because I'm using CodeIgniter as a framework of my application, I can't get it to work properly. I have a controller where I'm loading all of my Dashboard's views, ones I want display inside my div called content_container.

     

    Right now, I can get the content of each view with ajax request, but it doesn't change the actual URL (of course it doesn't) How should I implement this to get this to work properly with URL:s?

     

    Here's the controller:

     



    <?php
     
    class Dashboard extends CI_Controller {
     
        public function __construct()
        {
     
            parent::__construct();
            $this->output->nocache();
            $this->load->model('subject_model');
            $this->load->model('user_model');
        }
     
     
        public function index()
        {
     
            $this->load->view('header');
            $this->load->view('dashboard');
            $this->load->view('footer');
        }
     
        public function users() 
        {
     
            $data['users'] = $this->user_model->getUsers();
            $this->load->view('staff_users', $data);
        }
        public function lomake()
        {
     
            $this->load->view('lomake');
        }
     
        public function profile()
        {
     
            $data['userinfo'] = $this->user_model->getUserInformationById($this->session->userdata('user_id'));
            $this->load->view('myprofile', $data);
        }
     
        public function subjects()
        {
     
            $this->load->view('subjects');
        }   
    }
    ?>


     

    And here's my dashboard view (part of it):

     



    <aside id="left_control_panel">
     
        <ul id="left_control_links">
            <li>
            <a href="home" id="ajax" class="active">Home</a>
            </li>
            <li>
            <a href="dashboard/subjects" rel="tab">Subjects</a>
            <span class="list_total_count"><?=$total_subjects?></span>
            </li>
     
            <li>
            <a href="dashboard/lomake" id="ajax">Query</a>
            </li>
     
        <?php if($this->session->userdata('user_type') == 'admin'):?>
     
            <span class="left_control_heading">User management</span>
            <li>
            <a href="dashboard/users" rel="tab">Users</a>
            <span class="list_total_count"><?=$total_users?></span>
            </li>
     
            <li>
            <a class="add_user" href="add_user">Add User</a>
            </li>
        <?php endif;?>
     
            <span class="left_control_heading">Account management</span>
            <li>
            <a href="dashboard/profile" rel="tab">My Profile</a>
            </li>
     
            <li>
            <a href="<?=base_url()?>users/logout">Sign Out</a>
            </li>
        </ul>
    </aside> <!-- end of left_control_panel -->
     
    <div id="wrapper_loggedin">
            <div class="content_container">
            <! -- I will display all the data from different views in here -->
            </div>
    </div> <!-- end of wrapper_loggedin -->


     

     And the JS to load the content from different views into div called "center_container"

    $("a#ajax").bind("click", function(e) {
        e.preventDefault();
     
        $("#loading_spinner").show();
        var url = $(this).attr("href");
     
    $.ajax({
     
            url: url,
            type: "GET",
            async: false,
            data: url,
          success: function(data) {
     
          $("#loading_spinner").hide();
     
          $('.content_container').hide();
          $('p.where_am_i').html(url);
          $('.content_container').html(data).fadeIn(300);
         
     
          }
          });
         
        return false;
     
        });


     

    application/config/routes.php (although I think it isn't set up properly)

     



    $route['dashboard'] = 'dashboard/index';
    $route['dashboard/(:any)'] = 'dashboard/$1';


     

  3. I asked this earlier at StackOverflow but didn't got any solutions from there, so I decided to post my problem in a more appropriate forum. 

     

    So, I have form for my project where I can create users into database. There

    are three types of user types, admins, moderators and end users. 

     



    CREATE TABLE IF NOT EXISTS users (
     
     id SMALLINT(5) UNSIGNED PRIMARY KEY AUTO_INCREMENT,
     name VARCHAR(70) NOT NULL,
     email VARCHAR(70) NOT NULL,
     username VARCHAR(9) NOT NULL,
     password VARCHAR(60) NOT NULL,
     user_type ENUM('admin','moderator','enduser'),
     phone_number VARCHAR(10) NOT NULL,
     
     school_id SMALLINT(5) UNSIGNED DEFAULT NULL,
     CONSTRAINT fk_school_id
     FOREIGN KEY (school_id)
     REFERENCES schools(id)
     ON UPADTE CASCADE ON DELETE RESTRICT,
     
     subject_id SMALLINT(5) UNSIGNED DEFAULT NULL,
     CONSTRAINT fk_subject_id
     FOREIGN KEY (subject_id)
     REFERENCES subjects(id)
     ON UPDATE CASCADE ON DELETE RESTRICT
     
    ) ENGINE = INNODB;


     

    So the school_id and subject_id are working as foreign keys.

     

    Here's my model:

     

     



    <?php

      class User extends CI_Model {
     
       public function add_user($data) {
     
       $data = array(
         'username' => $data['username'],
         'name' => $data['name'],
         'email' => $data['email'],
         'password' => $data['password'],
         'user_type' => $data['user_type'],
         'phone_number' => $data['phone_number'],
         'subject_id' => empty($data['subject']) ? null : $data['subject'],
         'school_id' => empty($data['school']) ?  null : $data['school']
        );
     
       $this->db->insert('users', $data);
      }
     }
    ?>


     

     

    Here's my controller (part of it actually):

     



         $this->load->model('user');
     
          $name = ucfirst($this->input->post('f_name')). " " .ucfirst($this->input->post('l_name'));
     
          $data = array (
            'name'    => $name,
            'email'   => $this->input->post('email'),
            'username'   => $username,
            'password'   => $this->phpass->hash($password),
            'user_type'  => $this->input->post('user_type'),
            'phone_number'  => $this->input->post('phone_number'),
            'school_id'  => $this->input->post('school'),
            'subject_id'  => $this->input->post('subject')
           );
     
          if($this->user->add_user($data))
          {
                        // Send email to user
                    }


     

     

    My first thought was that it's not working because of my another model and controller designed to fetch all those subjects and schools from the database. I will include them in here as well, just in case: 

     

     



    <?php
     
    class Dashboard extends CI_Controller {
     
     public function __construct()
     {
     
      parent::__construct();
      $this->load->model('subject');
     }
     
     public function index() {
     
      $data['subjects'] = $this->subject->get_all_subjects();
      $data['schools'] = $this->subject->get_all_schools();
     
       $this->load->view('header');
      $this->load->view('dashboard', $data);
      $this->load->view('footer');
     } 
    }
     
    ?>


     



    <?php
     
    class Subject extends CI_Model
    {
     
     public function get_all_subjects()
     {
      $this->db->select('*')->from('subjects')->order_by('name', 'asc');
      $query = $this->db->get();
      return $query->result_array();
     }
     
     public function get_all_schools()
     {
     
      $this->db->select('*')->from('schools')->order_by('name', 'asc');
      $query = $this->db->get();
      return $query->result_array();
     }
    }
     
     
    ?>


     

    And the view for my dashboard where that add user form locates:

     



    <?php echo form_open('users/add_user', $attributes); ?>
     
        <span class="close_form_button_add_user_form">X</span>
     
        <?php echo validation_errors('<div class="login_error">', '</div>'); ?>
     
        <div class="form_row">
        <input type="text" name="f_name" placeholder="Etunimi" class="half-width" />
        <input type="text" name="l_name" placeholder="Sukunimi" class="half-width"  right; margin-right: 24px;"/>
        </div>
     
     
        <div class="form_row">
        <input type="email" name="email" placeholder="Uuden käyttäjän sähköpostiosoite" class="user full-width" />
        </div>
     
     
        <div class="form_row">
        <input type="email" name="email_confirm" placeholder="Sähköpostiosoite uudelleen" class="user full-width" />
        </div>
     
        <div class="form_row">
        <input type="text" name="phone_number" placeholder="Puhelinnumero (0401234567)" class="full-width" />
        </div>
     
     
        <div class="form_row"  20px;">
        <select name="user_type" class="add_user_select" id="select_user_type">
            <option value="">Käyttäjätyyppi</option>
            <option value="admin">Hallinto</option>
            <option value="moderator">Hallinto 2</option>
            <option value="enduser">Pääkäyttäjä</option>
        </select>
     
        <input type="submit" name="add_user" value="Luo käyttäjä" class="login_submit" id="submit_user"  5px 24px 0px 0px;"/>
        </div>
     
        <div class="form_row" id="add_user_optional_information">
        <select name="school" class="add_user_select half-width">
            <option value="">Koulutalo</option>
            <?php  foreach($schools as $school) :?>
            <option value="<?=$school['id']?>"><?=$school['name']?></option>
            <?php endforeach; ?>
        </select>
     
        <select name="subject" class="add_user_select half-width">
            <option value="">Laji</option>
            <?php  foreach($subjects as $subject) :?>
            <option value="<?=$subject['id']?>"><?=$subject['name']?></option>
            <?php endforeach; ?>
        </select>
        </div>
     
    <?php echo form_close(); ?>


     

    After I submitted my form, I opened the developer tab, and checked what values were included in this post request and everything looked good in there. For some reason, it will always saves those subject_id and school_id as NULL.

     

     

    Thanks in advance !

  4. You should validate that it is the value you think it is. Try adding a line right after you define from

     

    var from = $(this);

    alert(from.attr('action'));

     

    If that isn't alerting the value you expect then that's the source of your problem. If it is the value you expect, then go to the next logical step in the process and verify the data.

     

     

    I alerted the form action, and yes it was directing into that forgot_pass method.. Could it be that the error is caused by that login method? Every time I submit the button and take a look at developer tools tab, the referer line is always indicating to that login method? Am I loading the views wrong?

     

    Here's my whole controller:

    <?php
    
    	class Users extends CI_Controller {
    
    
    	
    	public function login() {
    
    		$data['error'] = 0;
    				
    		if(isset($_POST['submit'])) {
    
    		        $this->load->model('user');		
    					
    		        $email = $_POST['email'];	
    			$password = $_POST['password'];	
    
    						
    
    			$user = $this->user->login($email, $password);	
    					
    
    				if(!$user) {
    
    				$data['error'] = 1;		
    					
    
    				} else {
    
    				echo "Kirjautuminen onnistui";
    		
    				}
    
    			}
    
    			$this->load->view('header');
    			$this->load->view('index', $data);
    			$this->load->view('footer');
    
    		}
    			
    
    
    		public function forgot_pass() {
    
    			
    			if(isset($_POST['to_submit'])) {
    
    				$this->load->model('user');
    
    				$email = $_POST['to_email'];
    
    				$email_addr = $this->user->get_email_address($email);
    
    				        if($email_addr) {
    
    					$this->load->library('email');
    
    				$this->email->from('your@example.com', 'Your Name');
    				$this->email->to($email);  
    				$this->email->subject('Test');
    				$this->email->message($email_addr[0]['password']);	
    
    					if($this->email->send()) {
    									
    						echo "1";
    
    					} else {
    
    						echo "0";
    					}
    				}
    			}
    
    			$this->view->load('header');
    			$this->view->load('index');
    			$this->view->load('footer');
    		}
    
    
    	}
    ?>
    
  5.  

    Well, I don't see how that class gets called from the AJAX request. It may not be getting used at all for all I know. You could do a couple of quick tests to see what is happening.

    Change the success condition in the AJAX call to alert() the returned value. Then you can verify what, if anything, is being returned. If you do get a 0 response then change the PHP method to return the $_POST['to_email'] value (with the alert still in place) so you can verify the AJAX is passing the value correctly. If you aren't getting anything inthe alert() then that method is not getting called.

     

    Well, yeah, I got an empty alert().

     

    I thought ajax would grab the method in here:

    url: from.attr('action')

    So the question is how do I call that method so that ajax can get the value from that forgot_pass() method?

  6. As to your problem, what debugging have you done so far and what did you find? We can't solve your problem since we don't know what the results are. So, pick one place of possible failure and verify what is or is not happening. Here is the break-down as I see it should go:

    1. The JavaScript makes a call to a PHP page passing the email value

    2. The PHP page takes the email value, performs operations and returns a 1 or 0

    3. The JavaScript page takes the return value to determine what to show/hide

     

     

    Well, the script works perfectly without the ajax. So the PHP file itself is working properly. 

     

    Edit: After reading the PHP file, all it contains is a class. Is that the file that is called from the AJAX request? If so, the class is never instantiated or called. So, that page would simply return nothing.

     

     

    The method forgot_pass() is called from the AJAX request.. And since I'm using CodeIgniter (MVC pattern), why should I instantiate the class? 

     

     For example, why is there a foreach() loop on something that should only include a single record?

     

     

    Yeah I know foreach() loop isn't the most fanciest way to loop if there are only record one. I could of use while() loop instead

  7. I've made a form with CodeIgniter to retrieve users password and send it to the given email address. However, if I'm trying to send the request with Ajax, it doesn't work. It is working without the Ajax part.

     

    Form:

     

    <form action="<?=base_url()?>users/forgot_pass" method="post" id="forget_pass_form">
    
    
    
    
    
    
    <div class="form_header">
    
    <h1>Unohditko salasanasi?</h1>
    
    </div>
    
    <p>Tilaa uusi salasana syöttämällä sähköpostiosoitteesi</p>
    
    <div class="front_success" style="display:none" id="forgot-pass-success">
    
    
    <p>Salasana on lähetetty antamaasi sähköpostiosoitteeseen.</p>
    
    
    </div>
    
    <div class="login_error" style="display:none" id="forgot-pass-error">
    
    
    <p>Sähköpostiosoitetta ei löytynyt järjestelmästämme.</p>
    
    
    </div>
    
    <div id="loading_spinner"></div>
    
    
    <p><input type="text" name="to_email" placeholder="Sähköpostiosoite" class="user" style="background-postion: -200px; margin-top: 20px;" />
    
    
    <input type="submit" name="to_submit" value="Lähetä salasana" class="login_submit" id="forget-pass" /></p>
    
    
    </form>

    Here's the controller to handle the form:

     

    <?php
    
    
    class Users extends CI_Controller {
    
    public function forgot_pass() {
    
    
    if($_POST['to_submit']) {
    
    
    $this->load->model('user');
    
    
    $email = $_POST['to_email'];
    
    
    $email_addr = $this->user->get_email_address($email);
    
    
    if(!empty($email_addr)) {
    
    
    foreach($email_addr as $row) {
    
    
    $this->load->library('email');
    
    
    $this->email->from('your@example.com', 'Your Name');
    $this->email->to($email);  
    $this->email->subject('Password');
    $this->email->message($row['password']); 
    
    
    if($this->email->send()) {
    
    echo "1";
    
    } else {
    
    echo "0";
    }
    
    
    }
    }
    
    }
    
    } 
    
    }
    
    ?>

    And here's the JS file:

     

    $(document).ready(function() {
    
    $("form#forget_pass_form").on('submit', function(){
    
    
    var from = $(this);
    
    $.ajax({
    
             url: from.attr('action'),
             type: from.attr('method'),
             data:$(from).serialize(),
             beforeSend: function(){
    
    
                             $("#loading_spinner").show();
    
                     },
             success: function (data) {
    
                   if(data == '1'){
        //if the email is send then it return 1 so that you show success msg
    
    
                   $(".front_success").show();
                     } else {
       //if the email is not send then it return 0 so that you show error msg
    
    
                   $("#forgot-pass-error").show();
                   }
            $("#loading_spinner").hide();// hide when ajax complete
    
    
                  }
         });
         return false;
    
         });
    
    }); 
    Each and everytime it will show that "login_error" div even though I have typed my email address correctly. Any help would be appreciated
     

  8. <?php

    class User {


    public function Register() {

    // do something


    }

    public function Login() {

    // do something


    }

    public function Logout() {

    // do something

    }

    public function CheckIfLoggedIn() {

    // do something

    }

    public function ChangePassword() {

    // do something

    }

    }

    ?>

     

  9. Hello, guys. I recently started to take a closer look into the world of AJAX. I'm trying to create a live search application, but for some reason it doesn't return the values from the database although it's still does something when I checked it with Googles "Inspect Element" tool. The only response I got with that tool is "This request has no responsive data available".

     

    I have two files, index.php and search.php. Underneath, I've pasted both of them. The search engine works fine without AJAX, tested that while ago.

     

    index.php 

    <!DOCTYPE html>
    <html>
    <head>
    <title>Ajax Search Engine</title>
    <link rel="stylesheet" type="text/css" href="css/style.css" media="all" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    
    <script type="text/javascript">
    $(document).ready(function() {
    
    	$("#search").on("keyup", function() {
    
    		var search = $("#search").val();
    
    		$.ajax({
    			type: "POST",
    			url: "search.php",
    			data: {search:search},
    			success: function(res) {
    
    				$("#userslist").html(res);
    			}
    
    
    		});
    
    	});
    });
    </script>
    </head>
    <body>
    
    <div id="search">
    
    	<input type="text" name="search" id="search" placeholder="Search for users...">
    	<button type="submit" class="search-icon"><span class="magnifier"></span></button>
    
    
    
    </div>
    
    <div id="userslist">
    
    </div>
    </body>
    </html>
    

    search.php

    <?php
    
    	try {
    
    		$conn = new PDO("mysql:host=localhost;dbname=search","root", "");
    
    
    	} catch (Exception $e) {
    
    		$e->getMessage();
    	}
    
    if(isset($_POST['search']) && $_POST['search'] != "") {
    
    	$stmt = $conn->prepare("SELECT * FROM users WHERE username LIKE :name ");
    	$stmt->execute(array(
    			':name' => '%'.$_POST['search'].'%'
    		));
    
    	if($stmt->rowCount() == 0) {
    
    		echo "No users was found";
    
    	} else {
    
    		while($data = $stmt->fetch()) {
    		?>
    
    		<div class="user-details">
    		<img src="images/<?php echo $data['userimg'];  ?>" class="small-img" />
    		<span class="username"><?php echo $data['username'];?></span>
    		<span class="location"><?php echo $data['location'];?></span>
    		</div>
    
    <?php
    	}
    
    }
    
    }
    
    
    ?>
    
  10. Just create the checkboxes, give them a name and a value based on the id of it's row. Then create a new php file like update.php or so

    and refer to that in the form action part. Then run a check if the submit button is pressed and remember to name your submit button.. If so update the date and time for that specific row

    if(isset($_POST['submit'])) {
    
    $id = $_POST['id'];
    $timestamp = date("Y-m-d G:i:s");
    // Create the PDO object
    
    $connect = new PDO (DB_DSN, DB_USER, DB_PASS); // Define your own constants
    
    try {
    $query = "UPDATE software SET timestamp = :timestamp WHERE SoftwareID = :id";
    $stmt = $connect->prepare($query);
    $stmt->execute(array(
        ':timestamp' => $timestamp, // Bind the value
        ':id' => $id  // Bind the value 
    ));
    
    } catch (PDOException $e) {
       $e->getMessage();
    }
    
    // Let's do a rowCount
    $rows = $stmt->rowCount();
    
    if($rows == 1) {
    echo "Date and time was updated";
    } else {
    echo "Boo! Nothing happened";
    }
    
    }
  11. Moving to PDO requires a lot of rewrites and has no benefits, so I'd suggest moving to mysqli instead (and to be careful about using prepared statements, they are not supposed to be the default choice)

     

    Well, this totally depends on user. Will it be bad practice to rewrite your SQL queries again with PDO since you're learning while you're rewriting them? I think not. But that's totally up to user. When I figured out that the mysql functions are going to be deprecated, I didn't even hesitate to look up for PDO.

     

    However, both of them will do the thing. 

  12. You might want to have to create those checkboxes first and give them names.. 

     

    f.e.

    <input type="checkbox" name="id_value" />

    and then run the check

    if(isset($_POST['id_value'])) {
    
    // Insert time and date to the database
    
    }

    I also highly recommend that you dump the old mysql functions since they are deprecated in PHP 5.5.. Use PDO instead, the syntax is not hard to learn. For example:

    $query2 = "UPDATE software SET timestamp = '$timestamp' WHERE SoftwareID = '$id'" ;

    can be written with PDO like this:

    // Create the PDO object
    
    $connect = new PDO (DB_DSN, DB_USER, DB_PASS); // Define your own constants
    
    try {
    $query = "UPDATE software SET timestamp = :timestamp WHERE SoftwareID = :id";
    $stmt = $connect->prepare($query);
    $stmt->execute(array(
        ':timestamp' => $timestamp, // Bind the value
        ':id' => $id  // Bind the value 
    ));
    
    } catch (PDOException $e) {
       $e->getMessage();
    }
    

    Also you shouldn't name your variables with the same name as MySQL datatypes.. 

  13. Wow, that's cheap.

     

     

    Well I'm not doing it full-time and I'm still a student of IT so the money isn't so relevant to me, but the learning and understanding of web development :)

     

    And I honestly thought I'm asking too much. Well, seems like it's my time to raise my hourly rate

  14. Well basically there's nothing dynamic there, all just static pages so u shouldn't charge too much. If you need to build up the whole layout (using a Photoshop or something first), I would charge anything between 150 to 200 euros.  

     

    Don't know about the updating charge though, since I have only created pages which user can / are updated by the users itself.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.