Rectangle 27 1

you can decode javascript text into php variable like this, but first you have to read the file into text like :

$json_text = file_get_contents('file.json');
 // or the yii way
 $json_text = $this->renderPartial('path.to.file.json', null, true, true);

 // then decode it 
 $var = json_decode($json_text);
 // or the yii way
 $var = CJSON::decode($json_text);

Is the path the module path or the full path? In the Yii way? I also read there is a renderJSON() function, but again no examples.

application.modules.YOUR_MODULE.foldername.file

Thanks, can you see the edit I made to my comment? Nevermind that is for rendering a JSON file.

php - CJSON Yiiframework Example - Stack Overflow

php yii
Rectangle 27 279

PHP String Encryption Example with Libsodium

To implement authenticated encryption, you want to Encrypt then MAC. The order of encryption and authentication is very important! One of the existing answers to this question made this mistake; as do many cryptography libraries written in PHP.

You should avoid implementing your own cryptography, and instead use a secure library written by and reviewed by cryptography experts.

Both of the libraries linked above above make it easy and painless to implement authenticated encryption into your own libraries.

If you still want to write and deploy your own cryptography library, against the conventional wisdom of every cryptography expert on the Internet, these are the steps you would have to take.

  • Encrypt using AES in CTR mode. You may also use GCM (which removes the need for a separate MAC). Additionally, ChaCha20 and Salsa20 (provided by libsodium) are stream ciphers and do not need special modes.
  • Unless you chose GCM above, you should authenticate the ciphertext with HMAC-SHA-256 (or, for the stream ciphers, Poly1305 -- most libsodium APIs do this for you). The MAC should cover the IV as well as the ciphertext!
  • Unless Poly1305 or GCM is used, recalculate the MAC of the ciphertext and compare it with the MAC that was sent using hash_equals(). If it fails, abort.
  • Do not compress anything ever. Ciphertext is not compressible; compressing plaintext before encryption can lead to information leaks (e.g. CRIME and BREACH on TLS).
mb_strlen()
mb_substr()
'8bit'
mbstring.func_overload
mcrypt_create_iv()
MCRYPT_RAND
bin2hex()

Even if you follow the advice given here, a lot can go wrong with cryptography. Always have a cryptography expert review your implementation. If you are not fortunate enough to be personal friends with a cryptography student at your local university, you can always try the Cryptography Stack Exchange forum for advice.

Don't encrypt passwords. You want to hash them instead, using one of these password-hashing algorithms:

Never use a general-purpose hash function (MD5, SHA256) for password storage.

If you do not have libsodium installed, you can use sodium_compat to accomplish the same result (albeit slower).

<?php
// This requires the libsodium PECL extension

/**
 * Encrypt a message
 * 
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 */
function safeEncrypt($message, $key)
{
    $nonce = \Sodium\randombytes_buf(
        \Sodium\CRYPTO_SECRETBOX_NONCEBYTES
    );

    $cipher = base64_encode(
        $nonce.
        \Sodium\crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
    \Sodium\memzero($message);
    \Sodium\memzero($key);
    return $cipher;
}

/**
 * Decrypt a message
 * 
 * @param string $encrypted - message encrypted with safeEncrypt()
 * @param string $key - encryption key
 * @return string
 */
function safeDecrypt($encrypted, $key)
{   
    $decoded = base64_decode($encrypted);
    $nonce = mb_substr($decoded, 0, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    $plain = \Sodium\crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
    \Sodium\memzero($ciphertext);
    \Sodium\memzero($key);
    return $plain;
}
<?php
// This refers to the previous code block.
require "safeCrypto.php"; 

// Do this once then store it somehow:
$key = \Sodium\randombytes_buf(
    \Sodium\CRYPTO_SECRETBOX_KEYBYTES
);
$message = 'We are all living in a yellow submarine';

$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

One of the projects I've been working on is an encryption library called Halite, which aims to make libsodium easier and more intuitive.

<?php
use \ParagonIE\Halite\KeyFactory;
use \ParagonIE\Halite\Symmetric\Crypto as SymmetricCrypto;

// Generate a new random symmetric-key encryption key. You're going to want to store this:
$key = new KeyFactory::generateEncryptionKey();
// To save your encryption key:
KeyFactory::save($key, '/path/to/secret.key');
// To load it again:
$loadedkey = KeyFactory::loadEncryptionKey('/path/to/secret.key');

$message = 'We are all living in a yellow submarine';
$ciphertext = SymmetricCrypto::encrypt($message, $key);
$plaintext = SymmetricCrypto::decrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

All of the underlying cryptography is handled by libsodium. Obviously, this means you need the PECL extension to use Halite.

<?php
/**
 * This requires https://github.com/defuse/php-encryption
 * php composer.phar require defuse/php-encryption
 * 
 * Note that v2.0.0 is around the corner and this might need
 * to be edited when it's finally released.
 */

use \Defuse\Crypto\Crypto;

require "vendor/autoload.php";

// Do this once then store it somehow:
$key = Crypto::createNewRandomKey();

$message = 'We are all living in a yellow submarine';

$ciphertext = Crypto::encrypt($message, $key);
$plaintext = Crypto::decrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);
Crypto::encrypt()
base64_encode()
base64_decode()

If you're tempted to use a "password", stop right now. You need a random 128-bit encryption key, not a human memorable password.

You can store an encryption key for long-term use like so:

$storeMe = bin2hex($key);

And, on demand, you can retrieve it like so:

$key = hex2bin($storeMe);

I strongly recommend just storing a randomly generated key for long-term use instead of any sort of password as the key (or to derive the key).

That's a bad idea, but okay, here's how to do it safely.

First, generate a random key and store it in a constant.

/**
 * Replace this with your own salt! 
 * Use bin2hex() then add \x before every 2 hex characters, like so:
 */
define('MY_PBKDF2_SALT', "\x2d\xb7\x68\x1a\x28\x15\xbe\x06\x33\xa0\x7e\x0e\x8f\x79\xd5\xdf");

Note that you're adding extra work and could just use this constant as the key and save yourself a lot of heartache!

Then use PBKDF2 (like so) to derive a suitable encryption key from your password rather than encrypting with your password directly.

/**
 * Get an AES key from a static password and a secret salt
 * 
 * @param string $password Your weak password here
 * @param int $keysize Number of bytes in encryption key
 */
function getKeyFromPassword($password, $keysize = 16)
{
    return hash_pbkdf2(
        'sha256',
        $password,
        MY_PBKDF2_SALT,
        100000, // Number of iterations
        $keysize,
        true
    );
}

Don't just use a 16-character password. Your encryption key will be comically broken.

password_hash()
password_verify()

"Do not compress anything ever." You mean like HTTP, spdy and other protocols do? Before TLS? Absolutist advice much?

@ScottArciszewski I like your comment about key "// Do this once then store it somehow:" .. somehow, lol :)) well how about storing this 'key' (which is object) as plain string, hardcoded? I need the key itself, as a string. Can I get it from this object somehow? Thanks

function getKeyFromPassword($password, $keysize = \Sodium\CRYPTO_SECRETBOX_KEYBYTES)

security - How do you Encrypt and Decrypt a PHP String? - Stack Overfl...

php security encryption cryptography encryption-symmetric
Rectangle 27 2

PHP Example

I would attack this problem by first splitting the string into groups of either quoted or not quoted strings.

Then iterating through the matches and if Capture Group 1 is populated, then that string is quoted so just do a simple replace on replace Capture Group 0. If Capture group 1 is not populated then skip to the next match.

Since splitting the string is the difficult part, I'd use this regex:

("[^"]*")|[^"]*
"mission podcast" modcast A B C "D E F"
PHP Code Example: 
<?php
$sourcestring="your source string";
preg_match_all('/("[^"]*")|[^"]*/i',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>
$matches Array:
(
    [0] => Array
        (
            [0] => "mission podcast"
            [1] =>  modcast A B C 
            [2] => "D E F"
            [3] => 
        )

    [1] => Array
        (
            [0] => "mission podcast"
            [1] => 
            [2] => "D E F"
            [3] => 
        )

)
<?php

$text ='"mission podcast" modcast A B C "D E F"';

preg_match_all('/("[^"]*")|[^"]*/',$text,$matches);

foreach($matches[0] as $entry){
    echo preg_replace('/\s(?=.*?")/ims','~~new~~',$entry);
    }
"mission~~new~~podcast" modcast A B C "D~~new~~E~~new~~F"

Thank you very much for the answer and for taking the time to illustrate it! And as it would do perfect, i was hoping i could avoid splitting into arrays. Do you have any suggestion with preg_replace instead?

actually it was the foreach statement i was trying to avoid, but, anyways this does perfectly. Thank you very much!

What if the space was a string? Can i match a whole string?

nevermind i figured it out. if any noob like me is wondering, the \s in echo preg_replace('/\s(?=.*?")/ims','~~new~~',$entry); should be replaced with the string you want to replace. Thanks very much everyone!

Replace part of string between quotes in php regex - Stack Overflow

php regex substring quotes double-quotes
Rectangle 27 99

Example with inheritance

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class.

<?php
class mclass { }
class sclass { }
$a = new mclass;
var_dump($a instanceof mclass);
var_dump($a instanceof sclass);
bool(true)
bool(false)

Reason: Above Example $a is a object of the mclass so use only a mclass data not instance of with the sclass

<?php 
class pclass { } 
class childclass extends pclass { } 
$a = new childclass; 
var_dump($a instanceof childclass); 
var_dump($a instanceof pclass);
<?php 
class cloneable { } 
$a = new cloneable;
$b = clone $a; 
var_dump($a instanceof cloneable); 
var_dump($b instanceof cloneable);

The above example will output:

bool(true)
bool(true)

The above works with 'interfaces' as well. This is useful for checking that a particular interface is available.

operators - Reference — What does this symbol mean in PHP? - Stack Ove...

php operators symbols
Rectangle 27 98

Example with inheritance

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class.

<?php
class mclass { }
class sclass { }
$a = new mclass;
var_dump($a instanceof mclass);
var_dump($a instanceof sclass);
bool(true)
bool(false)

Reason: Above Example $a is a object of the mclass so use only a mclass data not instance of with the sclass

<?php 
class pclass { } 
class childclass extends pclass { } 
$a = new childclass; 
var_dump($a instanceof childclass); 
var_dump($a instanceof pclass);
<?php 
class cloneable { } 
$a = new cloneable;
$b = clone $a; 
var_dump($a instanceof cloneable); 
var_dump($b instanceof cloneable);

The above example will output:

bool(true)
bool(true)

The above works with 'interfaces' as well. This is useful for checking that a particular interface is available.

operators - Reference — What does this symbol mean in PHP? - Stack Ove...

php operators symbols
Rectangle 27 98

Example with inheritance

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class.

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class.

<?php
class mclass { }
class sclass { }
$a = new mclass;
var_dump($a instanceof mclass);
var_dump($a instanceof sclass);
<?php
class mclass { }
class sclass { }
$a = new mclass;
var_dump($a instanceof mclass);
var_dump($a instanceof sclass);
bool(true)
bool(false)
bool(true)
bool(false)

Reason: Above Example $a is a object of the mclass so use only a mclass data not instance of with the sclass

Reason: Above Example $a is a object of the mclass so use only a mclass data not instance of with the sclass

<?php 
class pclass { } 
class childclass extends pclass { } 
$a = new childclass; 
var_dump($a instanceof childclass); 
var_dump($a instanceof pclass);
<?php 
class pclass { } 
class childclass extends pclass { } 
$a = new childclass; 
var_dump($a instanceof childclass); 
var_dump($a instanceof pclass);

The above example will output:

bool(true)
bool(true)

The above works with 'interfaces' as well. This is useful for checking that a particular interface is available.

<?php 
class cloneable { } 
$a = new cloneable;
$b = clone $a; 
var_dump($a instanceof cloneable); 
var_dump($b instanceof cloneable);

The above example will output:

bool(true)
bool(true)

The above works with 'interfaces' as well. This is useful for checking that a particular interface is available.

operators - Reference — What does this symbol mean in PHP? - Stack Ove...

php operators symbols
Rectangle 27 216

Example - using preg_match to find occurrences of a given URL surround...

preg_quote() is what you are looking for:

string preg_quote ( string $str [, string $delimiter = NULL ] )

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

Importantly, note that if the $delimiter argument is not specified, the delimiter - the character used to enclose your regex, commonly a forward slash (/) - will not be escaped. You will usually want to pass whatever delimiter you are using with your regex as the $delimiter argument.

$url = 'http://stackoverflow.com/questions?sort=newest';

// preg_quote escapes the dot, question mark and equals sign in the URL (by
// default) as well as all the forward slashes (because we pass '/' as the
// $delimiter argument).
$escapedUrl = preg_quote($url, '/');

// We enclose our regex in '/' characters here - the same delimiter we passed
// to preg_quote
$regex = '/\s' . $escapedUrl . '\s/';
// $regex is now:  /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/

$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
preg_match($regex, $haystack, $matches);

var_dump($matches);
// array(1) {
//   [0]=>
//   string(48) " http://stackoverflow.com/questions?sort=newest "
// }

One additional remark to @TomHaigh answer, if you don't specify the second $delimiter argument to preg_quote() it won't escape any delimiter, not even the "default" (or the most common) /.

I've added a whole bunch of stuff to this answer - the note brought up by @AlixAxel about the importance of the $delimiter argument, the description of that argument from the docs, a clarification for the confused about exactly what it means, and a heavily commented example showing preg_quote being used in the simplest case I could come up with where it's actually being used to programatically form a regex and put it into another preg_* function (because otherwise, what's the point?). Feel free to rollback if you don't like the change.

Is there a PHP function that can escape regex patterns before they are...

php regex escaping
Rectangle 27 212

Example - using preg_match to find occurrences of a given URL surround...

preg_quote() is what you are looking for:

string preg_quote ( string $str [, string $delimiter = NULL ] )

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

Importantly, note that if the $delimiter argument is not specified, the delimiter - the character used to enclose your regex, commonly a forward slash (/) - will not be escaped. You will usually want to pass whatever delimiter you are using with your regex as the $delimiter argument.

$url = 'http://stackoverflow.com/questions?sort=newest';

// preg_quote escapes the dot, question mark and equals sign in the URL (by
// default) as well as all the forward slashes (because we pass '/' as the
// $delimiter argument).
$escapedUrl = preg_quote($url, '/');

// We enclose our regex in '/' characters here - the same delimiter we passed
// to preg_quote
$regex = '/\s' . $escapedUrl . '\s/';
// $regex is now:  /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/

$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
preg_match($regex, $haystack, $matches);

var_dump($matches);
// array(1) {
//   [0]=>
//   string(48) " http://stackoverflow.com/questions?sort=newest "
// }

One additional remark to @TomHaigh answer, if you don't specify the second $delimiter argument to preg_quote() it won't escape any delimiter, not even the "default" (or the most common) /.

I've added a whole bunch of stuff to this answer - the note brought up by @AlixAxel about the importance of the $delimiter argument, the description of that argument from the docs, a clarification for the confused about exactly what it means, and a heavily commented example showing preg_quote being used in the simplest case I could come up with where it's actually being used to programatically form a regex and put it into another preg_* function (because otherwise, what's the point?). Feel free to rollback if you don't like the change.

Is there a PHP function that can escape regex patterns before they are...

php regex escaping
Rectangle 27 79

This could become an example of CSRF if :

  • from another site : cross-site
<img>
<img src="http://mysite.com/vote/30" />

You would just have voted for that item ;-)

The solution that is generally used is to place a token, that has a limited life-time, in the URL, and, when the URL is fetched, check that this token is still valid.

The basic idea would be :

  • generate a unique token
  • store it in the user's session
http://mysite.com/vote/30?token=AZERTYUHQNWGST
  • Check if the token is present in the URL
  • Check if it's present in the user's session
  • If not => do not register the vote

The idea there is :

  • Tokens don't have a long life-time, and are hard to guess
  • has only a window of a few minutes during which his injection will be valid
  • will have to generate a different page for each user.

Also, note that the shorter the user's session remains active after he has left your site, the less risks there are that it's still valid when he visits the bad website.

But here, you have to choose between security and user-friendly...

  • The browser is sending GET requests for injected tags
  • As this URL is modifying some data, anyway, it should not work with GET, but only with POST

But note that this is not perfectly safe : it's (probably ? ) possible to force/forge a POST request, with some bit of Javascript.

You are right, it's about as easy to forge a GET as an POST request. Though I don't agree that it's necessary to have a token that expire. If the attacker are able to get hold of your session data you have bigger trouble than some extra votes. But your suggested fix still work since the key is just to have a token/random value in the Cookie and in the request data (saved in a cookie or tied to the users session key).

Thank you both for the suggestions. I will change all the links to have this token. I have to agree this is a much saver method. However I am not going to implement the token expiration, i agree with MygGaN on this.

Any of you guys have an idea on what to do when I use AJAX for the voting. Should i just reuse the same key while the user is on the page, and only generate a new token when he refreshes. Or do i have to supply an new token for all the links whenever a vote is done.

Not sure there is a definitive answer to that question, but you have to think that refreshing the token "too often" can lead to troubles ; especially, what if the user has several tabs opened on your site in his browser, and the token changes from one of those ?

POST requests should always be required for operations that modify the server state, as otherwise web crawlers, pre-crawlers ect. may trigger state changes

CSRF (Cross-site request forgery) attack example and prevention in PHP...

php csrf owasp
Rectangle 27 15

One of the most common examples is this query:

' or '1'='1

If you enter this as the username and password into some unsanitized login input the query changes like so:

Original: SELECT * FROM USERS WHERE USER='' AND PASS='';
Modified: SELECT * FROM USERS WHERE USER='' or '1'='1' AND PASS='' or '1'='1';

This causes each thing its looking for to be true, as 1 will always equal 1. Problem with this method is it does not allow the selection of a particular user. Doing so you need to make it ignore the AND statement by commenting it out as seen in other examples.

PHP MySQL injection example? - Stack Overflow

php mysql code-injection
Rectangle 27 15

One of the most common examples is this query:

' or '1'='1

If you enter this as the username and password into some unsanitized login input the query changes like so:

Original: SELECT * FROM USERS WHERE USER='' AND PASS='';
Modified: SELECT * FROM USERS WHERE USER='' or '1'='1' AND PASS='' or '1'='1';

This causes each thing its looking for to be true, as 1 will always equal 1. Problem with this method is it does not allow the selection of a particular user. Doing so you need to make it ignore the AND statement by commenting it out as seen in other examples.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

PHP MySQL injection example? - Stack Overflow

php mysql code-injection
Rectangle 27 15

One of the most common examples is this query:

' or '1'='1

If you enter this as the username and password into some unsanitized login input the query changes like so:

Original: SELECT * FROM USERS WHERE USER='' AND PASS='';
Modified: SELECT * FROM USERS WHERE USER='' or '1'='1' AND PASS='' or '1'='1';

This causes each thing its looking for to be true, as 1 will always equal 1. Problem with this method is it does not allow the selection of a particular user. Doing so you need to make it ignore the AND statement by commenting it out as seen in other examples.

PHP MySQL injection example? - Stack Overflow

php mysql code-injection
Rectangle 27 15

One of the most common examples is this query:

' or '1'='1

If you enter this as the username and password into some unsanitized login input the query changes like so:

Original: SELECT * FROM USERS WHERE USER='' AND PASS='';
Modified: SELECT * FROM USERS WHERE USER='' or '1'='1' AND PASS='' or '1'='1';

This causes each thing its looking for to be true, as 1 will always equal 1. Problem with this method is it does not allow the selection of a particular user. Doing so you need to make it ignore the AND statement by commenting it out as seen in other examples.

PHP MySQL injection example? - Stack Overflow

php mysql code-injection
Rectangle 27 20

You can use serialize. Below is an example.

$("#submit_btn").click(function(){
    $('.error_status').html();
        if($("form#frm_message_board").valid())
        {
            $.ajax({
                type: "POST",
                url: "<?php echo site_url('message_board/add');?>",
                data: $('#frm_message_board').serialize(),
                success: function(msg) {
                    var msg = $.parseJSON(msg);
                    if(msg.success=='yes')
                    {
                        return true;
                    }
                    else
                    {
                        alert('Server error');
                        return false;
                    }
                }
            });
        }
        return false;
    });

$.parseJSON() is a total lifesaver, thanks. I was having trouble interpreting my output based on the other answers.

javascript - jQuery Ajax POST example with PHP - Stack Overflow

php javascript jquery ajax post
Rectangle 27 12

Example using date

According to the article How to Get Current Datetime (NOW) with PHP, there are two common ways to get the current date. To get current datetime (now) with PHP, you can use the date class with any PHP version, or better the datetime class with PHP >= 5.2.

<?php
    echo date('Y-m-d H:i:s');
?>

This expression will return NOW in format Y-m-d H:i:s.

<?php
    $dt = new DateTime();
    echo $dt->format('Y-m-d H:i:s');
?>

datetime - How to get the current date and time in PHP? - Stack Overfl...

php datetime
Rectangle 27 12

Example using date

According to the article How to Get Current Datetime (NOW) with PHP, there are two common ways to get the current date. To get current datetime (now) with PHP, you can use the date class with any PHP version, or better the datetime class with PHP >= 5.2.

<?php
    echo date('Y-m-d H:i:s');
?>

This expression will return NOW in format Y-m-d H:i:s.

<?php
    $dt = new DateTime();
    echo $dt->format('Y-m-d H:i:s');
?>

datetime - How to get the current date and time in PHP? - Stack Overfl...

php datetime
Rectangle 27 12

Example using date

According to the article How to Get Current Datetime (NOW) with PHP, there are two common ways to get the current date. To get current datetime (now) with PHP, you can use the date class with any PHP version, or better the datetime class with PHP >= 5.2.

<?php
    echo date('Y-m-d H:i:s');
?>

This expression will return NOW in format Y-m-d H:i:s.

<?php
    $dt = new DateTime();
    echo $dt->format('Y-m-d H:i:s');
?>

datetime - How to get the current date and time in PHP? - Stack Overfl...

php datetime
Rectangle 27 12

Example using date

According to the article How to Get Current Datetime (NOW) with PHP, there are two common ways to get the current date. To get current datetime (now) with PHP, you can use the date class with any PHP version, or better the datetime class with PHP >= 5.2.

<?php
    echo date('Y-m-d H:i:s');
?>

This expression will return NOW in format Y-m-d H:i:s.

<?php
    $dt = new DateTime();
    echo $dt->format('Y-m-d H:i:s');
?>

datetime - How to get the current date and time in PHP? - Stack Overfl...

php datetime
Rectangle 27 19

You can use serialize. Below is an example.

$("#submit_btn").click(function(){
    $('.error_status').html();
        if($("form#frm_message_board").valid())
        {
            $.ajax({
                type: "POST",
                url: "<?php echo site_url('message_board/add');?>",
                data: $('#frm_message_board').serialize(),
                success: function(msg) {
                    var msg = $.parseJSON(msg);
                    if(msg.success=='yes')
                    {
                        return true;
                    }
                    else
                    {
                        alert('Server error');
                        return false;
                    }
                }
            });
        }
        return false;
    });

$.parseJSON() is a total lifesaver, thanks. I was having trouble interpreting my output based on the other answers.

javascript - jQuery Ajax POST example with PHP - Stack Overflow

php javascript jquery ajax post
Rectangle 27 19

You can use serialize. Below is an example.

$("#submit_btn").click(function(){
    $('.error_status').html();
        if($("form#frm_message_board").valid())
        {
            $.ajax({
                type: "POST",
                url: "<?php echo site_url('message_board/add');?>",
                data: $('#frm_message_board').serialize(),
                success: function(msg) {
                    var msg = $.parseJSON(msg);
                    if(msg.success=='yes')
                    {
                        return true;
                    }
                    else
                    {
                        alert('Server error');
                        return false;
                    }
                }
            });
        }
        return false;
    });

$.parseJSON() is a total lifesaver, thanks. I was having trouble interpreting my output based on the other answers.

javascript - jQuery Ajax POST example with PHP - Stack Overflow

php javascript jquery ajax post