I am building a very simple chat application, nothing too fancy just a way for multiple users to chat at once.
The problem I am having is that whilst I can read and display messages from the database, no new messages will get inserted.
I am using JavaScript to pass a $.Get with the message and the username. I have checked the console and there is no errors showing but I have an undefined index: text and undefined index: username when I use POSTMAN to test.
Can anyone help push me in the right direction to solve this?
chat.php
<div class="wrapper">
<p id='chat-user'> </p>
<div id='chat-area'></div>
<form id='send-message-area'>
<textarea name="the-textarea" id="the-textarea" maxlength="150" placeholder="Start Typing..."autofocus></textarea>
</form>
<button id='chatSend' class="btn btn-info" type="submit">Post New Message</button>
<div id="the-count">
<span id="current">0</span>
<span id="maximum">/ 150</span>
</div>
</div>
var name = prompt("Enter your name:", "Guest");
if (!name || name === ' ') {
name = "Guest";
}
window.onload = function () {
document.getElementById("chat-user").innerHTML = "Your are: " + name;
};
$(document).ready(function () {
var chatInterval = 250;
var $chatOutput = $("#chat-area");
var $chatInput = $("#the-textarea");
var $chatSend = $("#chatSend");
function sendMessage() {
var chatInputString = $chatInput.val();
$.GET("testProcess.php", {
username: name,
text: chatInputString
});
retrieveMessages();
}
process.php
<?php
error_reporting(E_ALL);
include ("connection.php");
$username = substr($_GET["username"], 0, 32);
$text = substr($_GET["text"], 0, 150);
$nameEscaped = htmlentities(mysqli_real_escape_string($conn, $username));
$textEscaped = htmlentities(mysqli_real_escape_string($conn, $text));
$timestamp = date("Y-m-d H:i:s");
$insertMessage = "INSERT INTO message (messageID, messageBody, timeSent, nickname, sent) VALUES ('', '$textEscaped', '$timestamp', '$nameEscaped')";
$result = mysqli_query($conn, $insertMessage);
Your postman request is wrong as shown in the picture
you are passing the param GET with the value send but in your php script you have $_GET["username"] and $_GET["text"] the method GET is already set in the left side of the url in the picture so you dont need to send it what you want to send is the param username and text so the url would look like this
http://xxxxxxx/testProcess.php?username=Guest&text=test
as for your javascript code the jquery method for get is $.get and not $.GET and you are missing a way to handle the submit of the form because your submit button is outside of the form so a correct way to this would be
var name = prompt("Enter your name:", "Guest");
if (!name || name === ' ') {
name = "Guest";
}
window.onload = function() {
document.getElementById("chat-user").innerHTML = "Your are: " + name;
};
$(document).ready(function() {
var chatInterval = 250;
var $chatOutput = $("#chat-area");
var $chatInput = $("#the-textarea");
var $chatSend = $("#chatSend");
//intercepting the submit event to call the sendMessage function
$("#send-message-area").on("submit", function(e) {
e.preventDefault();
sendMessage()
})
function sendMessage() {
var chatInputString = $chatInput.val();
$.get("testProcess.php", {
username: name,
text: chatInputString
});
retrieveMessages();
}
})
Related
I'm making a dynamic website that need to show the user's name in the heading. The heading should say 'Hello, ', when the user enters their name into the text box and presses the button. And the name has to stay on the page even if I refresh the page.
What will be the javascript functions and html codes to implement this?
However, to implement this, the site need to read the query string when the page is loaded, not when the button is pressed. How can I write functions for the onload event for this?
I've tried this, but this doesn't work.
function setUserName() {
var userName = document.getElementById("userName").value;
localStorage.setItem("userName", userName);
}
function getUserName() {
var userName = localStorage.getItem("userName");
return userName;
}
function displayUserName() {
var userName = getUserName();
if (userName) {
document.write("Hello, " + userName);
} else {
document.write("Hello, world!");
}
}
<input type="text" id="userName">
<button onclick="setUserName()">Set Name</button>
<body onload="displayUserName()"></body>
Try this code, It might helpfull to you
function setUserName() {
var userName = document.getElementById("userName").value;
localStorage.setItem("userName", userName);
location.reload();
}
function getUserName() {
var userName = localStorage.getItem("userName");
return userName;
}
function displayUserName() {
var userName = getUserName();
if (userName) {
document.getElementById("helloText").textContent = "Hello, " + userName;
} else {
document.getElementById("helloText").textContent = "Hello, world";
}
}
<span id="helloText"></span>
<input type="text" id="userName" name="userName">
<button onclick="setUserName()">Set Name</button>
<body onload="displayUserName()">
</body>
Local storage wont work with the snippet by the way
I wanted to ask how can i get the values of the Javascript Input and store it into a php value so i can post this data into Sqlite3. Im receiving user inputs from the Javascript Prompts. Is there another way to accomplish this also. Any help would be greatly appreciated.
function myFunc(){
var code = prompt("Please enter authorized code twice for security purposes: ");
var email = prompt("Please enter email twice to continue: ");
if(code==""||code==null||code!="1234"){
//Handle Error
window.location.href="error.html";
}
}
document.onreadystatechange = () => {
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
myFunc();
}
});
}
Using jquery you can use the $.post method:
function myFunc() {
var code = prompt("Please enter authorized code twice for security purposes: ");
var email = prompt("Please enter email twice to continue: ");
var url = "phpToGetInputs.php";
var data = {
code: code,
email: email
}
$.post(url, data); // "send the data to the php file specified in url"
// code...
}
document.onreadystatechange = () => {
// code...
}
Then, in your PHP file (that you specified as the url)
phpToGetInputs.php:
<?php
if(isset($_POST['email'])) {
$email = $_POST['email']; // get the email input (posted in data variable)
$code = $_POST['code']; // get the code input (posted in data variable)
// do code that requires email and code inputs
}
?>
Use a jQuery post request to send the variable from javascript to php.
$.post([url], { "data" : text });
Look at this website for more information: https://api.jquery.com/jquery.post/
I'm making a login page where if the email address already exists i want to stay on the same page and prompt the user that the email address already exists.
Here is the function which is the onClick function that will be called when the button is clicked
function login() {
var username = document.getElementById("username").value;
var pword = document.getElementById("pword").value;
var confpwd = document.getElementById("confpwd").value;
var email = document.getElementById("email").value;
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var gender = document.getElementById("gender").value;
var t = 1;
if (t.toString() !== '0') {
var er = "Email-id already exists";
event.preventDefault();
document.getElementById("nemail").value = er;
document.getElementById("username").value = username;
document.getElementById("pword").value = "";
document.getElementById("confpwd").value = "";
document.getElementById("fname").value = fname;
document.getElementById("lname").value = lname;
document.getElementById("gender").value = gender;
}
}
You must pass a function to the <form onsubmit="return login()">. The login function must return true if you want to submit and false otherwise. See this answer for more details: JavaScript code to stop form submission
Working codepen to illustrate: http://codepen.io/DeividasK/pen/YZqwLO
Depending on how your code is setup to submit. You may just need to insert a return when the code realizes the email address is a duplicate. Something along this path might help prevent the page from moving forward.
if (ListOfExistingEmails.indexof(email) > 0 ) return false;
Hello guys im new on Google Script,
im making an app that read the input from the box,
and then send it to the mysql.
I have this:
-
Codigo.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('getIp');
}
var connection = Jdbc.getConnection("jdbc:mysql://HOST:PORT/DB", "USER", "PW");
// perform the query
var SQLstatement = connection.createStatement();
var result = SQLstatement.executeQuery("Insert Into IPS Values(IPFromPrompt,0)");
Look at "IPFromPrompt" there is where i want IP from the following code
GetIp.html
<div>
<p>Click the button and enter your IP Addess.</p>
<button onclick="myFunction()">Try it</button>
<p id="AddIP"></p>
<script>
function myFunction() {
var IP = prompt("Please enter your IP Address", "");
if (person != null) {
document.getElementById("AddIP").innerHTML =
"Added " + IP + "to our database";
}
}
</script>
</div>
Do you know how can i do that?
I think you've got multiple problems here. You need a google.script.run call to trigger the .gs code from the HTML. Your myFunction() function needs to have google.script.run.
<script>
function myFunction() {
var IP = prompt("Please enter your IP Address", "");
var theUserInput = To Do . . .Get user input;
google.script.run
.withSuccessHandler(onSuccess)
.processInput(theUserInput)
}
function onSuccess(argIP) {
if (person != null) {
document.getElementById("AddIP").innerHTML =
"Added " + argIP + "to our database";
}
};
</script>
Codigo.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('getIp');
}
function processInput(argGetInput) {
var connection = Jdbc.getConnection("jdbc:mysql://HOST:PORT/DB", "USER", "PW");
// perform the query
var SQLstatement = connection.createStatement();
var result = SQLstatement.executeQuery("Insert Into IPS Values(IPFromPrompt,0)");
return result;
};
I have made a Script sendsms.php which executes and sends SMS with HTTP API. I call sendsms.php with a Java script (Button) and get back results in a text input window.
When I press my Java Button the phone number is automatically sent to sendsms.php and it executes. Below in my CODE you can see how the #phone is sent (with Java) and how its retrieved by sendsms.php
My question is: Now I want add and SEND #nick_name together with #phone. How should I do that?
My Jave Button:
<script type="text/javascript">
$(document).ready(function() {
$('.smsbutton').click(function() {
var val = $('#phone').val();
$.get('http://mydomain.com/sendsms.php', {phone: val}, function(data) {
result = $.parseJSON(data);
$("input[name='avaresultsms']").val(result.avaresultsms);
});
});
});
</script>
<br />
<input type="text" name="avaresultsms" value="" style="width: 370px;" readonly="readonly" />
<input id="smsbutton" name="smsbutton" type="button" class="smsbutton" value="SEND SMS">
And here is sendsms.php:
<?php
$phone = $_GET['phone'];
$smstophone = str_replace("+", "", $phone);
$sendapi = 'http://sms.com/api.php=sendsms&user=MYUSERNAME&password=MYPASS&&from=Escort%20Home&to='.$smstophone.'&text=Hello%20'.$nick_name.'%20Test1%20test2';
$smsrsult = file_get_contents($sendapi);
$result['avaresultsms'] = $smsrsult;
echo json_encode($result);
?>
As you can see I use var val = $('#phone').val(); in Java Button so with sendsms.php I can get it with: $phone = $_GET['phone'];
But now I also want to get $nick_name = $_GET['nick_name']; What should I add to Java script?
Thank you very much for your help.
THIS WORKED FOR ME:
var nickname = $('#nick_name').val();
$.get('http://mydomain.com/sendsms.php', {phone: val, nick_name: nickname}, function(data) {
try something like this
var val = $('#phone').val();
var nick_name_val = 'sample name';
$.get('http://mydomain.com/sendsms.php', {phone: val,nick_name: nick_name_val}, function(data) {
result = $.parseJSON(data);
$("input[name='avaresultsms']").val(result.avaresultsms);
});
Just add the nick name like how you got phone and add it to the object.
var nickname = $('#nickname');
$.get('http://mydomain.com/sendsms.php', {phone: val, nick_name: nickname}, function(data)