javascript JSON stringify and PHP JSON decode

//From client browser console, send JSON via POST request
jQuery.ajax({
 type: "POST",
 url: "proxy.php",
 data: JSON.stringify({
   arr: [1,2,3,4]   
 }),
 contentType: "application/json",
 dataType: 'json',
 success: function(res){console.log(res);}
}); 

//server side proxy.php
<?php
$obj = json_decode($HTTP_RAW_POST_DATA,true);//POST DATA decode
var_dump($obj);

What I expected is like

array(1) {
  ["arr"]=>
   array(4) {
   [0]=>
     int(1)
   [1]=>
     int(2)
   [2]=>
     int(3)
   [3]=>
    int(4)
   }
  }
}

but the result was

array(1) {
 ["arr"]=>
 string(12) "[1, 2, 3, 4]"
}

Problem was json_decode() does not recognise “[]” as array but just string.

Changed proxy.php code to

<?php
$d = str_replace('"[','[',$HTTP_RAW_POST_DATA);
$d = str_replace(']"',']',$d);
$obj = json_decode($d,true);
var_dump($obj);

Now, this works

Advertisements

Symfony2 from scratch

#Reverse engineering only
#DB => XML
$ php app/console doctrine:mapping:import --force FooBarBundle xml
Importing mapping information from "default" entity manager
  > writing ~\Foo\BarBundle/Resources/config/doctrine/Foo.orm.xml

# XML Example
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping
	xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
	<entity name="Foo\BarBundle\Entity\User" table="user">

		<indexes>
			<index name="name_idx" columns="name" />
			<index columns="email" />
		</indexes>

		<unique-constraints>
			<unique-constraint columns="name,email" name="search_idx" />
		</unique-constraints>

		<lifecycle-callbacks>
			<lifecycle-callback type="prePersist" method="doStuffOnPrePersist" />
			<lifecycle-callback type="prePersist"
				method="doOtherStuffOnPrePersistToo" />
			<lifecycle-callback type="postPersist" method="doStuffOnPostPersist" />
		</lifecycle-callbacks>

		<id name="id" type="integer" column="id">
			<generator strategy="IDENTITY" />
		</id>
		<field name="name" column="name" type="string" length="50" nullable="true" unique="true" />
		<field name="email" column="email" type="string" column-definition="CHAR(32) NOT NULL" />
		<field name="isActive" column="is_active" type="boolean" />
	    <field name="login_count" type="integer" nullable="false">
	        <options>
	            <option name="comment">The number of times the user has logged in.</option>
	            <option name="default">0</option>
	        </options>
	    </field>		
		
		<one-to-one field="address" target-entity="Address" inversed-by="user">
			<cascade>
				<cascade-remove />
			</cascade>
			<join-column name="address_id" referenced-column-name="id" on-delete="CASCADE" on-update="CASCADE" />
		</one-to-one>
<!-- 
		<one-to-many field="phonenumbers" target-entity="Foo\BarBundle\Entity\Phonenumber" mapped-by="user">
			<cascade>
				<cascade-persist />
			</cascade>
			<order-by>
				<order-by-field name="number" direction="ASC" />
			</order-by>
		</one-to-many>
		
        <many-to-many field="groups" target-entity="Foo\BarBundle\Entity\Group">
            <cascade>
                <cascade-all/>
            </cascade>
            <join-table name="users_groups">
                <join-columns>
                    <join-column name="user_id" referenced-column-name="id" nullable="false" unique="false" />
                </join-columns>
                <inverse-join-columns>
                    <join-column name="group_id" referenced-column-name="id" column-definition="INT NULL" />
                </inverse-join-columns>
            </join-table>
        </many-to-many>
 -->        		

	</entity>
</doctrine-mapping>

 

## generate Entities from XML
$ php app/console doctrine:mapping:convert annotation ./src
## generate get//set method in Entity File
$ php app/console doctrine:generate:entities FooBarBundle
## update DB schema
$ php app/console doctrine:schema:update --force

 

javascript CORS + nginx

CORS policy

Client send OPTIONS request first and make sure secured connnection like ‘Access-Control-Allow-Headers’,’Access-Control-Allow-Origin’ etc

server nginx conf

 location / {
 
 if ($request_method = 'OPTIONS') {
 add_header 'Access-Control-Allow-Origin' "$http_origin";
 add_header 'Access-Control-Allow-Credentials' 'true';
 add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
 add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With,X-WSSE'; 
 return 204;
 }


 # try to serve file directly, fallback to app.php
 try_files $uri /app.php$is_args$args;
 }

client side

//angularjs
var req = {
 method: 'POST',
 url: 'https://example.com/api/usages/lastest12month.json',
 headers: {
   'Authorization': 'WSSE profile="UsernameToken"',
   'X-WSSE' : $scope.token
 },
 data: {}
}
		
$http(req) 						  
  .then(function(response) {
    console.log(response);		  
  });

convert map value using template in javascript

function matchAndReturnBag($str1, $str2, $delimiter ){
$delimiter = $delimiter || “.”;
var returnBagArray = [];
var tmplArr = $str1.split($delimiter);
var genArr = $str2.split($delimiter);
for(var $i =0;$i < tmplArr.length;$i++){
if(tmplArr[$i] !== genArr[$i]){
var regex = /\${(.*)}$/; // extract variable name
var key = tmplArr[$i].match(regex)[1] ;
returnBagArray[key] = genArr[$i];
}
}
return returnBagArray;
}

var str1 = “test.${interface_id}.aaa.${circuit_id}”;
var str2 = “test.1.aaa.2”;
var bag = matchAndReturnBag(str1,str2);

//result

bag[“interface_id”] => 1

bag[“circuit_id”] => 2

bash shell example

#!/bin/bash

#comment
: << COMMENT
 ANY COMMENT HERE
COMMENT

#full command
declare -A cmd=(
  [clean]="--clean"
  [help]="--help"
)
#short command
declare -A scmd=(
  [clean]="-c"
  [help]="-h"
)

takes_ary_as_arg()
{
  declare -a argAry1=("${!1}")
  echo "${argAry1[@]}"
}

usage()
{
  takes_ary_as_arg cmd[@]
  echo "usage: test.sh [options]"
  echo "options : ${cmd[@]}"
}

case $1 in
  ${scmd[clean]} | ${cmd[clean]} )
    //todo
  ;;
  ${scmd[help]} | ${cmd[help]} )
    echo ${cmd[help]}
  ;;
  * )
    usage $cmd
    exit 1
esac