Wednesday, June 21, 2017

JavaScript | jQuery: Manual Ajax Form Submit Using XMLHttpRequest | XMLHttpRequest to Post HTML Form | Upload File Ajax | Submit FormData

It's easy to submit an form using JavaScript ajax request. We also can upload files using ajax form submit. Below is a simple code snippet:


<form name="content_info">
    <input type="file" name="file"/>
    <button type="button" onclick="doPost()">Ajax Submit</button>
</form>

<script type="text/javascript">
    function doPost() {
        var form = document.forms.namedItem("content_info");
        var formData = new FormData(form);
        //or formData = new FormData();
        formData.append("custom_param", "custom_param_value");

        var request = new XMLHttpRequest();
        request.open("POST", "submit.php", true);
        request.responseType = "json";
        request.onload = function(oEvent) {
            console.log(request.status);
            console.log(request);
            console.log(request.response);
            alert(request.status);
        };
        request.onerror = function (error) {
            console.log(error);
        };
        request.setRequestHeader("Custom-Code", "EKKODJIU");
        request.send(formData);
    }
</script>




Monday, June 19, 2017

VBScript: Execute Script Using Command Prompt | Execute Script Using Batch File Processing

VBScript: Execute Script Using Command Prompt | Execute Script Using Batch File Processing. It's easy to execute a VBScript file using Windows command prompt. First need to create ".vbs" file. Now create a file named "MyScript.bat" with following code and double click the bat file to execute VBScript.


@ECHO OFF
mode 200,50

cscript.exe MyScript.vbs

pause

exit;








Sunday, June 18, 2017

Laravel 5.X Forward To URL | Redirect To Route | Forward Request | Mock Request | Mock HTTP Request | Dynamic HTTP Request | Laravel Dispatch Request

Laravel 5.X Forward To URL | Redirect To Route | Forward Request | Mock Request | Mock HTTP Request | Dynamic HTTP Request.

It's easy to forward a request using Laravel Route. Forwarding do for you is URL will not change but response will change. The way it is working is that it will mock a request using Request::create(...) and dispatch using current Router.

<?php
namespace App\Http\Controllers;

use Illuminate\Routing\Router;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request as HttpRequest;

class MyController extends Controller {
    public function __construct(HttpRequest $httpRequest, Router $router) {
        $this->middleware('auth', ['except' => ['action1', 'action2']]);

        $this->httpRequest = $httpRequest;
        $this->appRouter = $router;
    }

    //Route=my/need-forward (Create new request and dispatch)
    public function needForward() {
        //http://www.domain.com/my/need-forward
        $route_name = action("MyController@forwardHere");
        //http://www.domain.com/other-folder/my/need-forward
        $route_name = action("OtherFolder\\MyController@forwardHere");
        //http://www.domain.com/my/need-forward/100/Name%20Text?roll=303
        $route_name = action("MyController@forwardHere", ["id" => 100, "name" => "Name Text", "roll" => 303]);
        $request = HttpRequest::create($route_name, 'GET', array("param1" => "Param 1", "param2" => "Param 2"));
        return app()->handle($request);
    }

    //Route=my/need-forward (Forward same request to new route)
    public function needForward2() {
        $route_name = "my/forward-here";
        $request = HttpRequest::create($route_name);
        return  $this->appRouter->dispatch($request);
    }

    //Route=my/forward-here
    public function forwardHere() {
        echo "Browse [/my/need-forward] will send output of [/my/forward-here]";
    }
}


Saturday, June 17, 2017

MySQL Trigger | MySQL Before/After Insert Trigger | MySQL Before/After Update Trigger | MySQL Before/After Delete Trigger

MySQL Trigger | MySQL Before/After Insert Trigger | MySQL Before/After Update Trigger | MySQL Before/After Delete Trigger:


DROP TRIGGER IF EXISTS `example_table_before_insert`;
DELIMITER $$
CREATE TRIGGER `example_table_before_insert`
BEFORE INSERT ON `example_table` FOR EACH ROW BEGIN
  DECLARE ready INT DEFAULT 0;
  DECLARE rnd_str TEXT;
  IF NEW.CODE IS NULL OR CHAR_LENGTH(NEW.CODE) = 0 THEN
    WHILE NOT ready DO
      SET rnd_str := UPPER(SUBSTR(MD5(CONCAT(rand(), now())), 1, 5));
      IF NOT exists(SELECT * FROM example_table WHERE CODE = rnd_str) THEN
        SET NEW.CODE = rnd_str;
        SET ready := 1;
      END IF;
    END WHILE;
  END IF;
END
$$
DELIMITER ;

DROP TRIGGER IF EXISTS `example_table_before_update`;
DELIMITER $$
CREATE TRIGGER `example_table_before_update`
BEFORE UPDATE ON `example_table` FOR EACH ROW BEGIN
  DECLARE ready INT DEFAULT 0;
  DECLARE rnd_str TEXT;
  IF NEW.CODE IS NULL OR CHAR_LENGTH(NEW.CODE) = 0 THEN
    WHILE NOT ready DO
      SET rnd_str := UPPER(SUBSTR(MD5(CONCAT(rand(), now())), 1, 5));
      IF NOT exists(SELECT * FROM example_table WHERE CODE = rnd_str) THEN
        SET NEW.CODE = rnd_str;
        SET ready := 1;
      END IF;
    END WHILE;
  END IF;
  SET NEW.updated_at = now();
END
$$
DELIMITER ;

DROP TRIGGER IF EXISTS `example_table_after_delete`;
DELIMITER $$
CREATE TRIGGER `example_table_after_delete`
AFTER DELETE ON `example_table` FOR EACH ROW BEGIN
  DELETE FROM example_table_associations WHERE example_id=OLD.id;
END
$$
DELIMITER ;



Friday, June 16, 2017

How to Handle Laravel 5.X Exceptions

In Laravel 5.2, all errors and exceptions, both custom and default, are handled by the Handler class in app/Exceptions/Handler.php with the help of two methods ##report & ##render.

The ##report method enables you to log raised exceptions or parse them to error logging engines. 

The ##render method return with an error message as well as response code raised by any exception. It generates a HTTP response from the exception and sends it back to the browser.

We can also override the default behavior of error handling with our own custom exception handler if we need.


/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Exception $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    //$request->ajax() [[AJAX REQUEST CHECK]]
    if ($e instanceof MyException) {
        if ($request->ajax()) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('errors.custom', [], 500);
    }
    if ($this->isHttpException($e)) {
        switch ($e->getStatusCode()) {
            case 404:
                return response()->view('errors.404', [], 500);
            case 500:
                return response()->view('errors.500', [], 500);
            default:
                return $this->renderHttpException($e);
        }
    } elseif ($e instanceof TokenMismatchException) {
        return redirect()->back()->withInput()->with('error', 'Your session has expired');
    } else {
        return response()->view('errors.500', [], 500);
    }
}

And finally you have to add a 404.blade.php && 500.blade.php file in resources/view/errors to represent our custom error page.


We can also generate a 404 as well as 500 error page response by calling the abort method which takes an optional response message.

abort(404, 'The resource you are looking for could not be found');


This will check for a related resources/view/errors/404.blade.php and serve a HTTP response with the 404 status code back to the browser. The same applies for 401 and 500 or for other error status codes.








Laravel 5.X: Access HTTP Session From Controller | Service

It's very important to have access to HTTP session in our Laravel Controller or Service class. Below is a code sample of session access in Controller class. Use of session in Service is similar.


<?php

namespace App\Http\Controllers;

use Symfony\Component\HttpFoundation\Session\Session;

class HomeController extends BaseController
{
    private $Session;
    public function __construct(Session $Session)
    {
        $this->Session = $Session;
    }

    public function setSessionValue()
    {
        $this->Session->set("some_name", "some_value_in_session");
        exit;
    }

    public function getSessionValue() {
        echo $this->Session->get("some_name");
        die();
    }










Laravel 5.X: Access HTTP Request From Controller | Service

It's very important to access HTTP Request from Laravel Controller or Service. Below is a code example showing how to access HTTP Request from Laravel Controller. Same for Service.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request as HttpRequest;
use Illuminate\Routing\Controller as BaseController;

class HomeController extends BaseController
{
    private $HttpRequest;
    public function __construct(HttpRequest $HttpRequest)
    {
        $this->HttpRequest = $HttpRequest;
    }

    public function checkHttpRequest() {
        echo $this->HttpRequest->get("id") . "<BR>";
        echo $this->HttpRequest->getBaseUrl() . "<BR>";
        echo $this->HttpRequest->getUri();
        die();
    }
}