0

I have a text file where my existing data is placed in there. Now I enter an email address that is already existing to my text file student.txt. How can I restrict an email about to enter, that the email is already existing in my text file student.txt or How can I add an error message to state that the email is already existing? Below is my code.

Thank you

CharlesS
  • 33
  • 7

3 Answers3

1

In the ajax call you'are not feeding the studentArr array with emails, it stays empty, that's why filter function will always return an empty array and the test for duplicated emails will fails, try this:

$.get("/files/students.txt", function(data) {
    var html1 = "";
        html1 += "<tr>";
        html1 += "<th>Students</th>";
        html1 += "<th>Email Address</th>";
        html1 += "</tr>";

    var rows = data.split("\n");
        rows.forEach( function getvalues(thisRow) {
        html1 += "<tr>\n";
            var columns = thisRow.split(",");
        for(var i=0;i<columns.length;i++){ 
            html1 += "<td>" + columns[i] + "</td>\n"; 
        }

        // push name and email to studentArr 
        studentArr.push(studentArr.push({
            name:columns[0],
            email:columns[1]
        }););


    });
    html1 += "</tr>\n";
    $("#output").append(html1); 
}); 
YouneL
  • 8,152
  • 2
  • 28
  • 50
0

You can't write to a file on your local device from jquery since that would be a security threat

Read/write to file using jQuery

In order to store that data you have two options.

  1. Use a server with some web server app running that allows you to write server side code to store the data as it is sent using your jquery ajax call.
  2. If its a simple app for your own use - store it in the browsers local-storage.

The easiest route for a local app such as yours is local storage

https://www.w3schools.com/html/html5_webstorage.asp

MartinWebb
  • 1,998
  • 1
  • 13
  • 15
0

Assuming your program can read the file:

$.get("http://somesite.com/student.txt", function(response) {
   var filecontent = response;
   var email = "turd.ferguson@jeopardy.com";
   if(filecontent.indexOf(email) != -1){
      alert("Error: email already exists.");
   }
});

As mentioned in the other answer, this won't work locally. Look into cross-origin requests to avoid these kinds of errors.

Tony
  • 2,658
  • 2
  • 31
  • 46