Jump to content

maxxd

Gurus
  • Content Count

    991
  • Joined

  • Last visited

  • Days Won

    24

Posts posted by maxxd


  1. Few things here.

    1. I could be wrong, but I think it's too late to call the wp_enqueue_scripts hook after the template is loaded.
    2. In the JavaScript file, your AJAX url value is incorrectly formed - you're using `nova_ajax_url,ajax_url`. You need to use a period between the object and the property, not a comma.
    3. WordPress doesn't know what 'func' means as a parameter passed to the AJAX handlers - it's looking for 'action'.
    4. I don't have the slightest idea what `drop_var` is.
    5. You show a functions file, but there's no AJAX handling in what you've shown. WordPress looks for `wp_ajax_{whatever_your_action_value_is}` and `wp_ajax_nopriv_{whatever_your_action_value_is}` action hooks to handle AJAX functionality.
    6. If you're using setTimeout() to wait for a response to be returned, it's unnecessary - AJAX is asynchronous and the .done() or .fail() chained functions await the promise resolution.

  2. 18 hours ago, davidhb21l6 said:

    interesting that there's outputted blocks for admin or users, i'll have to look into that.

     

    its the header.php file. should be present on every page,in fact it is.. 

    The rest of the JS is coming out OK , such as the config tag,  the initial async line  etc..

    Depending on what theme you're using, it's very possible that that exact code is duplicated across multiple templates, so you could be in the wrong file without knowing it. WordPress doesn't exactly require - or even in a lot of ways promote - good practices when it comes to PHP and coding for the web. And some of the Automattic plugins are the worst offenders (WooCommerce, I'm looking at you), so don't assume it's good just because it came from the same company as WP or it's got a lot of stars.


  3. 2 hours ago, ajetrumpet said:

    $dbHost apparently has to be "localhost".  now why in the hell is that the case!?

    Because the database server is on the same machine as the web server.

     

    2 hours ago, ajetrumpet said:

    have you ever heard of this?

    All the time, actually.

     

    2 hours ago, ajetrumpet said:

    it should be an ip address or domain name, shouldn't it?

    If you feel strongly about using an IP address you can try http://127.0.0.1 and that should work - although honestly, it's GoDaddy so I can't guarantee it.


  4. Are you not getting syntax errors with this? From my formatting of the code, you've got mismatched braces all over the place. It's hard to tell because you're bouncing between using braces and not (please stop doing that), but it looks like there are some nesting issues going on unless I'm mistaken.

    <?php
    $response = array("error" => false , "success" => false , 'redirect' => false);
    
    function post_content($query){
      $query_array = array();
      foreach( $query as $key => $key_value )
        $query_array[] = urlencode( $key ) . '=' . urlencode( $key_value );
      
      return implode( '&', $query_array );
    }
    
    global $API;
    $opts = array('http' =>  array('method'  => 'POST',"header" => "Content-type: application/x-www-form-urlencoded\r\nAuthorization:".base64_encode($API["api_key"].":".$API["secret_key"])."\r\n", "content" => post_content($content)));
    
    return stream_context_create($opts);  // WHAT ARE YOU RETURNING FROM?
    
    }   //WHERE DOES THIS START?
    
    function submit(){
      global $API;
    
      if(empty($captcha) || $captcha == '' || !isset($captcha))
        return array(    "error" => "Please solve the captcha.");
    
      if (empty($_POST['account']) || !ctype_alnum($_POST['account']))
        return array(    "error" => "Invalid account id.");
          
      $checkAccount = checkAccount($_POST['account']);
    
      if (isset($checkAccount["error"]))
        return array("error" => $checkAccount["error"]);
    
      if (isset($checkAccount["success"])){
        $account_unique_id = (isset($_SESSION['kal_id'])) ? $_SESSION['kal_id'] : $checkAccount["success"]; 
        $result = json_decode(file_get_contents($API["API_Domain"] . '/api/generate/vote-rewards-token', false, postParams(array('callback' => $API["callback"],'account_unique_id' => $account_unique_id    ))) , true);
    
      { // WHAT IS THIS FOR?
    
        echo '<br><center><h3>Please wait...</h3></center>';
      }
      if (!empty($result)){
        if (isset($result["response"])){
          if (isset($result["response"]["error"]))
            return array("error" => $result["response"]["error"]);
    
          elseif (isset($result["response"]["success"]))
            return array("redirect" => '<script type="text/javascript">setTimeout(function () { window.location.href = "'.$result["response"]["success"].'";}, 500)</script>');
    
        }
      }
      } //  WHAT?
    }
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['account'])){
      $response = submit();
      if (isset($response['redirect']) && $response['redirect']){
        echo $response['redirect'];
        die;
      }
    }elseif (isset($_GET['return'])){
      $result = json_decode(file_get_contents($API["API_Domain"] . '/api/verify/vote-rewards-token', false, postParams(array('returned_code' => $_GET['return']))) , true);
      if (!empty($result)){
        if (isset($result["response"])){
          if (isset($result["response"]["error"]))
            $response['error'] = $result["response"]["error"];
    
          elseif (isset($result["response"]["success"])){
            insertRewards($result["response"]["account_unique_id"]);
            $response['success'] = '<b>Thank you, Your vote has been recorded and the server rank will be updated soon.<b><br />You will receive your rewards in storage of your account.<p>Your next vote in : <b>' . $result["response"]["NextVote"] . '</b></p>';
          }
        }
      }
    }
    ?>

     


  5. Do you really have to support IE6 or is the book you're using just really old? I've not seen that structure in forever; honestly I think that exact code is one of the main reasons jQuery blew up as big as it did as quickly as it did.


  6. Hi y'all. So I'm currently working a project in CodeIgniter and I can't get the frigging thing to pass data from a form. At all.

    My autoload.php:

    $autoload['helper'] = [
      'text',
      'form',
      'url',
    ];

    Here's the view code:

    <header>
    	<div>
    		<?php
    			print form_open('/location/change', ['id'=>'location']);
    			print form_label('Location', 'locations');
    			print form_dropdown('locations', $locations, (!empty($_SESSION['location'])) ? $_SESSION['location'] : '');
    			print form_submit('change_location', 'Change');
    			print form_close();
    		?>
    	</div>
    </header>

    The route:

    $route['location/change']['post'] = 'location/change';

    And the controller code:

    class Location extends CI_Controller{
       public function change(){
    
        $this->output->enable_profiler(true);
    
        $vars = $this->input->post();
    
        print("<pre>".var_export($_POST, true)."</pre>");
        print("<pre>".var_export($vars, true)."</pre>");
      }
    }

    The output:

    array (
    )
    
    array (
    )

    WTF? This is quite literally the simplest thing to do - I just want to pass data... Any ideas why it's not working?


  7. 21 minutes ago, ginerjm said:

    Saving html code in a db is mind-boggling to me.

    Not to be a pedantic ass, but sometimes the data is client-created HTML content. Any CMS runs into this, and a lot of application-style sites I've worked on (including my current job) offer clients the option of customizing display text where it makes sense, and it can include lists and images and whatnot.


  8. 1 hour ago, benanamen said:
    Quote

    the additional code is not printing.

    How do you expect it to print anything when there is no code to output anything? No echo, no return, no nothing.

    Also, there is no additional code. It's the same code twice. I'll add to benanamen's request and ask that you post the actual code along with the actual problem.


  9. OK - starting to hate Laravel. I've cloned my repo into a fresh directory, nuked all the existing containers, images, bridges, volumes, etc. and run a fresh docker-compose up. Everything's fine until I get to the migration and seeding for a specific table. Remember, this is the exact set of files I've been developing with, only in a different folder. Now, the controller says save does not exist. Everything else works - I can run the migration and seed just fine on the other three tables/controllers/models, just no this one. Here's the controller:

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Issue as IssueModel;
    
    class Issue extends Controller
    {
    
    }

    Again, this system works perfectly in the other directory, but I need to be able to move it - the reviewers should be able to clone the repo, run docker-compose up and have a functional system. What the actual f**k am I missing? Steps I've run, in order:

    composer install
    
    sudo mv .env.example .env
    sed -i -e 's/DB_USERNAME=root/DB_USERNAME=laravel/g' .env
    sed -i -e 's/DB_PASSWORD=/DB_PASSWORD=laravel/g' .env
    sed -i -e 's/DB_HOST=127.0.0.1/DB_HOST=database/g' .env
    sed -i -e 's/DB_PORT=3306/# DB_PORT=3306/g' .env
    
    php artisan key:generate
    
    php artisan migrate:refresh --seed
    

     


  10. namespace Tests\Unit;
    use Tests\TestCase;
    class APITest extends TestCase
    {
       protected $db;
       const DB_URL = "https://sample.testing.edu/db.json";
       public function setUp(): void
       {
           parent::setUp();
           $this->db = json_decode(file_get_contents(self::DB_URL));
       }
       /**
        * The endpoint under test should return JSON of an array of objects containing users ids
        * and their total time
        * [
        *   {'user_id': <int>, 'seconds_logged': <int>},
        *   ... other users ...
        * ]
        *
        * @test
        */
       public function it_should_provide_sum_of_all_users_time()
       {
           $user = $this->db->users[array_rand($this->db->users)];
           $totalSecondsLogged = array_reduce($this->db->timelogs,
             function ($c, $i) use ($user) {
                 return $c + ($i->user_id == $user->id ? $i->seconds_logged : 0);
             }, 0);
           $response = $this->json('GET', '/user-timelogs');
           $response->assertJsonFragment([
             'user_id' => $user->id,
             'seconds_logged' => $totalSecondsLogged,
           ]);
       }
    }

    There's more to the file, obviously, but this is the test that's  bombing right now. Also, the $this->db stub file contains the same data I'm working with, so there's no issue there, and I think I've rebuilt my composer autoload file like nine or nineteen times, so I'm flat-out stumped. And tired. Mostly tired, but a good portion of that is due to the stumped, so...


  11. Hi y'all. First off, posting this here to hopefully avoid the noise that's happening in the Applications sub-forums, so mods please feel free to move if it's too inappropriate here.

    Anyway, I'm currently doing a skills assessment for a potential new job in Laravel - if I wasn't using Laravel I would've been done hours ago, but one of the requirements is Laravel. Honestly, for the most part I dig it - it's pretty simple, despite it's reliance on magic. Anyway, I've written a couple API routes and when I visit them in the browser everything works exactly as expected and desired. However, when I run the pre-built test file, I get a Symfony\Component\HttpKernel\Exception\NotFoundHttpException for /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php.

    The route as defined in api.php:

    use App\Http\Controllers\User;
    
    /**
     * I tried using a Resource Collection here - there's obviously something about those
     * that I'm missing, because it actively refused to do anything worthwhile. I'd pass in
     * UserModel::with('timelogs')->get() like I use in \App\Http\Controllers\User::getTotalSeconds(),
     * and it didn't care. Just printed out absolute garbage, no matter what I fed to it.
     */
    Route::get('/user-timelogs', function(Request $request) {
        $u = new User;
        return $u->getTotalSeconds();
    });

    And the controller code:

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\User as UserModel;
    
    class User extends Controller
        public function getTotalSeconds()
        {
            $users = UserModel::with('timelogs')->get();
            $ret = [];
            foreach($users as $user){
                array_push($ret, [
                    'user_id' => $user->id,
                    'seconds_logged' => $this->calculateTime($user->timelogs)
                ]);
            };
            return json_encode($ret);
        }
    
        private function calculateTime($logs)
        {
            $totalTime = 0;
            foreach($logs as $log){
                $totalTime += $log->seconds_logged;
            }
            return $totalTime;
        }
    }

    The model file for good measure:

    namespace App;
    
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class User extends Authenticatable
    {
        use Notifiable;
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'name', 'email', 'password', 'id',
        ];
    
        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];
    
        /**
         * The attributes that should be cast to native types.
         *
         * @var array
         */
        protected $casts = [
            'email_verified_at' => 'datetime',
        ];
    
        public function timelogs()
        {
            return $this->hasMany('App\Timelog');
        }
    }

    Again, when I visit localhost/api/user-timelogs, the user IDs and correct total of seconds is right there. It's just in the test file that it's an issue. Anybody have any ideas?


  12. On 9/19/2019 at 11:21 AM, Psycho said:

    Because PHP doesn't have strong distinction between variable types it interprets the string "0" as the integer 0 and is therefore FALSE

    You are absolutely correct - thank you for the correction!

×
×
  • 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.