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)
Related
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();
}
})
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/
Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.
I'm new to jquery and ajax. I'm trying to get my first ajax script to work, but it's not working and I need some assistance, please.
I have a php page that is supposed to post to another php page, where the latter will do some processing and get some files to get zipped and download. The user needs to input a starting and ending date, and the second php script will use this information to prepare the data. This functionality works perfectly fine without jquery, but doesn't work when I add jquery.
What do I want to achieve? I want to post in the to the same php page and get the post output in a <div></div> tag.
My first php page contains (downloadPage.php):
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<form action="doDownload.php" method="post" id="dateRangeID">
<input id='time1' class='input' name="datefield1" style="text-align:center;"/>
<input id='time2' class='input' name="datefield2" style="text-align:center;"/>
<input type="submit" value="Download Data" name="submit" id="submitButton">
</form>
<div id="result"></div> <!-- I would like it to post the result here //-->
The second page (doDownload.php),
<div id="content">
<?php
if(isset($_POST['submit']))
{
$dateVal1 = $_POST['datefield1'];
$dateVal2 = $_POST['datefield2'];
if($dateVal1 != $dateVal2)
{
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename="file.zip"');
$fullListOfFiles = $downloadFullTmpFolder.$filesList;
$command = "sudo $ldlib -u myuser /usr/bin/python3 $downloadScriptFile -datadir $gnomeDataDir -time1 $dateVal1C -time2 $dateVal2C -outdir $downloadFullTmpFolder > debug_download.txt 2>&1";
$output = shell_exec($command);
$fp = popen('cat '.$fullListOfFiles.' | sudo -u myuser zip -# -9 - ', 'r');
$bufsize = 1024;
$buff = '';
while( !feof($fp) )
{
$buff = fread($fp, $bufsize);
echo $buff;
}
pclose($fp);
}
else
{
echo("<p>Dates have to be different in order for the download to start.</p>");
}
}
else
{
echo("<p>Error: Page called without submit.</p>");
}
?>
</div>
Finally, the jquery part in downloadPage.php, which if I add it doesn't work anymore (which I'd like to learn how to do right, and I mainly learned from the manual of jquery, the last example in the link)
<script>
/* attach a submit handler to the form */
$("#dateRangeID").submit(
function(event)
{
event.preventDefault();
var $form = $(this),
t1 = $form.find("input[name='datefield1']").val(),
t2 = $form.find("input[name='datefield2']").val(),
subm = $form.find("input[name='submit']").val(),
url = $form.attr('action');
var posting = $.post(url, { datefield1: t1, datefield2: t2, submit: subm} );
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content'); // <--- So this turns out to be wrong. Right is only $(data);
$("#result").empty().append(content);
});
});
</script>
What is wrong in this? Please assist. Thank you.
If you require any additional information, please ask.
Looking at the obvious, you have:
var content = $(data).find('#content');
where, you're trying to find an element with the ID content in one of the following results:
<p>Dates have to be different in order for the download to start.</p>
or
<p>Error: Page called without submit.</p>
I want to post data to a PHP file in a server (www.domaine.com) using a JavaScript located in computer / mobile app
example : test.php
<?php
$x = $_POST['count'];
for ($i = 0; $i < $x; $x++)
echo $x;
?>
data to be post using JavaScript and PSOT method to test.php
example
input
test.php / post data : count=5
output
01234
I want JavaScript to get me the output (01234) after posting (count=5) to (test.php) located in external server (www.domaine.com)
I basically develop in C# but as I'm obliged to do a cross-platform mobile app I switched to JavaScript (won't use Xamarin) for C# I was able to do everything using WebBrowser but not anymore in JavaScript, isn't there any object equivalent to WebBrowser in .NET ?
I need it for a mobile app that will load data from GPS Tracking website, API returns data in both XML and JSON
note : I don't have access to the external server
Here I'll give you a pretty good example of how these things are usually managed.
Still, it's up to you and your programming experience to grasp the meaning of it.
html and js example:
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
}
$("#submit").click(function(){
$("#formId").submit();
});
$(document).ready(function () {
$("#formId").bind("submit", function (event)
{
$.ajax({
async: true,
data: $("#formId").serialize(),
success: function(data, textStatus) {
getPhpResponse( data )
},
type:"POST",
url:"name/and/location/of/php/file.php"
});
return false;
});
});
</script>
file.php example:
<?php
$x = $_POST['count'];
echo '{"response":"';
for ($i = 0; $i < $x; $i++)
{
echo $i;
}
echo '"}';
Poxriptum:
There should be further input validation, one can't trust the type="number" just yet.
That the submit button is a span instead of an input is a personal choice that makes difference just for styling purposes.
You should read up on AJAX and JSON.
Consider using a PHP framework, such as CakePHP; it may serve you well.
This answer assumes you have access to the server. If you don't, then you should be reading the API documentation instead of asking questions on SO without even detailing which API you are talking about.
Edit:
Here is the $less version.
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
document.getElementById("submit").onclick = function () {
var url = 'name/and/location/of/php/file.php';
var userInput = encodeURIComponent(document.getElementById("inputNumber").value);
var data = "count=" + userInput;
makeRequest( data, url );
};
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
console.log(data);
parsed = JSON.parse(data);
console.log(parsed);
}
var xhr = new XMLHttpRequest();
var makeRequest = function( data, url ) {
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if ( xhr.readyState == 4 )
{
if ( xhr.status == 200 || window.location.href.indexOf("http") == -1 )
{
getPhpResponse(xhr.responseText);
}
else
{
console.log("Manage error here");
}
}
}
</script>