I am working on a project in PHP and AIML where the bot replies to the user queries asked by a user through a microphone. I am new to jQuery and JS so I need help in implementing loading effect in between the user input and final output.
<?php
$display = "";
$thisFile = __FILE__;
if (!file_exists('../../config/global_config.php'));
require_once ('../../config/global_config.php');
require_once ('../chatbot/conversation_start.php');
$get_vars = (!empty($_GET)) ? filter_input_array(INPUT_GET) : array();
$post_vars = (!empty($_POST)) ? filter_input_array(INPUT_POST) : array();
$form_vars = array_merge($post_vars, $get_vars); // POST overrides and overwrites GET
$bot_id = (!empty($form_vars['bot_id'])) ? $form_vars['bot_id'] : 1;
$say = (!empty($form_vars['say'])) ? $form_vars['say'] : '';
$convo_id = session_id();
$format = (!empty($form_vars['format'])) ? $form_vars['format'] : 'html';
?>
<!DOCTYPE html>
<html>
<head>
<title>Interact With Sia</title>
<script src="jquery.js"></script>
<script type="text/javascript" src="talk.js"></script>
</head>
<body onload='document.getElementById("say").focus(); document.getElementById("btn_say").style.display="none";'>
<center>
<h3>Talk to Sia</h3>
<form id="chatform1" name="chatform" method="post" action="index.php#end" >
<!-- <label for="say">Say:</label> -->
<input type="text" name="say" id="say" size="70" onmouseover="startDictation()" style="color:red" />
<input type="submit" class="say" name="submit" id="btn_say" value="say" />
<script>
$('#say').trigger('mouseover');
</script>
<input type="hidden" name="convo_id" id="convo_id" value="<?php echo $convo_id;?>" />
<input type="hidden" name="bot_id" id="bot_id" value="<?php echo $bot_id;?>" />
<input type="hidden" name="format" id="format" value="<?php echo $format;?>" />
</form>
<br/><br/>
<?php echo $display; ?> //THIS DISPLAYS THE OUTPUT TO THE QUERY
</center>
</body>
</html>
As soon as the page loads, the microphone in the user's browser is activated [via talk.js_startDictation()] and after the user finishes the voice input, the query is sent to the scripts and then the result is diplayed by <?php echo $display; ?>.
How can I implement a loading effect in place of <?php echo $display; ?> until the script returns the result of the query and updates the $display variable on the page?
You could use AJAX to archieve this, like:
1 - Load jquery.js (you could use CDN or download it).
2 - Create a div with a loader (usually a gif is fine, there are a lot). Hidde it with css: display:hidden;
3 - Add at the bottom of your page:
<script>
// Attach a submit handler to the form
$( "#chatform1" ).submit(function( event ) {
// Start the loader
$('#loader').show();
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var data = $(this).serialize();
var url = "urlToYourPhpFile.php";
// Send the data using post
var posting = $.post( url, { data: data } );
// Put the results in a div
posting.done(function( dataResponse ) {
//do something with dataResponse
$('#loader').hide();
});
});
</script>
When the form is sumitted, jquery 'catch' the request, process the .submit() functions and send the data via post to a .php file (you should create it) and receive the params with $_POST. Something like:
yourPhpFile.php
<?php
$convo_id = $data['convo_id'];
//do something
...
?>
Related
as you can see in the code, I have a form which gets displayed by clicking on the "Edit" word. Then the user inputs his profile, which on submit, via Ajax, gets processed by a PHP script I have that saves it in SQL. Once saved, the form disappears and -theoretically- I would want the new profile to be copied back in there.
My question is: how do I get the to be fixed there, once I chance page? The SQL Update and .ajax work perfectly, but when I change page and go back here, I lose what's inside the div and the user won't be able to see his newly saved profile link.
As you can see, I have a session variable with the profile in the code which I print so that when user gain's first access to his account, he sees his profile. Unfortunately, this remains after he's saved the new profile.
I'd be really glad if you could help, it's been days now I've tried to get my head around this. Thank you very much!
<?php
session_start();
$email = $_SESSION['email'];
?>
<html>
<style>
#form1{display:none;}
</style>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {"action": "test"};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "tryoutwo.php",
data: data,
success: function(data) {
$(".the-return").html(data["profile"]);
}
});
return false;
});
});
</script>
</head>
<body>
<div class="container">
<table>
<tr>
<td><p><b>My Facebook profile:</b></td>
<td>
<div class="the-return"></div>
<p id="editprofile"><? php print($profile); ?>
<form action="return.php" onsubmit="hideform()" class="js-ajax-php-json" method="post" id="form1">
<input type="text" name="profile" value=""/>
<input type="submit" name="submit" value="Submit form">
</form>
</p>
</td>
<td><p onclick="return showform()"><a href>Edit</a></p></td>
</tr>
</table>
</div>
<script>
function showform() {
document.getElementById("form1").style.display = 'block';
document.getElementById("editprofile").innerHTML = "";
return false;
}
function hideform() {
document.getElementById("form1").style.display = 'none';
return false;
}
</script>
</body>
</html>
This is what you should do:
<?php
session_start();
if( isset( $_POST['profile'] ) )
$_SESSION['profile'] = $_POST['profile'];
?>
and the html
<p id="editprofile">
<?php
if( isset( $_SESSION['profile'] ) )
echo $_SESSION['profile']; ?>
</p>
Index.php
...
<form id="calculator_form" name="form" action="" method="get" >
<input name="one" type="text">
<input name="two" type="text">
<input type="submit">
</form>
...
<!-- refresh area -->
<?php if(isset($_GET["one"])) { ?>
<div>
<?php echo $_GET["one"] . " " . $_GET["two"]; ?>
</div>
<?php } ?>
<------------------->
I would like to submit the form and reload the refresh area indicated above. I know this can be achieved by using AJAX but I'm not quite sure how.
I have tried putting the refresh area in a separate ajax.php file and using JQuery but it didn't work;
$(document).ready(function() {
$("#calculator_form").submit(function(event) {
event.preventDefault();
$("#divtoappend").load("ajax.php", data);
})
})
I've also tried using $.get() but to no avail.
I'm able to send the data back and forth to a seperate php page but I'm stuck trying to achieve what I am looking for.
EDIT:
The code that I posted was quickly written and the syntax isn't the issue in question, I'm merely wondering how I can refresh a <div> under the form so that it will once again do the if(isset($_GET["one"])) check and print the updated php variables.
EDIT 2:
My code is now as follows:
Index.php
...
<form id="calculator_form" name="form" action="" method="get" >
<input name="one" type="text">
<input name="two" type="text">
<input type="submit">
</form>
...
<div id="append">
<!-- where I want the ajax response to show -->
</div>
...
ajax.php
<?php if(isset($_GET["one"])) { ?>
<div>
<?php echo $_GET["one"] . " " . 4_GET["two"]; ?>
</div>
<!-- assume there's n number of divs -->
<?php } ?>
Now I want the ajax.php div to append to the #append div in index.php. There has to be a better way than altering the ajax.php and using echo:
ajax.php (with echo)
<?php
if(isset($_GET["one"])) {
echo "<div>". $_GET["one"] . " " . $_GET["two"] . "</div>";
}
?>
So, as ajax.php could be very large, is there a better solution than
just echoing data from ajax.php to index.php?
Now this can be done in many ways.. One of them is Following.. Try this:
Index.php file
<form method="get" id="calculator_form">
<input name="one" type="text" id="one">
<input name="two" type="text" id="two">
<input type="submit" name="submit">
</form>
<div class="result"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#calculator_form").on('submit', function(event){
event.preventDefault();
var one = $('#one').val(); // Taking value of input one
var two = $('#two').val(); // Taking value of input two
$.get( "ajax.php", { one:one, two:two }). done( function( data ) {
$('.result').html(data); // Printing result into result class div
});
});
});
</script>
ajax.php
<?php if(isset($_GET["one"])) { ?>
<div>
<?php echo $_GET["one"] . " " . $_GET["two"]; ?>
</div>
<?php } ?>
Use this,
$(document).ready(function() {
$(document).on('submit',"#calculator_form",function(event) {
event.preventDefault();
$.get(
'ajax.php',
function(ret_data){
$("#divtoappend").html(ret_data);
}
);
});
}) ;
The original syntax for $.get is,
$.get(
URL,
{
VAR_NAME1:VAL1,
VAR_NAME2:VAL2
},
function(response){
// your action after ajax complete
}
);
Typo: You have accidentally used $(document).read( instead of $(document).ready(! That will stop your code running.
Note: jQuery has a handy shortcut for the document ready handler:
$(function(){
// your code here
});
I'm not sure if I understand the question correctly, but here is what you can do: Assign some ID or at least the css Class name to the target div and paint the stuff you are getting from AJAX response something like below.
$(document).ready(function() {
$("#calculator_form").submit(function(event) {
event.preventDefault();
$.ajax({
url: "Ajax_URL",
success: function(result) {
$("#targetDiv").html(result.one + " " + result.two); //assuming you have assigned ID to the target div.
}
});
})
})
I wrote a piece of code, when the user click on submit button it send a string to PHP and then my code will run a Mysql query (based on the submitted string) and then using file_put_content it will upload the mysqli_fetch_array result to the file.
All I want to do is without refreshing the page it submit the value to php form and run the code then show Download From Here to the user.
How should I do that using javascript or jQuery ?
if(#$_POST['submit']) {
if (#$_POST['export']) {
$form = $_POST['export'];
echo $form;
$con1 = mysqli_connect("localhost", "root", "", "test_pr");
$sql2 = "SELECT email FROM `my_data` WHERE email LIKE '%$form%'";
$result2 = mysqli_query($con1, $sql2);
$rows = array();
while ($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
$rows[] = $row['email'] . PHP_EOL;
}
$nn = implode("", $rows);
var_dump($rows);
echo $nn . PHP_EOL;
$file = fopen("export.csv", "w");
file_put_contents("export.csv", $nn);
fclose($file);
}
}
?>
<html>
<form enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method=post>
<input name="export" type="text" value="example" /> Export Address<br/>
<input name="submit" type="submit" value="submit" />
Download From Here
</form>
</html>
Assuming you know how to include jquery, you would first bind a submit handler to the submit button, (I've added an id to make it easier) and prevent the default submit action. Then add an AJAX post request to the handler. This will post to your php file. Have that file echo out your link, then have the ajax callback function append it to the desired element. Something like this:
<form enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" id="form1" //Add an id to handle with >
<input name="export" type="text" value="example" /> Export Address<br/>
<input name="submit" type="submit" value="submit" />
Download From Here
</form>
<script>
$("#form1").submit(function (event) {
event.preventDefault();
$.post("//path of your php file here",{inputText: $("input[type='text']")},function (returnedString) {
$("#whereToPutReturnedString").append(returnedString);
});
});
</script>
Also, if you want to just show the link when the button is clicked, do the following:
<script>
$("input[type='submit']").submit(function () {
$("#idOfElementToPlaceLink").append("Your anchor text");
});
</script>
or you could just have it hidden with css or jquery and do $("#theId").show();
If you need more help, just holler!
everybody.
I have the following situation:
I have:
http://example.com/ and http://example.com/new
In example.com, I have some forms that I load in example.com/new domain with fancybox iframe.
My form, basically shows some fields for the user to enter his pessoal data, like name, phone and etc... After he submit that, I show some user agreement terms that comes from database and a checkbox for the user to say that he agree with the terms.
After he check and submit, I want to alert some sucess message and the fancybox modal/iframe to close and thats it.
In the form page, i've loaded jquery, and bootstrap. So, when the user agree, I print:
<?php
echo "
<script>
alert('Some success message!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
?>
I have three forms, in one, works, in the other two, i get:
Error: Permission denied to access property '$'
The only difference between the form that works and the other two, is that in the form that works, i don't have the agreement terms coming from database, only the checkbox.
I could put my entire code here, but would be a giant question. But if you guys need, I can update.
Sorry for my english and forgive-me if I was not clear.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<?php
/* Connect with DB */
require_once('require/conectar.php');
if(!empty($_POST))
foreach($_POST as $k => $v)
$$k = $v;
?>
<script type="text/javascript" src="http://example.com/new/assets/js/jquery.js"></script>
</head>
<body>
<?php if(!isset($agree) and !isset($next)): ?>
<h1>The form</h1>
<form method="post" action="">
<label>Your name:</label>
<input type="text" name="name">
<br>
<label>Your email:</label>
<input type="text" name="email">
<br>
<input type="submit" name="next">
</form>
<?php
else:
$error = (!isset($name)) ? true : false;
$error = (!isset($name)) ? true : false;
if($error)
{
echo '<script>You must fill all fields before submit.</script>';
exit;
}
$qrr = mysql_query("SELECT * FROM `terms`");
$terms = mysql_fetch_object($qrr);
?>
<h1>Terms:</h1>
<?php echo $terms->content; ?>
<form method="post" action="">
<input type="hidden" value="<?php echo $name; ?>" name="name">
<input type="hidden" value="<?php echo $email; ?>" name="email">
<input type="checkbox" value="1" name="accept"> I agree.
<input type="submit" name="agree">
</form>
<?php
endif;
if(isset($agree))
{
/*
Here i mail me the user data.
*/
echo "
<script>
alert('Soliciação Realizada com sucesso!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
}else
{
echo "<script>alert('You need to agree with the terms to proceed.');</script>";
}
?>
</body>
</html>
This is a browser security thing. While there's a few ways around it, the best one is probably to use the postMessage API.
On your example.com parent page, add some code like this:
function handleMessageFromiFrame(event) {
alert('Some success message: ' + event.data);
//$.fancybox.close();
}
window.addEventListener("message", handleMessageFromiFrame, false);
And, then on your child example.com/new iframe, add code like this:
var parentOrigin = "*"; // set to http://example.com/ or whatever for added security.
function sendMessageToParent(){
parent.postMessage("button clicked", parentOrigin);
}
$('#submit-btn').click(sendMessageToParent);
Here's an example of it in action:
Parent example.com page: http://jsbin.com/hiqoyevici/1/edit?html,js,output
Child example.com/new iframe: http://jsbin.com/goferunudo/1/edit?html,js,output
When you click the button in the child page, it uses postMessage to notify the parent. Then the parent listens for the message and does whatever action you want.
In my app I have to provide a 'save as image' button. I want to save the HTML rendered on my webpage as an image in JavaScript. It is a webapp and will be used in browsers of desktop/tablet/mobile phones. How to save rendered HTML as an image?
Check out html2canvas. A javascript framework that renders the page content on a canvas element. Saving the canvas as an image is as easy as:
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');
source
Using http://html2canvas.hertzen.com/
index.php
<style>.wrap{background:white;padding:0 0 16px 0;width:1500px;}.colour{width:1500px;position:relative;height:1400px;}p.footer{text-align:center;font-family:arial;line-height:1;font-size:28px;color:#333;}.wrap img{height:389px;width:389px;position:absolute;bottom:0;right:0;left:0;top:0;margin:auto;}p.invert{position:absolute;top:300px;left:0;right:0;text-align:center;display:block;font-family:arial;font-size:48px;padding:0 40px;filter:invert(0%);}p.inverted{-webkit-filter: invert(100%);filter:invert(100%);}</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/html2canvas.js"></script>
<script type="text/javascript" src="js/jquery.plugin.html2canvas.js"></script>
<?php // Open our CSV File
$colours = fopen('colours.csv', 'r');
// Reset Count
$i=0;
// Loop Through the Colours
while (($colour = fgetcsv($colours)) !== FALSE){
// Get the First Item and display some HTML
if($i==0){ ?>
<div id="target" class="wrap">
<div class="colour" style="background:<?php echo $colour[0]; ?>">
<img src="paragon2.png" alt="Image" />
<p class="invert inverted" style="filter:invert(100%);"><?php echo $colour[1]; ?></p>
</div>
<p class="footer"><?php echo $colour[1]; ?></p>
</div>
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
<input type="hidden" name="filename" id="filename" value="<?php echo $colour[0].".png"; ?>" />
</form>
<?php } // Count
$i++;
} // Loop
// Close the CSV File
fclose($colours); ?>
<script type="text/javascript">
$(window).load(function () {
$('#target').html2canvas({
onrendered: function (canvas) {
$('#img_val').val(canvas.toDataURL("image/png"));
document.getElementById("myForm").submit();
}
});
});
</script>
save.php
<?php // Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
$filename=$_POST['filename'];
// Decode the string
$unencodedData=base64_decode($filteredData);
// Save the image
file_put_contents("IMG2/".$filename, $unencodedData);
// Open the CSV File
$file = fopen('colours.csv', 'r');
// Loop through the colours
while (($line = fgetcsv($file)) !== FALSE) {
// Store every line in an array
$data[] = $line;
}
// Remove the first element from the stored array
array_shift($data);
// Write remaining lines to file
foreach ($data as $fields){
fputcsv($file, $fields);
}
// Close the File
fclose($file);
// Redirect and start again!
header( 'Location:/' ) ; ?>
Your question is very incomplete. First, is that a mobile or desktop app? In both cases, the solution to your problem will strongly depend on the HTML engine that renders the pages: Webkit, Geko/Firefox, Trident/IE for example have their own method to produce the view that you want to save as an image.
Anyway, you could start looking at how this Firefox plugin works: https://addons.mozilla.org/it/firefox/addon/pagesaver/
It should do what you want to implement, look for its source code.