Add SQL to function called 'onclick' - javascript

I have a button called "Add" which relates to each person in a list.
echo <td><input type=\"submit\" id=\"PlayerAdded".$id."\" value=\"Add\"
onclick=\"add('".$id."','".$name."','".$_SESSION['GameID']."');\"></input></td>";
When "Add" is clicked, I want to add the persons details to a table (working fine), and also add a new row including their name and ID into a table in my DB (this is my problem).
I am aware that PHP won't work in a JS function. I'm also aware that I should never access the database on my site from JS due to the security issues.
So how can I have a button which onclick calls a function which adds to the database?
I tried writing my function in PHP, but it wasn't doing anything when I clicked the button. See my function below:
function add(id,name,game){
var t = ("</td><td>");
var str = ("<tr id='Players" + id + "'><td>")
var ctr = ("</td></tr>")
var PID = ("<input type = 'hidden' name='ID" + id + "' value='" + id + "'></input>" + id)
var Pnam = ("<input type='hidden' name='Name" + id + "' value='" + name + "'></input>");
var place = ("<select name='Place" + id + "'><option value='17'>17th</option><option value='16'>16th</option><option value='15'>15th</option><option value='14'>14th</option><option value='13'>13th</option><option value='12'>12th</option><option value='11'>11th</option><option value='10'>10th</option><option value='9'>9th</option><option value='8'>8th</option><option value='7'>7th</option><option value='6'>6th</option><option value='5'>5th</option><option value='4'>4th</option><option value='3'>3rd</option><option value='2'>2nd</option><option value='1'>1st</option></select>")
var points = ("<form action='leaderboards.php' method='post' target='_blank'><input type='hidden' name='playerid' value='" + id + "'></input><input type='hidden' name='name' value='" + name + "'></input><input type='submit' value='View'></form>");
var cash = ("$<input name='Cash" + id + "' placeholder=' 0'></input>");
var ticket = ("<select name='Ticket" + id + "'><option value='No'>No</option><option value='Yes'>Yes</option>");
var del = ("<input type='button' value='Delete' onclick='remove(" + id + ")'> </input>")
$('#PlayerAdded').before(str+ PID + t + Pnam + name + t + place + t + points + t + cash + t + ticket + t + del + ctr);
// This is where I want to insert into the db. Similar to
// <?php
// $sql = "INSERT INTO results (`col`, `col2`, `col3`) VALUES ('$id', '$name', '$game')";
// mysqli_query($dbcon,$sql); ?>
//but I want to be able to do it inside this java script function.
}

Remove the bracket before the variables, which you have written for every variable in function.
Add the ajax piece at the end of your function code.
function add(id, name, game) {
var t = "</td><td>";
var str = "<tr id='Players" + id + "'><td>"
var ctr = "</td></tr>"
var PID = "<input type = 'hidden' name='ID" + id + "' value='" + id + "'></input>" + id;
var Pnam = "<input type='hidden' name='Name" + id + "' value='" + name + "'></input>";
var place = "<select name='Place" + id + "'><option value='17'>17th</option><option value='16'>16th</option><option value='15'>15th</option><option value='14'>14th</option><option value='13'>13th</option><option value='12'>12th</option><option value='11'>11th</option><option value='10'>10th</option><option value='9'>9th</option><option value='8'>8th</option><option value='7'>7th</option><option value='6'>6th</option><option value='5'>5th</option><option value='4'>4th</option><option value='3'>3rd</option><option value='2'>2nd</option><option value='1'>1st</option></select>";
var points = "<form action='leaderboards.php' method='post' target='_blank'><input type='hidden' name='playerid' value='" + id + "'></input><input type='hidden' name='name' value='" + name + "'></input><input type='submit' value='View'></form>";
var cash = "$<input name='Cash" + id + "' placeholder=' 0'></input>";
var ticket = "<select name='Ticket" + id + "'><option value='No'>No</option><option value='Yes'>Yes</option>";
var del = "<input type='button' value='Delete' onclick='remove(" + id + ")'> </input>";
$('#PlayerAdded').before(str + PID + t + Pnam + name + t + place + t + points + t + cash + t + ticket + t + del + ctr);
// making ajax call to insert.php and posting the data
$.ajax({
method: "POST",
url: "insert.php",
data: {
"id": id,
"name": name,
"game": game
},
beforeSend:function(){
// show something before data is saved to db.
}
}).done(function(msg) {
$("body").append(msg); //debugging purpose
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
insert.php
<?php
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['game'])){
$id= $_POST['id'];
$name= $_POST['name'];
$game= $_POST['game'];
//write your connection logic
// never write bare queries there is a chance of sql injection.
//Instead use prepared statement, prepare your query then bind the above values to it, then excute.
//write your insert logic below.
}
?>

You need to post the values you want to insert to your database via AJAX, append this to your add() function:
$.post('insertnew.php', { id:id,name:name,game:game }, function(data){
alert(data);
});
insertnew.php:
<?php
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['game'])){
// sanitize your data here, then:
$id = $_POST['id'];
$name = $_POST['name'];
$game = $_POST['game'];
//connect to your db, or instead include your dbconnect.php
$link= new mysqli('localhost', 'my_user', 'my_password', 'world');
// check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//use prepared statement, prepare your query then bind the above values to it, then excute
$stmt = mysqli_prepare($link, "INSERT INTO results VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, $id, $name, $game);
if(mysqli_stmt_execute($stmt)){
echo "Record has been added successfully";
}else{
echo "Sorry, record could not be inserted";
}
}
?>
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/mysqli-stmt.bind-param.php

Related

How to remove one radio button's post value to render new radio selection result

I am working on a module with 3 radio buttons. Clicking one radio button lists data related to it and so on. I have applied ajax call on radio buttons click and return an array in the response. My problem here is for each radio button click the data keeps on adding into the list. For e.g. if I click on 'All users' radio it displays the data related to "All" but again if I click on "Unapproved Users" radio, the list adds up to the 'All users ' listing at the bottom. So how can I reset the $_POST variable each time the data is rendered so that new list appears for new radio selection,
I would really appreciate the help or advice for this.
Code goes as,
<script>
$('#selection').change
(
function()
{
var selected_value = $("input[name='users']:checked").val();
//till here the code works fine.
$.ajax
(
{
url: "approval_ajax.php",
dataType : "json",
type: "POST",
cache: false,
data: { selected_value : selected_value },
success: function(response)
{
console.log(response);
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var email = response[i].email;
var employee_id = response[i].employee_id;
var first_name = response[i].first_name;
var middle_name = response[i].middle_name;
var last_name = response[i].last_name;
var mobile = response[i].mobile;
var created_on = response[i].created_on;
var disabled = response[i].disabled;
var tr_str = "<tr>" +
"<td>" + (i+1) + "</td>" +
"<td>" + email + "</td>" +
"<td>" + employee_id + "</td>" +
"<td>" + first_name + " " + middle_name + " " + last_name + "</td>" +
"<td>" + mobile + "</td>" +
"<td>" + created_on + "</td>" +
"<td><input type='checkbox' name='check[]'" + disabled + "value= '" + id + "' class='checkbox' id='select_all' ></td>" +
"<input type='hidden' value='" + id + "' name='user_id' id='user_id' >" +
"</tr>";
$("#example").append(tr_str);
}
alert("AJAX was a success");
}
}
);
}
);
</script>
And now my approval_ajax.php
<?php
session_start();
require("../includes/config.php");
require("../classes/Database.class.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$return_arr = array();
$status='';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$value = filter_input(INPUT_POST, "selected_value");
if (isset($value))
{
$users=$value;
}else{
$users='';
}
switch ($users)
{
case "all":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3";
break;
case "approved":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =1";
break;
case "unapproved":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =0";
break;
}
$sq = $db->query($sqlQuery);
if ($db->affected_rows > 0) {
while ($row = mysql_fetch_array($sq)) {
$disabled = '';
if ($status == '1') {
$disabled = "disabled = 'disabled' checked='checked' ";
}
$id = $row['id'];
$email = $row['email'];
$employee_id = $row['employee_id'];
$first_name = $row['first_name'];
$middle_name = $row['middle_name'];
$last_name = $row['last_name'];
$mobile = $row['mobile'];
$created_on1 = $row['created_on'];
$created_on = date("d-m-Y", strtotime($created_on1));
$return_arr[] = array("id" => $id,
"email" => $email,
"employee_id" => $employee_id,
"first_name" => $first_name,
"middle_name" => $middle_name,
"last_name" => $last_name,
"mobile" => $mobile,
"created_on" => $created_on,
"disabled" => $disabled
);
}
}
header('Content-Type: application/json', true, 200);
echo json_encode($return_arr);
}
The $_POST variable is reset on every new request.
The issue here is that you're using jquery's append() function. This function just adds up content to the end of your element.
EDITED:
In order to clear your list before adding new data, use the empty() function.

PHP while loop array data dispay into javascript

So I am making Text based browser game. I have made map where you can move around without refreshing page and updating it with javascript. I have added that it randomly generates bots from database which you can attack, but can't find a way to make it update when you move around the map.
This is the PHP I made to load the bots from database and make then randomly generate.
$sql3 = "SELECT * FROM monsters WHERE botworld='$world'";
$result3 = mysqli_query($conn,$sql3);
$row3=mysqli_fetch_array($result3,MYSQLI_ASSOC);
$rowsbot = array();
while ($rowbot = mysqli_fetch_assoc($result3)) {
$rowsbot[] = $rowbot;
}
for($i=0;$i<count($rowsbot);$i++) {
$a = rand(0,10);
if($a > 5) {
echo "<div class='botres$i'>";
echo "<div class='panel panel-default bot$i'><div class='panel-body bot1$i'>";
echo $i . ". " . $rowsbot[$i]['name'];
echo "<div class='pull-right'><button class='btn btn-default' botid='" . $rowsbot[$i]['id'] ."' botnr='" . $i . "'>Attack</button></div>";
echo "</div></div>";
echo "</div>";
}
}
I added then it automaticly updates the div block when you attack bot. But I want to make bots update when you move around.
I have got the array with data, but don't know how to use it.
var myArray = jQuery.parseJSON('<?php print json_encode($row3); ?>');
console.log(myArray)
Done
var rowsbot = <?php echo json_encode($rowsbot) ?>;
for(i=0; i<rowsbot.length; i++) {
var a = Math.floor((Math.random() * 10) + 1);
if(a>5) {
$(".monsters").append("<div class='botres" + i + "'><div class='panel panel-default bot" + i + "'><div class='panel-body bot1 " + i + "'>" + i + ". " + rowsbot[i].name + "<div class='pull-right'><button class='btn btn-default' botid='" + rowsbot[i].id + "' botnr='" + i + "'>Attack</button></div></div></div></div>");
}
}

Create button and click handler with JQuery

Currently I am displaying a table of values, where the last column provides an "Edit" and "Delete" option. For simplicity, when they edit a row, I am just clearing each column's innerHTML and placing input fields there instead. I need to also replace the Edit/Delete links with Save/Cancel, however I need to create these buttons with JS/JQuery, attach click handlers to them append them to the innerHTML.
While I have found similar examples, I am not quite clear on how to accomplish this and would appreciate any help.
function editRecord(line)
{
var zone = "<?= $data['zone']; ?>";
// Store the original field values
var valueName = document.getElementById("entryName" + line).innerHTML;
var valueTTL = document.getElementById("entryTTL" + line).innerHTML;
var valueAddress = document.getElementById("entryAddress" + line).innerHTML;
// Replace existing row value with input fields to make edits
document.getElementById("entryName" + line).innerHTML = "<input type='text' value='" + valueName + "'>";
document.getElementById("entryTTL" + line).innerHTML = "<input type='text' value='" + valueTTL + "'>";
document.getElementById("entryAddress" + line).innerHTML = "<input type='text' value='" + valueAddress + "'>";
// Create Save button with click handler
// Create Cancel button with click handler
// Append these to the element below (replacing the Edit/Delete)
document.getElementById("entryOptions" + line).innerHTML = "<input type='button' value='Save'> <input type='button' value='Cancel'>";
}
After further tinkering, I managed to figure it out. Here is the working code should it end up helping anyone else.
function editRecord(line)
{
var zone = "<?= $data['zone']; ?>";
// Store the original field values
var originalName = document.getElementById("entryName" + line).innerHTML;
var originalTTL = document.getElementById("entryTTL" + line).innerHTML;
var originalAddress = document.getElementById("entryAddress" + line).innerHTML;
// Replace existing row value with input fields to make edits
document.getElementById("entryName" + line).innerHTML = "<input type='text' value='" + originalName + "'>";
document.getElementById("entryTTL" + line).innerHTML = "<input type='text' value='" + originalTTL + "'>";
document.getElementById("entryAddress" + line).innerHTML = "<input type='text' value='" + originalAddress + "'>";
document.getElementById("entryOptions" + line).innerHTML = "";
var saveButton = $('<button/>', {
text: "Save",
id: 'btn_Save' + line,
click: function ()
{
// Save the changes
}
});
var cancelButton = $('<button/>', {
text: "Cancel",
id: 'btn_Cancel' + line,
click: function ()
{
document.getElementById("entryName" + line).innerHTML = originalName;
document.getElementById("entryTTL" + line).innerHTML = originalTTL;
document.getElementById("entryAddress" + line).innerHTML = originalAddress;
}
});
$("#entryOptions" + line).append(saveButton);
$("#entryOptions" + line).append(cancelButton);
}

Send a variable from Javascript to Javascript

I need to send a variable from a script to another script, i hope you can help me.
The variable i want to send is "campos" that is a counter.
This is the first script:
<script>
var campos = 0;
function agregarCampophp(hola){
// alert(campos);
var data = {};
data.pruebaId = $('#prueba').val();
data.deno = $('#subespecifica-descripcion').val();
data.prep = $('#partidaasociada-presupuestop').val();
data.tot = $('#partidaasociada-totalp').val();
// var datad = $.parseJSON(data);
// alert(data.prep);
campos = campos+1;
var NvoCampo= document.createElement("div");
$('#prueba').attr('value','');
$('#subespecifica-descripcion').attr('value','');
$('#partidaasociada-presupuestop').attr('value','');
$('#partidaasociada-totalp').attr('value','');
NvoCampo.id= "divcampo_"+(campos);
NvoCampo.innerHTML=
"<table class='table table-striped' >"+
" <tr>" +
" <td>" +
" <input type='text' size='20' name='articupart_" + campos +
"' id='articupart_" + campos + "' value='"+data.pruebaId+"'>" +
" </td>" +
" <td>" +
" <input type='text' size='70' name='articudeno_" + campos +
"' id='articudeno_" + campos + "' value='"+data.deno+"'>" +
" </td>" +
" <td align='right'>" +
" <input type='text' size='22' name='articuprep_" + campos +
"' id='articuprep_" + campos + "' value='"+data.prep+"'>" +
" </td>" +
" <td align='right'>" +
" <input type='text' size='22' name='articutot_" + campos +
"' id='articutot_" + campos + "' value='"+data.tot+"'>" +
" </td>" +
" <td align='right'>" +
" <input type='hidden' id='c_"+campos+"' value='hola_"+campos+"'>" +
" </td>" +
" </tr>"+
" </table>";
var contenedor= document.getElementById("contenedorcampos");
contenedor.appendChild(NvoCampo);
data.part = $('#articupart_'+campos).val();
data.deno = $('#articudeno_'+campos).val();
data.prep = $('#articuprep_'+campos).val();
data.tot = $('#articutot_'+campos).val();
}
I need that variable "campos" in this other Script:
$('._save').on('click', function(event){
event.preventDefault();
var data = {};
data.campos = $('#c_2').val();
alert(data.campos);
data.pruebaId = $('#prueba').val();
data.secId = $('#Hidden1').val();
data.proId = $('#Hidden2').val();
data.subId = $('#Hidden3').val();
data.proyId = $('#Hidden4').val();
data.actId = $('#Hidden5').val();
data.prep = $('#partidaasociada-presupuestop').val();
data.tot = $('#partidaasociada-totalp').val();
data.desc = $('#subespecifica-descripcion').val();
var success = function(data){
console.log("Success!", data);
}
var error = function(data){
console.log("Error!", data);
}
// $.ajax({
// url:'index.php?r=partidaasociada/get-linea',
// type:'POST',
// dataType:'json',
// data:data
// }, success, error);
});
I am trying to get the variable with a hidden div that i am creating in the first one, but i am getting some errors, thanks beforehand.
glad that worked for you. So basically this would be the solution:
// initialise the variable if it has not been initialised before
if (typeof(window.campos)=='undefined') {
window.campos= 0;
}
// increase by one
window.campos+=1;
And in your second script access it using:
$('._save').on('click', function(event){
...
// access the previously stored view counter
data.campos= window.campos;
}
Glad that worked for you!

clearInterval() not working correctly

I've recently been trying to repeat a jQuery AJAX request every two seconds. PLEASE NOTE: I've looked at the other questions on SO and not of them seem to apply to my situation, i've also looked at the documentation.
Snippet:
else if (text == "load") {
$(".response").text("working!");
var traffic = function load() {
$.ajax({url:"load.php",success:function(result){
var obj = jQuery.parseJSON(result);
var ids = obj.map(function(el) {
return "<tr><td>" + el.id + "</td><td>" + el.ip + "</td><td>" + el.proxyip + "</td><td>" + el.ping + "</td><td>" + el.time + "</td></tr>";
});
$(".response").html("<table><tr><td><strong>ID</strong></td><td><strong>IPs</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr>" + ids + "</table>");
}});
};
var trafficInterval = setInterval(traffic, 2000);
To cancle the timeout, i check to see if the text is not equal to "load", if it isnt equal to load, i cancle the timeout
else {
$(".response").text("'" + badCommand + "'" +" is not a valid command, type 'help' for a list of commands.");
clearInterval(trafficInterval);
}
HOWEVER, when i change the input of the textfield, the table will still load every two seconds, the timeout hasn't been cancled and i can't seem to see why.
Here's the whole function for people wondering
$("textarea").keyup(function(){
var text = $(this).val();
$(".log").text(text);
// Commands
if (text != "") {
var badCommand = $("textarea").val();
if (text == "help") {
$(".response").html("Commands:<br/><span class='indent'>traffic -url|all</span><span class='indent'>google #search term</span><span class='indent'>youtube #search term</span><span class='indent'>portfolio</span>")
} else if (text == "traffic") {
$(".response").html('Live traffic from:<br/><table><tr><td><strong>IP</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr><?php try { $db = new PDO("mysql:host=$mysql_host;dbname=$mysql_db", $mysql_user, $mysql_pass); $sql = "SELECT * FROM traffic ORDER BY id DESC LIMIT 50"; foreach ($db->query($sql) as $row) { echo "<tr>"; echo "<td class='details'>" . $row["ip"] . "</td>"; echo "<td class='details'>" . $row["proxyip"] . "</td>"; echo "<td class='details'>" . $row["ping"] . "</td>"; echo "<td class='details'>" . $row["time"] . "</td>"; echo "</tr>"; } $db = null; } catch(PDOException $e) { $e->getMessage(); } ?></tr></table>');
} else if (text == "load") {
$(".response").text("working!");
var traffic = function load() {
$.ajax({url:"load.php",success:function(result){
var obj = jQuery.parseJSON(result);
var ids = obj.map(function(el) {
return "<tr><td>" + el.id + "</td><td>" + el.ip + "</td><td>" + el.proxyip + "</td><td>" + el.ping + "</td><td>" + el.time + "</td></tr>";
});
$(".response").html("<table><tr><td><strong>ID</strong></td><td><strong>IPs</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr>" + ids + "</table>");
}});
};
var trafficInterval = setInterval(traffic, 2000);
} else {
$(".response").text("'" + badCommand + "'" +" is not a valid command, type 'help' for a list of commands.");
clearInterval(trafficInterval);
}
}
if (text == "") {
var noCommand = $("textarea").val();
$(".response").text(" ");
}
// End Commands
});
FYI:
Putting the clearInterval(); AFTER the code stops it from working,
Putting the clearInterval(); BEFORE the code does nothing.
The clearInterval(trafficInterval); MUST be working because if i place it at the end of the first function, nothing happens when i type "load"
It's not the timer either, i tried it instead to automatically update whenever the mouse is moved and the exact same thing happens...
This is a scoping issue. The interval needs to be outside the scope of the event handler call:
var trafficInterval = null;
$("textarea").keyup(function(){
var text = $(this).val();
$(".log").text(text);
// Commands
if (text != "") {
var badCommand = $("textarea").val();
if (text == "help") {
$(".response").html("Commands:<br/><span class='indent'>traffic -url|all</span><span class='indent'>google #search term</span><span class='indent'>youtube #search term</span><span class='indent'>portfolio</span>")
} else if (text == "traffic") {
$(".response").html('');
} else if (text == "load") {
$(".response").text("working!");
var traffic = function load() {
$.ajax({url:"load.php",success:function(result){
var obj = jQuery.parseJSON(result);
var ids = obj.map(function(el) {
return "<tr><td>" + el.id + "</td><td>" + el.ip + "</td><td>" + el.proxyip + "</td><td>" + el.ping + "</td><td>" + el.time + "</td></tr>";
});
$(".response").html("<table><tr><td><strong>ID</strong></td><td><strong>IPs</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr>" + ids + "</table>");
}});
};
trafficInterval = setInterval(traffic, 2000);
} else {
$(".response").text("'" + badCommand + "'" +" is not a valid command, type 'help' for a list of commands.");
clearInterval(trafficInterval);
}
}
if (text == "") {
var noCommand = $("textarea").val();
$(".response").text(" ");
}
// End Commands
});
See fiddle # http://jsfiddle.net/sLooj4on/ (can see polling fail in dev tools, stops when text is removed from input)
It's hard to tell without looking at the rest of the code, but your trafficInterval variable could be out of scope. Try initializing outside of the if/else statement
trafficInterval is only defined within the if statement. You're trying to clear it in the wrong scope. I still lack a bit of context here but you can try this:
var trafficInterval;
$("textarea").keyup(function() {
var text = $(this).val();
$(".log").text(text);
// Commands
if (text != "") {
var badCommand = $("textarea").val();
if (text == "help") {
$(".response").html("Commands:<br/><span class='indent'>traffic -url|all</span><span class='indent'>google #search term</span><span class='indent'>youtube #search term</span><span class='indent'>portfolio</span>")
} else if (text == "traffic") {
$(".response").html('Live traffic from:<br/><table><tr><td><strong>IP</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr><?php try { $db = new PDO("mysql:host=$mysql_host;dbname=$mysql_db", $mysql_user, $mysql_pass); $sql = "SELECT * FROM traffic ORDER BY id DESC LIMIT 50"; foreach ($db->query($sql) as $row) { echo "<tr>"; echo "<td class='
details '>" . $row["ip"] . "</td>"; echo "<td class='
details '>" . $row["proxyip"] . "</td>"; echo "<td class='
details '>" . $row["ping"] . "</td>"; echo "<td class='
details '>" . $row["time"] . "</td>"; echo "</tr>"; } $db = null; } catch(PDOException $e) { $e->getMessage(); } ?></tr></table>');
} else if (text == "load") {
$(".response").text("working!");
var traffic = function load() {
$.ajax({
url: "load.php",
success: function(result) {
var obj = jQuery.parseJSON(result);
var ids = obj.map(function(el) {
return "<tr><td>" + el.id + "</td><td>" + el.ip + "</td><td>" + el.proxyip + "</td><td>" + el.ping + "</td><td>" + el.time + "</td></tr>";
});
$(".response").html("<table><tr><td><strong>ID</strong></td><td><strong>IPs</strong></td><td><strong>Proxy IP</strong></td><td><strong>Ping</strong></td><td><strong>Time</strong></td></tr>" + ids + "</table>");
}
});
};
trafficInterval = setInterval(traffic, 2000);
} else {
$(".response").text("'" + badCommand + "'" + " is not a valid command, type 'help' for a list of commands.");
clearInterval(trafficInterval);
}
}
if (text == "") {
var noCommand = $("textarea").val();
$(".response").text(" ");
}
// End Commands
Move the variable declaration
var trafficInterval = null;
before the keyup eventhandler (to move it to the outside scope). See working, stripped down example here:
http://jsbin.com/yitiquwoce/1/

Categories