Clark Bernales Clark Bernales - 1 month ago 18
Ajax Question

ajax realtime refresh of values of word occurences using php

I tried searching for solutions but I could not handle it properly. Also, I want it to display using AJAX. So every time I type a word, it will appear below the textbox with a counter beside it.
My current code is this:

The output should be like this:
with the input of "the quick brown fox"

brown -- 1
fox -- 2
quick -- 1
the -- 1


but my current output is:

brown -- 1
fox -- 1
fox -- 2
quick -- 1
the -- 1
//the fox displays twice.


My index.php

<!DOCTYPE html>
<html>
<head>
<title>Working with Javascript</title>
<script type="text/javascript" src="js/jquery-3.2.1.min.js">
</script>
</head>

<body>
<!--textbox-->
<input type="text" name="input" id="textInput" autofocus/>
<!--where the answer will appear-->
<div id="content"></div>
</body>
<script type="text/javascript">
//get the content of the textbox
var textInput = document.getElementById("textInput");
//transform it into jQuery
var jTextInput = $("#textInput");
var divSelector = document.getElementById("content");
//the AJAX function
textInput.onkeyup = function () {
console.log($("#textInput").val());
$.ajax({
"method": "POST", //to specify what type of METHOD to
REQUEST in the SERVER (GET or POST)
"url": "assignment2.php", // where to send the request
"dataType": "JSON", // datatype of the request
"data": {
"text": $("#textInput").val() //DATA values that you'll
send
},
success: function (res) {
$("#content").html(res.reversedString);
}
});
};
</script>
</html>


and my assignment2.php

<?php
/*
//note: if you delete everything and left the commented code below, the text
displays as you type in the textbox.
//$vari = array("reversedString" => $_POST['text']);
//echo json_encode($vari);
*/
////////////////////////////////////////////////////
//get the content of textbox
$vari = array("reversedString" => $_POST['text']);
$var = $vari;
header('Content-Type: application/json;charset=utf-8');

//make it an array
$words = explode(' ', $var);
//sort by a-z
sort($words);
$result = array_combine($words, array_fill(0, count($words), 0));
//total number of words
$len = count($words);
//the array for the number of occurences
$totals = array();

foreach ($words as $word) {
$result[$word] ++;
array_push($totals, $result[$word]);
}
//the array for the words and number of occurences
$finalarray = array();
for ($i = 0; $i < $len; $i++) {
array_push($words[$i] . " -- " . $totals[$i] . " <br>");
}
//make the array back to sentence
$regularexpression = implode(" ", $finalarray);

$last = array("reversedString" => $regularexpression);
echo json_encode($last);


I'll answer any blurry information I have. This is an assignment of mine. Please help and thankyou for patience :)

Answer Source

Use if statement inside your for each loop

You check if it's there, using in_array, before pushing.

foreach($words as $word){if(!in_array($word, $liste, true)){
    array_push($liste, $word);
}}