Skip to main content
added 154 characters in body
Source Link

NOTE:

This what I get when ask to arduino to give me the values:

enter image description here

NOTE:

This what I get when ask to arduino to give me the values:

enter image description here

Source Link

Get JSON data from Arduino with AJAX

I have an Arduino with Ethernet Shield. I'm trying to get data from Arduino, using AJAX call. At the moment I have the following code on Arduino:

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

EthernetServer server(80);

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; 
  }

  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}


void loop() {
  float temperatureIndoor;
  float temperatureOutdoor;
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: Arduino");
          client.println("Connnection: close");
          client.println();
 
          temperatureIndoor = 22.77;
          temperatureOutdoor = 15.55;
          client.print("{\"0\":{\"TemperaturaInterior\":\"");
          client.print(temperatureIndoor);
          client.print("\",\"TemperaturaExterior\":\"");
          client.print(temperatureOutdoor);
 
          client.print("\"}}");
          client.println();
          break;
        }
        
      }
    }
    delay(1);
    client.stop();
    Serial.println("client disconnected");
  }
}

I'm trying to get values with the following ajax call:

    $.ajax({
        url: 'http://192.168.1.177/',
        type: 'post',
            data: { tag: 'getData'},
            dataType: 'json',
                  async: false,
                  success: function (data) {

$('#TemperaturaInterior').val(data.TemperaturaInterior).show();
$('#TemperaturaExterior').val(data.TemperaturaExterior).show();

                            }
                        });

If I access directly from the browser to Arduino (192.168.1.177) I get the correct JSON reply from arduino: {"0":{"TemperaturaInterior":"22.77","TemperaturaExterior":"15.55"}}

I'm not getting the values. Any idea? Thanks