POST with Javascript AJAX - javascript

I am currently writing some poll software and, even though it works fine, I am having difficulties getting some of my javascript to work. I have a button labelled "Add New Option" which, when clicked, will call the following javascript function:
function newoption()
{
var option = "";
while((option.length < 1)||(option.length > 150))
{
var option = prompt("Please enter the option value... ").trim();
}
var add = confirm("You entered " + option + ", are you sure?");
if(add==1)
{
var code = window.location.href.length;
var poll = prompt("Which poll are you adding this to?", window.location.href.substring(code - 5, code));
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{this.responsetext = option;}};
xhttp.open("POST", "../special/new.php", true);
xhttp.send("poll=" + poll + "&opt=" + option);
}
else
{
alert("OK... try again");
}
}
The page it posts to simply has a function to add the option to the poll which the user supplies the code for (it automatically gets this from the end of the URL) but the problem is that, when I refresh the page, the list of options is not updated which makes me think it isn't being added to the database but the function to add new options works on when the poll is created. Is there something I'm doing wrong?
The code for new.php is:
<?php require("internal/index.php");
$option = string_format($conection, $_POST["opt"], 1)
$poll =(int) $_POST["poll"];
if($poll&&$option)
{
new_poll_option($connection, $poll, $option);
}
?>

From what you wrote I understand that the code works until you refresh the page. That means that you don't check the Ajax response and just insert some HTML which will last until you refresh the page.
You need to look in your database if the items was created. If it is created then maybe you need to delete the browser cache (you can do that from the Network tab in DevTools in Chrome).
If the items was not insert in the database then you need to debug or just echo the message from the insert function that you used.
You can also use a form and not use Ajax if you will refresh the page anyway in a few moments.

Related

execute code after typing indication over

i have problem figuring out a solution . i am developing a chatbot .
this is my html where i print all the discussion , its just one :
<div id="divChat"> </div>
i want to add typing indicator to it .here is how it works on each message:
1)User types his message (exemple : Hello), and click on a button
<button onclick="sendMessage()" id="btn1" > Send </button>
2) i read his message and i sent it to mybackend application to receive the response and print it in the chat element.
function sendMessage(){
var url = "http://localhost:3000/api/v1/bots/renault/converse/user1";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var reponseBot= JSON.parse(xhr.responseText);
if(reponseBot!='undefined'){
$("#divChat").append(reponseBot+"</br>");
}
}
}
};
var values = {
type: "text"
}
values.text=$("#userMessage").val();
var data= JSON.stringify(values);
xhr.send(data);
}
the chat works fine , now i want to add typing indicator which is this element (u dont need see css of it):
<div class="typing-indicator"></div>
i want When the user send his message i Append the typing indicator to the chat , show it for 2sec then hide it and append then response bot : like this
if (xhr.readyState === 4 && xhr.status === 200) {
var reponseBot= JSON.parse(xhr.responseText);
if(reponseBot!='undefined'){
$("#divChat").append("<div class='typing-indicator' ></div>");
/// I WANT TO HIDE IT AFTER 2SEC THEN APPEND THE USER RESPONSE
$("#divChat").append(reponseBot+"</br>");
}
}
Please any idea how to achieve this and thanks
You can use setTimeout to delay an action.
Also note that if you've already included jQuery in the page you may as well use its AJAX methods to simplify the code. Try this:
let $divChat = $('#divChat');
function sendMessage() {
$.post('http://localhost:3000/api/v1/bots/renault/converse/user1', {
type: 'text',
text: $('#userMessage').val()
}, function(response) {
$('#userMessage').val(''); // empty the typed message
let $indicator = $('<div class="typing-indicator"></div>').appendTo($divChat);
setTimeout(() => {
$indicator.remove();
$divChat.append(response + "</br>");
}, 2000);
});
};
Also note that from the response to your AJAX request it looks like you're returning a plain text response which is not ideal, as it can be affected by whitespace. I'd suggest you amend your server side logic to return a serialised format, such as JSON or XML.

Call 'POST' route via Javascript so I can update record in database (using node.js, express framework, PUG, mongodb)

I'm trying to update a record in my database when a user decides to edit a table. I use javascript to make the table editable row by row and I change the button from 'Edit' to 'Save' image of table before a user can edit and image of table after a user clicks edit .
Once a user clicks'Save', I want to be able to call the route that will find the old record, and overwrite with the new record. I'm having troubles calling the route in my javascript. I've tried to use "location.href = '/people/updateshift'" but it doesn't because it load the people/update shift page, and I just want to be able to call the route in the background without sending a user to the page. Any resources, or pointers would be appreciated :)
Thank you in advance!
function editRow(obj) {
var currentTD = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
var row_length = document.getElementById("myTableData").rows[currentTD].cells.length;
console.log(obj.parentNode);
//the below is a way to get the HMTL within a cell
console.log(document.getElementById("myTableData").rows[currentTD].cells[0].innerHTML);
if (obj.value == 'Edit') {
document.getElementById("myTableData").rows[currentTD].cells[0].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].cells[1].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].cells[2].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].cells[3].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].cells[4].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].cells[5].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].style.backgroundColor = "#A4D9F5";
var_employeetype = document.getElementById("myTableData").rows[currentTD].cells[0].innerHTML
var_daysworked = document.getElementById("myTableData").rows[currentTD].cells[1].innerHTML
var_num_employees = document.getElementById("myTableData").rows[currentTD].cells[2].innerHTML
var_shift_start = document.getElementById("myTableData").rows[currentTD].cells[3].innerHTML
var_shift_start = document.getElementById("myTableData").rows[currentTD].cells[4].innerHTML
var_shift_end = document.getElementById("myTableData").rows[currentTD].cells[5].innerHTML
console.log(var_employeetype)
obj.value = 'Save'
} else {
document.getElementById("myTableData").rows[currentTD].cells[0].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].cells[1].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].cells[2].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].cells[3].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].cells[4].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].cells[5].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].style.backgroundColor = "#FFFFFF"
obj.value = 'Edit'
location.href = '/people/updateshift'
}
}
You want to look into the jQuery "post" feature. https://api.jquery.com/jquery.post/
When the user clicks save, send the value to the server using $.post, and an identifier for which "cell" it is (I don't know how you are doing this), and then have your server deal with updating the record.

AJAX Database make high CPU process

My Code for requast number notification :
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var Bil = xhttp.responseText;
document.getElementById("MsgNoti").innerHTML = Bil;
if ( Bil != ""){
if (ChkSession != "Mobile"){
window.open("Message/ViewMsgPopUp.asp", "", "width=900,height=600,top=25,left=100");
}
}
}
};
xhttp.open("GET", "CheckMsg1.asp", true);
xhttp.send();
}
This is code in CheckMsg1.asp
SQL ="select count(MsgID) over() as bil, MsgID from Msg where PopUpStatus = 'TRUE'"
set read = conn.execute(SQL)
if read.eof then
Bil = "0"
else
Bil1= read("bil")
end if
read.close()
Conn.Close()
response.write(Bil1)
Any problem with my code? Why this code make high CPU process in server when 25 - 30 user use. AJAX be run in 7 second use Javascript timer. Please help any suggestion for me? This code run in ASP Classic
Can you try this
select count(MsgID) from Msg where PopUpStatus = 'TRUE' Group by MsgId
I think Msg table has so much data, count() function scan all data in table. It is costly.
I Have some idea for your problem
1-)You can use Nosql db (Mongo,Raven tec.) instead of Msg table . Just write and read Msg data on Nosql db.
2-) Try to add index PopUpStatus on Msg table
3-) You can use summary table for count of Msg table. You can write a job on db this job get Count Msg table then write the count value different table

how do you connect an ajax post to a specific conditional in PHP file?

So i have written a function that is called onclick in my html file that uses AJAX, but i would like for this post to go to a specific table in mysql.
$('#submitIFC').click(function(e) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var opinionIFC = $('ul.sort').sortable('toArray').join(',');
request.onreadystatechange = function() {
if ((request.readyState===4) &&(request.status===200)) {
var return_data = request.responseText;
document.getElementById('rank_ul').innerHTML= 'return_data';
// Preventing the default action triggered by clicking on the link
e.preventDefault();
e.preventDefault();
}//end of if
}//end of onreadystatechange function
//send requested movie to php file which will send to the external server
request.open("POST", "results.php", true);
request.send(opinionIFC);
document.getElementById('rank_ul').innerHTML='<img src="ajax-loader.gif">';
});
however there seems to be an issue with connecting this to my php if conditional, i tried copying the contents on my request.send(), like so
if($_POST['opinionIFC'])
{echo
// The data arrives as a comma-separated string,
// so we extract each post ids:
$data=explode(',',str_replace('li','',$_POST['sortdata']));
// Getting the number of objects
list($tot_objects) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_objects"));
if(count($data)!=$tot_objects) die("Wrong data!");
foreach($data as $k=>$v)
{
// Building the sql query:
$str[]='('.(int)$v.','.($tot_objects-$k).')';
}
$str = 'VALUES'.join(',',$str);
// This will limit voting to once a day per IP:
mysql_query(" INSERT INTO `sort_votes` (ip,date_submit,dt_submit)
VALUES ('".$_SERVER['REMOTE_ADDR']."',NOW(),NOW())");
// If the user has not voted before today:
if(mysql_affected_rows($link)==1)
{
mysql_query(' INSERT INTO `sort_objects` (id,votes) '.$str.'
ON DUPLICATE KEY UPDATE votes = votes+VALUES(votes)');
}
}
why isnt the ajax post request filtering through to my php file?
thank you so much, any help is much appreciated.
You're not sending opinionIFC parameter, try:
request.send('opinionIFC=' + opinionIFC);
You also need to set Content-type
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");

fetching xml data into a div via ajax and javascript

Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps

Categories

Resources