База данных Firebase в реальном времени для javascript-кода системы рейтинга повторяется и записывает одни и те же данные снова и снова - PullRequest
0 голосов
/ 14 апреля 2019

Мой сайт работает с системой рейтинга (дизайн сайта, предоставляющего услуги)Он использует сервис базы данных Firebase Realtime.Когда я запускаю код и пишу отзыв, он повторяется и работает, пока я не закрою вкладку.

Я попытался onsubmit для формы, onclick для кнопки, изменил код JavaScript для перезагрузки после одногопредставление, но он перезагружается и работает.Если я заменяю местоположение на другую страницу, функция записи данных запускается около 4 раз и перенаправляет на страницу.

Я ожидал изменить количество оценок с 0 оценок, 1, 2, 3, ......

Но рейтинги начинаются с 0 в качестве первого рейтинга, то есть первый рейтинг - рейтинг0, рейтинг1, рейтинг2, ......

И с учетом текущего числа«x rating» создает «ratingx» и изменяет число оценок на «x + 1»

var success = 0;

function rateservice(){
    //set variables for data
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var mobile_no = document.getElementById("phone").value;
    var order_no = document.getElementById("order-code").value;
    var platform= document.getElementById("platform-name").value;
    var rating_no_string= document.getElementById("rating-number").value;
    var rating_no = Number(rating_no_string);
    var comment_input= document.getElementById("comment-input-text").value;
    if(name != null && email != null && order_no != null 
        && platform != null && rating_no != null && comment_input != null){
    
    firebase.database().ref('NoOfRatings/number').on('value', function(snapshot) {
    console.log("original No of ratings =" + snapshot.val());
    var originalNoOfRatings = snapshot.val(); // how many ratings are available?
    // write all other data in DB
    firebase.database().ref('ratings/rating'+originalNoOfRatings+'/').set({
        commentor:name,
        commentor_email : email,
        phone_no : mobile_no,
        order_no : order_no,
        platform : platform,
        rate : rating_no,
        comment : comment_input
    }).then(function(){
        success = 1;
        switch(success){
            case 1 : console.log("Can change the value of number? *Yes*");
        }
        if (success == 1){
            var newNoOfRatings = 1 + originalNoOfRatings;
            console.log("new No Of Ratings = " + newNoOfRatings);
            //write new no of ratings number
            firebase.database().ref('NoOfRatings/').set({
                number : newNoOfRatings
            }).catch (function(error) {
                console.log(error.message + " " + error.code);// number change error catch
            });
        window.alert("your data has written to our database");
        location.replace("./404.html");
      //  document.getElementById('reset-form').focus();
        }
    }).catch (function(error) {
        //if error happen
        window.alert("We have encountered a problem please try again. \n Error : " + error.message);
        console.log(error.code);
    });//catch data write errors
});//end of catching the no of ratings in database
    }
}
/*Rate adding system*/
input{
  display: inline-block;
  margin-bottom: 10px;
  width: 100%;
}
label{
  margin-top: 5px;
  display: block;
}
select{
  margin-bottom: 10px;
}
textarea{
  width: 100%;
}
<form>
        <label>Name :</label>
        <input type="text" id="name" required autofocus autocomplete="name" name="name" placeholder="Your Name">
        <label>Email :</label>
        <input type="email" name="email" required autocomplete="email" id="email" placeholder="Your Email">
        <label>Phone No :</label>
        <input type="tel" name="phone" autocomplete="tel" id="phone" placeholder="Your mobile no">
        <label>Order code :</label>
        <input type="text" name="order_code" required placeholder="order Code" id="order-code">
        <label>What platform :</label>
        <select required id="platform-name">
          <option>Fiverr.com</option>
          <option>Upwork.com</option>
          <option>GJCreations.info</option>
          <option>Freelancer.com</option>
          <option>Facebook.com</option>
          <option>Twitter.com</option>
          <option>Linkedin.com</option>
        </select>
        <label>Your Rating :</label>
        <select required id="rating-number">
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
        </select> Stars<br>
        <p>1 - very poor | 2 - poor | 3 - good | 4 - very good | 5 - fantastic</p>
        <label>Your Comment :</label>
        <textarea id="comment-input-text" name="comment" placeholder="Comment *Important" required></textarea>
        <p>Your sensitive data (email,phone no, order code) will not be public and will not use for anything than verifing purposes.</p>
        <button type="button" id="submit-btn" onclick="rateservice()">Rate</button>
        <button type="reset" id="reset-form">Reset</button>
      </form>

Результат из базы данных

(Число оценок равно 4, но доступно 5 оценок. Код выполняется один раз безизменение номера рейтинга)

{   
"NoOfRatings" : {
    "number" : 4   },   
"ratings" : {
    "rating0" : {
      "comment" : "Test comment 12345",
      "commentor" : "Test name",
      "commentor_email" : "testemail@email.com",
      "order_no" : "012CD45",
      "phone_no" : "07000000000",
      "platform" : "Facebook.com",
      "rate" : 3
    },
    "rating1" : {
      "comment" : "Test comment 12345",
      "commentor" : "Test name",
      "commentor_email" : "testemail@email.com",
      "order_no" : "012CD45",
      "phone_no" : "07000000000",
      "platform" : "Facebook.com",
      "rate" : 3
    },
    "rating2" : {
      "comment" : "Test comment 12345",
      "commentor" : "Test name",
      "commentor_email" : "testemail@email.com",
      "order_no" : "012CD45",
      "phone_no" : "07000000000",
      "platform" : "Facebook.com",
      "rate" : 3
    },
    "rating3" : {
      "comment" : "Test comment 12345",
      "commentor" : "Test name",
      "commentor_email" : "testemail@email.com",
      "order_no" : "012CD45",
      "phone_no" : "07000000000",
      "platform" : "Facebook.com",
      "rate" : 3
    },
    "rating4" : {
      "comment" : "Test comment 12345",
      "commentor" : "Test name",
      "commentor_email" : "testemail@email.com",
      "order_no" : "012CD45",
      "phone_no" : "07000000000",
      "platform" : "Facebook.com",
      "rate" : 3
    }
  }
}

1 Ответ

0 голосов
/ 14 апреля 2019

Я нашел решение, я загружу код здесь.Просто нужно проверить значение один раз не всегда.Проверьте жирный текст

firebase.database (). Ref ('NoOfRatings / number'). один раз ('значение') .then (функция (снимок) {var originalNoOfRatings =snapshot.val ();});

function rateservice(){
    //set variables for data
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var mobile_no = document.getElementById("phone").value;
    var order_no = document.getElementById("order-code").value;
    var platform= document.getElementById("platform-name").value;
    var rating_no_string= document.getElementById("rating-number").value;
    var comment_input= document.getElementById("comment-input-text").value;
    var rating_no = Number(rating_no_string);
    //if data is complete
    if(name != null && email != null && order_no != null && platform != null && rating_no != null && comment_input != null){
        firebase.database().ref('NoOfRatings/number').once('value').then(function(snapshot) {
            var originalNoOfRatings = snapshot.val(); // how many ratings are available?
            // write all other data in DB
            firebase.database().ref('ratings/rating'+originalNoOfRatings+'/').set({
                commentor:name,
                commentor_email : email,
                phone_no : mobile_no,
                order_no : order_no,
                platform : platform,
                rate : rating_no,
                comment : comment_input
            }, function(error) {
                if(error){
                    console.log(error.message + " " + error.code);// number change error catch
                    //if error happen
                    window.alert("We have encountered a problem please try again. \n Error : " + error.message);
                    console.log(error.code);
                    location.reload(true);
                }else{ 
                    var newNoOfRatings = 1 + originalNoOfRatings;
                    //write new no of ratings number
                    firebase.database().ref('NoOfRatings/').set({
                        number : newNoOfRatings
                    }, function(error) {    
                        if(error){
                            console.log(error.message + " " + error.code);// number change error catch
                        }else{
                            window.alert("your data has written to our database"); 
                            location.reload(true); 
                        }
                    });
                }
            });//catch data write errors

        });//end of catching the no of ratings in database  
    }
}
...