How to send serial output from arduino to textbox with ajax jquery - javascript

Would anyone happen to know how to receive a usb serial output from a device and send it to an html textbox using jQuery? I understand how to send a command using ajax and jQuery to a serial device, but I cannot figure out how to receive a message sent back from the device?
The following javascript is what I use for sending a message to the device, Arduino, from a button click:
<!-- Arduino Serial Connection -->
<script type='text/javascript'>
jQuery(function() {
jQuery('#contact_form').on('click', '.button',function (e) {
e.preventDefault(); //prevents the default of submitting the form
jQuery.ajax({
type: "POST",
url: '/test/SubmitFormWORefresh.php',
data: "rcmd="+jQuery(this).val(),
success: function() {
alert('Enroll Your Finger Now');
}
});
return false;
});
});
</script>
And here is the SubmitFormWORefresh.php:
<?php
$verz="1.0";
$comPort = "/dev/ttyACM0"; /*change to correct com port */
$PHP_SELF="index.php"; //This php file locate it from root
if (isset($_POST["rcmd"])) {
$rcmd = $_POST["rcmd"];
switch ($rcmd) {
case "Stop":
$fp =fopen($comPort, "w");
sleep(2);
fwrite($fp, 1); /* this is the number that it will write */
fclose($fp);
break;
case "Enroll":
$fp =fopen($comPort, "w");
sleep(2);
fwrite($fp, 3); /* this is the number that it will write */
fclose($fp);
break;
default:
die('Crap, something went wrong. The page just puked.');
}/*end switch case*/
}/*end if statemen t*/
?>
The following code is from the index.html page that displays the button that javascript manipulates, and also the textbox that I want the output of the serial device to display to.
<!----This is the button that I first send a message to the device -->
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<input type="submit" name="rcmd" class="button" id="submit_btn" value="Enroll" />
</fieldset>
</form>
</div>
<!----This is the textbox I need to send incoming data to-->
<input type="text" value="" id="table_0_fprint_id" data-key="fprint_id" data-input_type="text" class="editDialogInput " />
After I click the button and send a message to the device, the device then sends a message over a serial connection back to the webpage. I need the javascript to input this message into the textbox. I know I will probably need use the GET function, but I cannot get it to work properly.

All you need to do is to handle the ajax response. In my example i called it response (argument to the anonymous function bind to success). Code is untested, but should work:
<!-- Arduino Serial Connection -->
<script type='text/javascript'>
jQuery(function() {
jQuery('#contact_form').on('click', '.button',function (e) {
e.preventDefault(); //prevents the default of submitting the form
jQuery.ajax({
type: "POST",
url: '/test/SubmitFormWORefresh.php',
data: "rcmd="+jQuery(this).val(),
success: function(response) {
alert('Enroll Your Finger Now');
$("input#table_0_fprint_id").val($(response).text());
}
});
return false;
});
});
</script>
You also have to make sure that /test/SubmitFromWORefresh.php script prints/echo'es a message to be placed in the input on response.

Related

How to send and receive data from electron desktop app to a php website?

I am an intern at nodejs and php developer..
I want to check my desktop application availability by verifying macaddress in the database of a php website.I tried sending data from app using href="xyz.com?name=abc". it loads this page in the desktop application, but I can not go back to html page of the app with some returning value.Can go back to app html page with window.history.back(), but it can not retrieve any value, other functions search the page in website directory.like window.location.href().
I also tried ajax in the html page of application , it also not working..
HTML page in electron application..
<body>
<h1>Hello World!</h1>
<p id="ptext"></p>
<form>
<input type="hidden" name="value" value="abc">
<button id="start">start</button>
</form>
<script type="text/javascript"> console.log('hello');
// document.getElementById('ptext').innerHtml = window.location.search();
$(document).ready(function{
console.log('started document');
$('#start').click(function{
var formData = $(form).serialize();
alert(formdata);
$.ajax({
type: 'GET',
data: formData,
url: "http://localhost/newproject/index.php",
success: function (data, status, xhr) {
$('#ptext').append(data)
},
error: function (jqXhr, textStatus, errorMessage) {
$('#ptext').append('Error: ' + errorMessage)
}
});
});
});
</script>
Php website page
<?php
$val = $_GET['value'];
echo "\n".$val;
if($val=='abc')
{
?>
<!-- <script type="text/javascript">window.history.back();</script>
--><?php
echo "\nright value";
}
else
{
echo "\nwrong value";
}
// echo "\n".$_SERVER['HTTP_REFERER']; -------> does Not have any value , undefined
// header("location:index.html?result==right/wrong") -----> it search this page in website directory
?>
Now , how do I return some data to nodejs electron application.
It will be a great help for my project.
Thank you everyone for having a look at my first question on this website.

PHP code doesnt work together with JS function on "onclick"

i have a button in which i want it to perform 2 task; php and js.
The php part : generate different text everytime the button is pressed.
The js part : disabling the button for 5 secs and then enabling it back.
HTML
<button onclick = "disable();" class=btnGenerate type="submit" id="submit" name="submit" >GENERATE</button>
PHP
if(isset($_POST['submit'])){
$num=mt_rand(1,10);
$result=mysqli_query($con,"SELECT * from quote_table where id=$num");
$row = $result->fetch_assoc();}
JS
<script>
function disable(){
document.getElementById("submit").disabled = true;
setTimeout(function() { enable(); }, 5000); }
function enable(){
document.getElementById("submit").disabled = false;
}</script>
The PHP part only works when i delete the "onclick = "disable();" on the html but it doest seem to work when i add it. Can a button carry out PHP and JS at a single click ? Thanks in advance.
A disabled button can't be a successful control.
Don't depend on the name/value of the submit button being submitted in the form data if you are going to disable it.
Replace isset($_POST['submit']) with some other condition.
If you trigger a form submission, unless you're using AJAX the page will simply reload, rendering the enable() method moot unless
you're using it to re-enable the button on fail condition or on
successful return of data via AJAX.
It's sounds to me like you're trying to get data via request to the server, without reloading the page, and then re-enable the submit button after the data is returned. In that case you need to use AJAX.
HTML
<form action="/" method="post" id="form">
<button class=btnGenerate type="submit" id="submit" name="submit" >GENERATE</button>
</form>
JS
<script>
document.getElementById('submit').addEventListener('click', function(event){
event.preventDefault(); // prevents browser from submitting form
var form = document.getElementById('form');
var submit = document.getElementById('submit');
// using JQuery ajax
$.ajax(form.action, {
data: form.serialize(),
beforeSend: function() { // runs before ajax call made
// disable submit button
submit.disabled = true;
},
success: function(response) {
console.log(response);
// deal your return data here
},
error: function(error) {
console.log(error);
// deal with error
},
complete: function() { // runs when ajax call fully complete
// renable submit button
submit.disabled = false;
}
});
});
</script>

AJAX call not working - PHP, MySQL, jQuery/Ajax

I have the following problem:
What i'm trying to accomplish is:
User clicks on a submit/image type button
Ajax call handles the submit, calls another PHP script to update a record in a MySQL table, all without reloading the page ( obviously )
My PHP code is working fine without the AJAX, as it will reload and update the record. but somehow the ajax call is not working and/or returning any error.
My code:
$(function() {
$('#like_form').submit(function(event) {
event.preventDefault(); // Preventing default submit button
var formEl = $('#like_form');
var submitButton = $('input[type=submit]', formEl);
$.ajax({
async: true,
type: 'POST',
url: formEl.prop('action'),
accept: {
javascript: 'application/javascript'
},
beforeSend: function() {
submitButton.prop('disabled', 'disabled');
}
}).done(function(data) {
submitButton.prop('disabled', false);
$("#like").fadeOut();
$("#like").fadeIn();
});
});
});
<!-- LIKE een gebruiker -->
<form action="" id="like_form" method='POST' enctype="multipart/form-data">
<input onmouseover="this.src='img/heart2.png'" onmouseout="this.src='img/heart.png'" name='like' id="like" src='img/heart.png' type="image" />
</form>
my PHP (just in case):
<?php
include_once "dbconnection.php";
//if like button (submit button) clicked
if ($_POST){
$conn = DatabaseConnection::getConnection();
$sql = "UPDATE dating_members
SET likes = likes + 1
WHERE member_id = 3";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
?>
I figured out what the problem is, Kind of silly I didn't notice but better late than never.
I had to 'include' the JS script at the end of my PHP page in order to catch my onsubmit function and therefore disable the default event a.k.a submit button submitting my form and page reload / POSTs to the other PHP file.
Everything is working fine now

Save form inputs to txt, popup result, no page changing

I would like to build a newsletter subscription function to my website. and I want to get all the input save into a txt file in the host folder. However, I don't want to switch page after people submit it. Just show a popup message saying "Thank You for Subscribing" will be perfect. I know how to do it with PHP to show a message in a separate page, but not sure how to do it in a popup box. Here is my html and PHP code. Please help, thanks a lot.
<html>
<head>
<title></title>
</head>
<body>
<form>
<form action="myprocessingscript.php" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Text file</a>
</body>
PHP function is
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
Once you have included jQuery to your page, something like following should work:
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'field1' : $('input[name=field1]').val(),
'field2' : $('input[name=field2]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myprocessingscript.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// data is the output from your php, check it and display alert appropriately
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Take a look at source article

reload a div again without using load()

I have a form through which I want to upload a user's name which works fine but want to display it right after he uploads it by clicking "Save" button(of submit type) without reloading the page.Right now, the name is getting uploaded but appears only when I reload the page.Any suggestions?Please dont suggest using load() as it has compatibility problem with different browsers.
<div id="nameform">
//contains code to upload name via form
</div>
<div id="name">
<?php
$query1=mysqli_query($dbc,"select * from users where Email='".$_SESSION['Email']."'");
$row=mysqli_fetch_assoc($query1);
$name=$row['name'];
if ($name!="")
echo "$name";
else echo "Your name please....";
?>
</div>
$("#btn").click(function() {//#btn is a submit button in the form
document.getElementById("name").style.display="block";
document.getElementById("nameform").style.display="none";
});
$("#formname").submit(function () {
$.ajax({
url:"formname.php",
data:$("#formname").serialize(),
type:"POST",
success:function(data){
console.log(data);
if(data=="xyz"){
$("#formname")[0].reset();
$("#formname").on("click",".sframe",f(0));
}
},
error:function(data){
alert("Network error");
}
})
return false;
});
I am assuming that you have written insertion code in ajax page formname.php. On Ajax call if the name successfully inserted in database you fetch the name using your select query
$query1=mysqli_query($dbc,"select * from users where Email='".$_SESSION['Email']."'");
$row=mysqli_fetch_assoc($query1);
$name=$row['name'];
and echo the user name.
else
echo "0" for error handling .
now in your ajax call script instead of
if(data=="xyz"){
$("#formname")[0].reset();
$("#formname").on("click",".sframe",f(0));
}
put
if(data!=0){
$("#name").text(data); // It will put the name in the div
$("#formname").on("click",".sframe",f(0));
}
else
{
alert("Data insertion error");
}

Categories

Resources