2

i am very new to LUA and i am trying to send a json post from my ESP8266 using LUA to a PHP server on my localhost, i searched the internet and i cant find any example to do that can any one help me please ?

my LUA code

-- tested on NodeMCU 0.9.5 build 20141222...20150108
-- sends connection time and heap size to http:server.php
wifi.setmode(wifi.STATION)
wifi.sta.config("VIVA-4G-LTE-6134","VIVA176429")
--wifi.sta.config("AndroidAP","rapz4736")

print('httpget.lua started')
Tstart  = tmr.now()

conn = nil
conn = net.createConnection(net.TCP, 0) 

-- show the retrieved web page

conn:on("receive", function(conn, payload) 
                       success = true
                       print(payload) 
                       end) 

-- once connected, request page (send parameters to a php script)

conn:on("connection", function(conn, payload) 
                       print('\nConnected') 
                       conn:send("POST /server.php?"
                        .."name=mometto"
                        .."&age=27"
                        .." HTTP/1.1\r\n" 
                        .."Host: 172.0.0.1\r\n" 
                        .."Connection: close\r\n"
                        .."Accept: */*\r\n" 
                        .."User-Agent: Mozilla/4.0 "
                        .."(compatible; esp8266 Lua; "
                        .."Windows NT 5.1)\r\n" 
                        .."\r\n") 
                   --  conn:send("what":"books", "count":3 )
                       end) 

-- when disconnected, let it be known
conn:on("disconnection", function(conn, payload) print('\nDisconnected') end)

conn:connect(80,'192.168.43.181') 

here it is easy for me to send parameters, but when i want to send a request body i cant, i tried to add this code to send the request body

conn:send("what":"books", "count":3 )

but it is not working and i get this message : enter image description here

so can any one provide any help for me please ?

mohammad
  • 2,142
  • 7
  • 35
  • 60
  • 1
    What isn't working exactly? The commented out `connection:send` call? How is it not working? Does `send` serialize a table to json or do you need to do that yourself? – Etan Reisner Nov 01 '15 at 01:15
  • ```var superHero``` This seems off to me. This is Lua code? var shouldn't be there, and the table should be a string and converted to json on php's side – warspyking Nov 01 '15 at 01:45
  • `("what":"books", "count":3 )` Again, this doesn't appear to be valid Lua code, has this worked in the past? – warspyking Nov 07 '15 at 18:02

1 Answers1

1

So, firstly that's invalid Lua code for a dictionary. Secondly, if you want to send JSON, you're going to need to encode it with the cjson module.

Try something like

local msg = {"what":"books", "count":3}
conn:send(cjson.encode(msg))
Tom Parker-Shemilt
  • 1,679
  • 15
  • 26