diff --git a/examples/Makefile b/examples/Makefile index 0976788a..4a405209 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -50,6 +50,9 @@ upload: upload.c ../mongoose.c auth: auth.c ../mongoose.c $(CC) auth.c ../mongoose.c $(OUT) $(CFLAGS) +form: form.c ../mongoose.c + $(CC) form.c ../mongoose.c $(OUT) $(CFLAGS) + mjpg: mjpg.c ../mongoose.c $(CC) mjpg.c ../mongoose.c $(OUT) $(CFLAGS) diff --git a/examples/form.c b/examples/form.c new file mode 100644 index 00000000..8884c5c2 --- /dev/null +++ b/examples/form.c @@ -0,0 +1,81 @@ +#include +#include +#include +#include "mongoose.h" + +static int static_value = 123; // Exposed and changeable via the form + +static void print_html_form(struct mg_connection *conn) { + mg_send_header(conn, "Content-Type", "text/html"); + mg_send_header(conn, "Cache-Control", "max-age=0, post-check=0, " + "pre-check=0, no-store, no-cache, must-revalidate"); + + // Note that all the following normally should reside in static HTML page + mg_printf_data(conn, "%s", ""); + // It is better to use local copy though + mg_printf_data(conn, "", + "http://code.jquery.com/jquery-1.11.0.min.js"); + mg_printf_data(conn, "%s", ""); + mg_printf_data(conn, "%s", ""); + mg_printf_data(conn, "%s", "

Ajax form submission example

"); + mg_printf_data(conn, "%s", "
"); + mg_printf_data(conn, "%s", "Device value: "); + mg_printf_data(conn, "%s", ""); + mg_printf_data(conn, "%s", "
"); + mg_printf_data(conn, "%s", ""); +} + +static int ev_handler(struct mg_connection *conn, enum mg_event ev) { + if (ev == MG_REQUEST) { + if (strcmp(conn->uri, "/get_value") == 0) { + mg_printf_data(conn, "{\"value\": %d}", static_value); + } else if (strcmp(conn->uri, "/set_value") == 0) { + // This Ajax endpoint sets the new value for the device variable + char buf[100] = ""; + mg_get_var(conn, "new_value", buf, sizeof(buf)); // Get form variable + static_value = atoi(buf); // Set new value + mg_printf_data(conn, "%s", "{\"success\": true}"); + printf("Setting value to [%d]\n", static_value); // Debug trace + } else { + // Better way is to set "document_root" option, put "index.html" file + // into document_root and return MG_FALSE here. We're printing HTML + // page by hands just to keep everything in one C file. + print_html_form(conn); + } + return MG_TRUE; + } else if (ev == MG_AUTH) { + return MG_TRUE; + } + + return MG_FALSE; +} + +int main(void) { + struct mg_server *server; + + // Create and configure the server + server = mg_create_server(NULL, ev_handler); + mg_set_option(server, "listening_port", "8000"); + + // Serve request. Hit Ctrl-C to terminate the program + printf("Starting on port %s\n", mg_get_option(server, "listening_port")); + for (;;) { + mg_poll_server(server, 1000); + } + + // Cleanup, and free server instance + mg_destroy_server(&server); + + return 0; +}