简体   繁体   中英

How not update the value from the browser when using jquery in Ajax?

I have a problem on my code. I want my value from the URL on Ajax call not to update twice, but once only. But what the code does it keeps on updating that field from the URL and do mismatch between 0 and 1 value from the URL on Ajax call. Please see my logic on this code and help me to improve my logic. I only want my field8=1 update once only on BtnOn() function, so if i click twice without refreshing the page it does not, same applies with BtnOff() function. That keeps that original value to its state as being field8=0. So it wont do mismatched between field8=1 to it, which is doing that currently which is bad to a user to see it and also status message as well.

      <div class ="success"></div>
      <div class = "warning"></div>
    <div class="col-md-2 text-center"> 
    <button id="singlebutton" name="singlebutton" class="btn btn-danger" 
      onclick="BtnOff();">Off</button> <br>
     </div>
      <!------
      ---->
      <br/>
    <div class = "col-md-2 text-center">
      <button id = "singlebtn" name="singlebtn" class="btn btn-success" 
      onclick = "BtnOn();">On</button> <br>

    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
      var data;
      function BtnOff() {
        $.ajax({
          url:'https://api.thingspeak.com/update api_key=D***&field8=0',
          type:'GET',
          data:{
          type:'text'
          },
          success:function(response){
            alert(response);
            $('div.warning').html('status changed to zero').delay(1000).fadeOut();
            $('#singlebutton').append(data);
             return false;
             }

        });
        //setTimeout("Subscribe()", 100);

        }
      // second button to unsubscribe.
      function BtnOn() {
        $.ajax({
          url:'https://api.thingspeak.com/updateapi_key=D***&field8=1',
          type:'GET',
          data:{
          type:'text'
          },
          success:function(response){
            alert(response);
            $('div.success').html('status changed to one').delay(1000).fadeOut();
            $('#singlebtn').append(data);
            return data;
             }

          });
        var h = setTimeout("Subscribe()", 100);
        clearTimeout(h);
      }


    </script>

<!-- Back End--->

/*
  Azure IoT Hub WiFi

  This sketch securely connects to an Azure IoT Hub using MQTT over WiFi.
  It uses a private key stored in the ATECC508A and a self signed public
  certificate for SSL/TLS authetication.

  It publishes a message every 5 seconds to "devices/{deviceId}/messages/events/" topic
  and subscribes to messages on the "devices/{deviceId}/messages/devicebound/#"
  topic.

  The circuit:
  - Arduino MKR WiFi 1010 or MKR1000

  This example code is in the public domain.
*/

#include <Wire.h>
#include <Arduino_MKRENV.h>
#include <SPI.h>
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <utility/ECCX08SelfSignedCert.h>
#include <ArduinoMqttClient.h>
#include <WiFiNINA.h> // change to #include <WiFi101.h> for MKR1000

#include "arduino_secrets.h"

/////// Enter your sensitive data in arduino_secrets.h
const char ssid[] = SECRET_SSID;
const char pass[] = SECRET_PASS;
const char broker[] = SECRET_BROKER;
String     deviceId = SECRET_DEVICE_ID;
String       mqttPassword = SECRET_MQTT_PASSWORD;

WiFiClient    wifiClient;            // Used for the TCP socket connection
BearSSLClient sslClient(wifiClient); // Used for SSL/TLS connection, integrates with ECC508
MqttClient    mqttClient(sslClient);

unsigned long lastMillis = 0;
unsigned long postNumbers = 0;

float temperature, humidity, pressure, illuminance, uva, uvb, uvIndex;
String jsonString = "";

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

                if (!ENV.begin())
                {
                                Serial.println("Failed to initialize MKR ENV shield!");
                                while (1);
                }

                if (!ECCX08.begin())
                {
                                Serial.println("No ECCX08 present!");
                                while (1);
                }

                // reconstruct the self signed cert
                ECCX08SelfSignedCert.beginReconstruction(0, 8);
                ECCX08SelfSignedCert.setCommonName(ECCX08.serialNumber());
                ECCX08SelfSignedCert.endReconstruction();

                // Set a callback to get the current time
                // used to validate the servers certificate
                ArduinoBearSSL.onGetTime(getTime);

                // Set the ECCX08 slot to use for the private key
                // and the accompanying public certificate for it
                sslClient.setEccSlot(0, ECCX08SelfSignedCert.bytes(), ECCX08SelfSignedCert.length());

                // Set the client id used for MQTT as the device id
                mqttClient.setId(deviceId);

                // Set the username to "<broker>/<device id>/api-version=2018-06-30" and empty password
                String username;

                username += broker;
                username += "/";
                username += deviceId;
                username += "/api-version=2018-06-30";

                mqttClient.setUsernamePassword("MKR1010", mqttPassword);

                // Set the message callback, this function is
                // called when the MQTTClient receives a message
                mqttClient.onMessage(onMessageReceived);
}

void loop()
{
                if (WiFi.status() != WL_CONNECTED)
                {
                                connectWiFi();
                }

                if (!mqttClient.connected())
                {
                                // MQTT client is disconnected, connect
                                connectMQTT();
                }

                // poll for new MQTT messages and send keep alives
                mqttClient.poll();

                // publish a message roughly every 60 seconds.
                if (millis() - lastMillis > 60000)
                {
                                lastMillis = millis();

                                publishMessage();

                                readEnvSensors();
                }
}

void readEnvSensors()
{
                // read all the sensor values
                temperature = ENV.readTemperature();
                humidity = ENV.readHumidity();
                pressure = ENV.readPressure();
                illuminance = ENV.readIlluminance();
                uva = ENV.readUVA();
                uvb = ENV.readUVB();
                uvIndex = ENV.readUVIndex();

                postNumbers++;
                Serial.print("Post number: ");
                Serial.println(postNumbers);

                // print each of the sensor values
                Serial.print("Temperature = ");
                Serial.print(temperature);
                Serial.println(" °C");

                Serial.print("Humidity    = ");
                Serial.print(humidity);
                Serial.println(" %");

                Serial.print("Pressure    = ");
                Serial.print(pressure);
                Serial.println(" kPa");

                Serial.print("Illuminance = ");
                Serial.print(illuminance);
                Serial.println(" lx");

                Serial.print("UVA         = ");
                Serial.println(uva);

                Serial.print("UVB         = ");
                Serial.println(uvb);

                Serial.print("UV Index    = ");
                Serial.println(uvIndex);
}

unsigned long getTime()
{
                // get the current time from the WiFi module
                return WiFi.getTime();
}

void connectWiFi()
{
                Serial.print("Attempting to connect to SSID: ");
                Serial.print(ssid);
                Serial.print(" ");

                while (WiFi.begin(ssid, pass) != WL_CONNECTED)
                {
                                // failed, retry
                                Serial.print(".");
                                delay(5000);
                }
                Serial.println();

                Serial.println("You're connected to the network");
                Serial.println();
}

void connectMQTT()
{
                Serial.print("Attempting to MQTT broker: ");
                Serial.print(broker);
                Serial.println(" ");

                while (!mqttClient.connect(broker, 8883))
                {
                                // failed, retry
                                Serial.print(".");
                                Serial.println(mqttClient.connectError());
                                delay(5000);
                }
                Serial.println();

                Serial.println("You're connected to the MQTT broker");
                Serial.println();

                // subscribe to a topic
                mqttClient.subscribe("channels/899906/subscribe/fields/field8/F35GLOFJ8L99D0OM");
}

void publishMessage()
{
                Serial.println("Publishing message");

                // send message, the Print interface can be used to set the message contents
                mqttClient.beginMessage("channels/899906/publish/DLQ0F7W5FGVO1I9Q");
                String dataString = String("field1=") + String(temperature) + String("&field2=") + String(illuminance);
                mqttClient.print(dataString);
                mqttClient.endMessage();

                /*
                // send message, the Print interface can be used to set the message contents
                mqttClient.beginMessage("channels/899906/publish/fields/field1/DLQ0F7W5FGVO1I9Q");
                mqttClient.print(temperature);
                mqttClient.endMessage();

                mqttClient.beginMessage("channels/899906/publish/fields/field2/DLQ0F7W5FGVO1I9Q");
                mqttClient.print(illuminance);
                mqttClient.endMessage();
                */
}

void onMessageReceived(int messageSize)
{
                // we received a message, print out the topic and contents
                Serial.print("Received a message with topic '");
                Serial.print(mqttClient.messageTopic());
                Serial.print("', length ");
                Serial.print(messageSize);
                Serial.println(" bytes:");

                // use the Stream interface to print the contents
                while (mqttClient.available())
                {
                                Serial.print((char)mqttClient.read());
                }
                Serial.println();

                Serial.println();
}

This sounds like it is most likely either a typo in your URL/key or a problem on the back end. Are you receiving data whenever you make an ajax call? It might be beneficial to put a simple console.log in your.then statements.

If you URL is inaccurate, if your key is off, or if there is a bug on the API, that would explain why the value is not updating. There may also be an error with your request. It looks like you're trying to update a value in the API, but you're using a get request. While that should work, it is uncommon for users to modify back end data with a get request. Double check that the back end is not expecting a put or post request in order to update this variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM