Category: Javascript

  • Sending JSON with data Javascript Fetch

    An important reminder to include following header while sending data in Javascript fetch() call in JSON format.

    Also, do not forget to use JSON.Stringify().

    var data = { some_data: ABC};
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify( data ),

    This is not needed if you are creating a form data object and appending data to it.

    var data = new FormData();
    data.append( 'some_data', 'ABC' );
  • Decode a PHP encoded string url in Javascript

    Sometimes you may face a problem when you have to decode a string with Javascript which was originally url encoded with PHP. This can be an API response or cookie set by PHP setcookie function.

    A simple way to do this is through decodeURIComponent function in Javascript. But it leaves the "+" signs in the string. For that we can use replace function to replace all the "+" signs with space. Remember, simply using replace function sign will only replace the first occurrence in the string. To replace all the occurrences, use the regex version with g flag.

    Here is the code for your reference-

    var decodedString = decodeURIComponent( encodedString ).replace( /+/g, ' ' );

    Here encodedString is the url encoded string received from PHP.

    Its that simple!

    If you have any other method, do share in comments.

    Happy coding!