PHP $_POST not populating from jQuery (JavaScript) $.ajax() POST

Problem

I was trying to submit data from a web page to a back-end API in PHP using jQuery’s AJAX (ie. $.ajax()).

But the $_POST variable in PHP didn’t contain the values I was posting.

 

Solution

The problem is I was encoding the POST body data the wrong way in JavaScript.

I was using JSON.stringify(data), where “data” is a JavaScript object or array.

What I needed to do what manually create a string of key1=value1&key2=value2&keyN=valueN pairs.

Example Code from my submit function:

        //sendData = JSON.stringify(data);  //<-- This doesn't work ...

        // ... but this does.
        sendData = "";
        for (var key in data) 
        {
            if (sendData != "") sendData = sendData + "&";
            sendData = sendData + key + "=" + data[key];
        }

	var ajaxRequest = {
		url: url,
		type: "POST",
		data: sendData,
 		dataType: dataType,

		success: function(data, textStatus, jqXHR)  { successCallback(data, textStatus, jqXHR ); },
		error: function(jqXHR, textStatus, errorThrown) { errorCallback(data, textStatus, errorThrown); }
	};

	$.ajax(ajaxRequest);

 

What I searched for (which didn’t help much):

Search “$_POST empty from jquery”: https://duckduckgo.com/?q=%24_POST+empty+from+jquery&amp;atb=v147-1&amp;ia=web

https://stackoverflow.com/questions/1650516/jquery-ajax-method-post-but-post-empty

https://stackoverflow.com/questions/16360008/jquery-post-post-empty

https://stackoverflow.com/questions/54039285/ajax-form-posting-to-php-script-but-post-is-empty-in-php-script

https://stackoverflow.com/questions/1650516/jquery-ajax-method-post-but-post-empty/49948834#49948834

Sample Vue.js app to demonstrate the simple concepts (app, conditionals, loops, binding, components, and routes)

I’ve created a very simple Vue.js sample app you can run immediately to see different Vue concepts in action.

Get the code at: https://github.com/jsnelders/vuejs-sample

Simply download the 2 files and run vueapp.html in a browser (it should even run from your hard drive). No compiling or tools required.

See in action at https://jsnelders.com/vuejs_sample/.

 

The app is a simple way to see the most common elements of Vue in action:

  • Setting up a simple in-page “app”.
  • Setting the “data” model.
  • Creating methods (for example for handling click events.
  • Using if statements.
  • Using for loops.
  • Creating “hash” routes which map to different “views” in the app that you can switch between (think of them as pages within a page).
  • Creating components
    • With templates defined in the JavaScript.
    • With templates in the HTML page.
    • Attaching them to routes.
    • Stand-alone components you can use in your app, and allow you to pass data in from the app, and get data back from the component via events.

These simple concepts should cover 95% of your Vue.js needs.

Git: Reset a local branch to last remote commit, remove unstages files, and fix file permissions

I use the Codeanywhere online IDE for my WordPress development. Sometimes I screw up something I’m testing (usually when I try to manipulate the filesystem with PHP) and need to reset my local branch to the last clean commit I sent to remote.

(Note that I said “remote”. I don’t trust local commits. I continually push to remote to have a safe restore point, especially if I need to do a full delete of my local branch. Yes, it has happened more than once.)

Occasionally I find folder permissions screw up as well and I need to reset via the bash command line.

The following commands are what I always come back to.

Note: The “$” in the command below represent the command-line prompt. The actual commands follow it.

 

Reset a local branch to the the last remote commit of the branch

$ git reset --hard HEAD

 

Clean up any uncommitted folders/files that the reset didn’t remove

$ git clean -f -d

 

Set full permission recursively on a folder and all files/sub-folders

Change directory (cd) to the parent folder of the folder you want to set permission on.

$ sudo chmod -R 777 vylesk-module-z1

 

Recursively delete a folder and all files/sub-folders

Change directory (cd) to the parent folder of the folder you want to delete.

$ rm -rf vylesk-module-z1

Note: The “f” means you are not prompted to delete each file/folder.

The difference between old media and social media

There are two clear differences between almost all published media that has come before and the social media we know now.

1. Available audience
2. Cost

Not cost to the consumer.

I’m about talking cost to the publisher – the person who wants to distribute their content.

In the past there has always been a greater cost to produce and distribute content, whether it in time, effort, materials or straight up money to get others to do work.
There were higher barrier to publishing and distribution: paper, printing, physical distribution of real media, a limited audience who would see the material. It was not readily scalable, nor was it cheap to scale.

That cost generally translated to a need in higher quality content, because the producer had to maximise on their return.
By that I mean: they couldn’t afford to produce shit no once would waste their time on, whether they were paying or not.
They needed maximum return on their money spent, for what was generally an expensive outlay to spread their content.

In addition, and partly due to the cost of media a type of distribution, the audience was limited.
Distribution was limited, harder, and bound my the physical medium.
Again, the producer needed to ensure maximum adoption of their content.

But with the Internet and social media that has all changed.

Social platforms allow “free” and easy distribution of content.
They also allow a “free” and easy inclusion of a massive audience.
That’s an incredibly low barrier of entry on both sides of the equations.
Combine that with increasingly easier ways to create content – written, audio and video – through readily available consume tools, and an abundance of cheap add-on services offered via outsourcing, and we have now have social platforms open to publish almost limitless amounts of content, of every quality, at almost zero cost to both the publisher and consumer.

But there is a cost.

Some may say it’s distraction. Some say privacy. And others see pathways for disinformation.
All are true to varying degrees.

What is see as the ultimate cost to the average person is:

Time and attention.

Because every piece of content generated and distributed on the social platforms is calling for our attention. And it take away our precious time, to both consider and digest, regardless of value.
People are hungry for it (for whatever their individual reason).
And worst of all, in the world of social media:

There are no editors.
No one to check for quality or facts.
No one to curate the chaff from the wheat.

Our time – our precious, limited time alive – is second-by-second being consume by other people’s shit.
Shit that is now without the barrier of economics that anyone can produce and distribute things to suck our time.
Yes, we get a momentary hit of joy or a hint of interest, but how often do we get value that actually enriches us or is usable?

I wonder: what if the social networks flipped the model and started charging for content to be published? How will the world look in 10 years time?

Potato Salad with Bacon and Eggs

Ingredients

  • 1 kg desiree potatoes (or small Carisma potatoes)
  • 6 large eggs
  • 8 rashers short cut rindless bacon
  • 1 cup garlic aioli (mayonnaise)
  • 2 tbs source cream

Optional:

  • 1 bunch spring onions chopped in small pieces; or 1 small red onion finely chopped
  • 1 small lemon, juiced

Time

Preparation: 20 min
Cook: 20 min
Extra time: 1 hour 20 min to cool.
Ready in: 2 hours

Directions

  1. Hard boil the eggs
    Place in a pot, cover with salted tap water and bring to boiling.
    Turn off the heat, cover and let sit for 17 minutes.
    Cool under running water, or empty and refill pot and allow eggs to radiate (repeat 2-3 times)
    Crack all over.
    Leave in fridge covered with cold water for an hour to cool.
    Cut into quarters.
  2. Cook the potatoes
    Peel potatoes if you wish but it works just as well un-peeled.
    Dice potatoes into 2-3cm cubes (or cut into quarters if small potatoes).
    Place in large pot and cover with salted tap water.
    Bring to boil and cook for approximately 10 mins, check regularly, the potatoes should be just cooked, not falling apart.
    Drain and place in fridge for 2 hours. This helps to stop the potatoes from falling apart when mixing in the rest of the ingredients.
  3. [Optional] Chop spring onions or red onion.
  4. Fry the bacon
    Either cut first into small strips, or fry full rashers and cut after.
    Fry bacon so it is browned but not too crispy.
    Drain on paper towel.
  5. Create dressing
    Mix together the aioli/mayonnaise and optional lemon. Mix volumes to preferred taste.
  6. Mix together
    Mix dressing, bacon, onion and eggs through with the potatoes.

This lasts for a few days in the fridge and tends to improve in taste as flavours infuse over time.

potato salad

How to successfully travel the world, make friends and not rub people the wrong way

There are only 2 words you need to learn in almost any language to endear people:

Hello
Thank you

If you can’t learn those words for the country you’re travelling to as a tourist, or you don’t at least try to them, then to be honest you should stay home.
And don’t complain about the hospitality of the host nation.

English may be the de facto universal language of the travelling world now, but 99% of the people in the world are good, kind people and appreciate a “hello” and “thank you” in their own language.

If nothing else, at least smile and try to show a friendly attitude.
Commanding attitude, arrogance, ignorance and self-importance just get you spit in your soup.
And a little small talk – even if you can only do it in English (or your native tongue) – goes a long way to create a bond that shows others you’re worth serving.

 

Bonus Words

Try also learning:

Yes [thank you]
No [thank you]
Please

Again, simple and common words.

 

That’s 5 words in total to learn that show you have put some effort into understanding and respecting the people you have chosen to visit.

 

And in case you don’t realise, all of the above applies when communicating with people in your everyday life.

 

Bash: Remove file and folder with Windows style directory names and backslashes

The Problem

While working with zip files in WordPress (I’m setting up my own update server and package update process), I manually created a zip file in using 7zip in Windows (my primary operating system) and extracted it via PHP in a Codeanywhere Ubuntu workspace.

The problem was the zip file was created containing Windows paths, so I ended up file with a file name “vylesk-test-plugin\vylesk-test-plugin.txt” and directory name “D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\“.
Notice the backslashes and “D:” drive path.

Removing the file and directory was a problem.

Attempting to perform a simple rm and rm -rf resulted in:

rm: cannot remove './vylesk-test-plugin\vylesk-test-plugin.txt': Permission denied
rm: cannot remove '_temp/vylesk-test-plugin.1.1/D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\': Permission denied

I tried changing file permissions using chmod and that also resulted in:

chmod: changing permissions of 'vylesk-test-plugin.1.1/D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\': Operation not permitted
chmod: changing permissions of 'vylesk-test-plugin.1.1/vylesk-test-plugin\vylesk-test-plugin.txt': Operation not permitted

 

The Solution

The solution turned out to be very simple. I just needed to prefix the command with sudo.

So I ended up with:

sudo rm vylesk-test-plugin\\vylesk-test-plugin.txt
sudo rm -rf 'D:\Temp\php\vylesk-test-plugin\vylesk-test-plugin.1.1\vylesk-test-plugin\'

The file and directory then deleted successfully (and I didn’t need an su password, which I don’t know anywhere because it’s in a virtual environment I don’t control).

Note 2 other elements of the commands:

  • In the first ‘rm’ line the “\\” (double-backslash), because backslashes need to be escaped.
  • In the second line I surrounded the directory path with single quotes, an alternative to the double-backslash.

Excel: Cells have left padding space (but it’s not an indent)

Working in Microsoft Excel (2013 and 2016) I noticed what looked like padding (space between the left side of the cell and the text) in some cells in my sheet.

(See the highlighted cell J39)

I didn’t have text indentation in the cell, and “Format Cells > Alignment > Text alignment > Indent” was set to zero.

The cause was the formatting based on the selected cell data type (in the “Number” section of the ribbon).

I had “Accounting” selected which automatically adds some padding.
Changing it to “General” returned it to normal (removed the space) for a cell with just text.

An easy mistake to make but hard to spot.

Slow NBN or Fiber Internet? Check your modem/router and your WiFi band.

If you have Australia’s infamous NBN or other high speed internet service, but you find your service to be slow, then two things to check:

1. A poor quality modem/router can affect your speed. You may be getting 90Mbps into the router, but a bad router or too many connected devices will reduce the speed coming out of it into your phone/tablet/computer.

Here’s an example from my own experience.
I’ve been a customer of TPG’s FTTB (Fiber to the Building) network twice. The service consistently gives me speeds over 50Mbps and often nudges around 90Mbps.
When I initially setup the service (both times) TPG have be their own branded Huawei router.
In our first home it worked OK for a while and seemed to give good speeds (at least, compared to the ADSL2+ I previously had). We had 3 computers, 2 phones and an occasional tablet connected to it. After a while the Internet stopped and I suspect I literally burnt out the device. And devices would continually disconnect because we had too many connecting at the same time.

So I spent $300 (AUD) on a Netgear Nighthawk D7000 and saw immediate improvement.
We started nudging the theoretical max speeds, even over WiFi, with all devices connected. I could run 4 computers, 2 phones and a tablet at the same time, all over WiFi, with 2 computers streaming high quality video services and we never saw an interruption.

The same thing happened in our second home. We received a new modem, which I plugged in initially and tested. I was only getting ADSL2+ type speeds (about 12Mbps). I switched back to the Nighthawk and wham!, straight back to consistent 60-90Mbps over WiFi.

I’ve been running the Nigthawk and same number of connected devices (all on WiFi) for about 4 years now.
Occasionally I have to reboot the router. Very occasionally TPG has a service interruption. Apart from that, we regularly stream video services (free-to-air TV via web/YoutTube/Netflix/Amazon Prime) at the same time, over WiFi, during peak night time periods, and I never see a problem except in the service provider (usually the Australian free-to-air TV streaming sites).

2. It seems 2.4GHz vs 5GHz WiFi can affect your speed. That’s according to this article I found. The article starts:

A study of 43 devices conducted by Enex for the Australian Communications and Media Authority (ACMA) has “unexpectedly” shown 5GHz Wi-Fi outperforming 2.4GHz in long-range testing, negating a major reason to continue using the slower 2.4GHz band.

If your modem/router allows both bands, switch your connection up to the 5GHz band if you haven’t already. If you only have 1 WiFi choice then chances are you’re stuck with 2.4GHz.

[End of article]


In case you are interested

We need to remember “The Internet” isn’t just a solid pipe running from a website into your phone or computer.
There are many segments, devices and relays data must travel through to get from a website to your screen, each of which has it’s own limitations and factors that affect speeds.

Here’s just a few off the top of my head:

  • The server (computer) running the website or service:
    • CPU, memory and bus/network speeds affect the processing and speed of data.
    • Heat, both in and around the the server, affects the speed. In fact, heat can have a big affect on all electronics and computers.
    • Sometimes the server is under extreme load. Or the service is out.
    • Sometimes the data is “cached” (a copy is made) closer to you so time to get it to you is less. Sometimes the data comes from the other side of the world.
  • The transmission lines between the server and your Internet Service Provider. This can include:
    • Going up to space (to satellites) and back again.
    • Through undersea cables and crossing half the world.
    • Crossing through and being processed by tens of other servers as it moves across the world.
    • Some of these links around the world can be down, to the data has to be re-routed through other links.
    • Sometimes there is interference in the signal and quality is reduced.
    • Sometimes the Internet is “under attack” (being clogged up) by Denial of Service attacks that also affect your data.
    • Always there are many different segments that data must travel through.
  • In your Internet Service Provider.
    • They have filters and computers the data must travel through, checking for content restrictions and who knows what else.
  • From your Internet Service Provider to local phone exchange.
    • The quality of the transmission line (cables) will affect the speed.
  • From your local phone exchange to your home.
    • If you’re in Australia, the data could be travelling through anything from long-distance WiFi, to old copper cables or new fiber networks.
    • The distance from your exchange can affect speed because on older networks speed reduces the further away from the exchange you are.
    • In some networks (like old copper phone lines) the data also has to travel through curb-side switches before betting to your house.
  • In your home or building.
    • Phone line or fiber cabling inside your home will affect speed.
    • Physical lines can degrade or be damaged over time.
  • Into and through your modem.
    • Your modem will have different speed capabilities.
    • It will also have internal software and services that need to process your data.
  • From your modem to your device.
    • The quality and health of your cable from the modem to computer can affect speed.
    • If using WiFi, where you place the router and what the signal has to travel through (e.g. walls) to get to your device will affect speed.
  • Inside your device.
    • Your device will have different network components that have different speed and quality ratings.

And that process happens in both directions.
To get the data from a website your computer first sends a request to the site, going through all those same steps in the opposite direction.

Every step of the way, your data is being switched, processed, sped up or slowed down.
In the fraction of the second between a your device requesting data from a website or service and it being displayed to you, that data is been touched by hundreds or thousands of pieces of equipment and software.

(Note: In the above list refer to “data” as a singular – i.e. “data has”. I know this is wrong. I did it on purpose for the great good of reading.)

Cannot login to Nighthawk modem router admin page

I have a NETGEAR D7000 Nighthawk modem router and you can login to the admin screen via the IP 192.168.0.1 or URL http://www.routerlogin.net/.

The problem is, when I try to login on Chrome I get an error page “This page isn’t working – www.routerlogin.net sent an invalid response” with “ERR_INVALID_HTTP_RESPONSE”:

The fix is easy:

Use the FireFox browser.

There must be something in the page that Chrome doesn’t like, bit FireFox is happy to load the page.