I'm currently struggling because I want to load the same page submited by PHP. To make this more clear, it's a comment section, where after people submit their message I would like to retrieve the same information PLUS the new one.
I'm having problems because I'm not doing this by AJAX.
So, the index.php has the following:
/* Before HTML tag */
if(Cookie::Exists('comment')){
$data = unserialize(stripslashes(Cookie::Get('comment')));
if($data['status'] == 1){
$page = "<script type='text/javascript'>set_product_id('" . $data['id'] . "')</script>";
}
Cookie::Delete('comment', time() - 3600);
}
/* Further ahead.. (inside body) */
<form method="POST" action="insert_info.php" data-ajax="false">
<input type="hidden" id="product_id" name="product_id"/>
<input type="text" id="name_" name="name_" required="required"/>
<input type="text" id="comment" name="comment" required="required"/>
</form>
/* After body */
<script type="text/javascript">
$(document).on("pagebeforeshow", "#page-comments", function() {
$(function(){
get_comments(objs.product_id);
});
});
var objs = {
product_id : ''
}
function set_product_id(id){
objs.product_id = id;
$.mobile.changePage('#page-comments', {role: 'dialog'});
}
</script>
/* After the HTML tag */
<?php echo $page; ?>
I do receive the correct ID, etc, also it works perfectly before submiting the comment. The page loads the content without any problem, etc.
insert_info.php
new_comment($host, $user, $pass, $db);
$arr = array("status" => 1, "id" => $_POST['product_id']);
Cookie::set('comment', serialize($arr), time()+60);
header("Location: ../index.php");
exit();
When I perform this operation, I do receive the following erro on google chrome console:
Uncaught TypeError: Cannot call method 'trigger' of undefined
Poiting to the line:
function set_product_id(id){
objs.product_id = id;
$.mobile.changePage('#page-comments', {role: 'dialog'});
}
What am I missing? Thanks.
EDIT: changing the set_product_id() function, to this:
$('#page-main').on('pagecreate', function(event) {
$.mobile.changePage('#page-comments', {role: 'dialog'});
});
The page of comments appears and disappears again. But if I remove the "dialog", the page stays and works correctly. But I need that to be on dialog.
Your $.mobile.changePage() needs to contain a url..
So this:
$.mobile.changePage('#page-comments', {role: 'dialog'});
Should be something like this:
$.mobile.changePage('../index.php', {role: 'dialog'});
Related
I have the following button:
<input type="submit" name="kudos_button" value="★ Give kudos"/>'
And for testing purpose, I made a PHP script like this after the </html>:
<?php
if(isset($_POST['kudos_button'])){
$message = "Pressed";
echo "<script type='text/javascript'>alert('$message');</script>";
//and then execute a sql query here
}
?>
It all works fine, when pressing the kudos_button the message shows up. But the problem is that when the user refreshes the page, the message shows up again. And I get the following message:
The page that you're looking for used information that you entered.
Returning to that page might cause any action you took to be repeated.
Do you want to continue?
Any tips how I can avoid this, so the button does not press again when refreshing?
If you don't want to navigate to a new page, then you can't use a regular form submission.
Make the HTTP request with JavaScript instead.
e.g.
const form = document.querySelector("form");
const responseHandler = response => response.json();
const dataHandler = data => {
alert(data.message);
};
const submitHandler = event => {
event.preventDefault()
const data = new FormData(form);
const url = "/path/to/dedicated/webservice/that/returns/json";
fetch(url, { method: "POST", body: data }).then(responseHandler).then(dataHandler);
};
form.addEventListener("submit", submitHandler);
MDN has a guide on using fetch.
Then your server-side code would look something like:
<?php
// Execute a sql query here
header("Content-Type: application/json");
$message = "Pressed";
echo json_encode( [ message => $message ] );
Here is my solution:
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<input type="submit" name="kudos_button" value="★ Give kudos"/>
</form>
<?php
if(isset($_POST['kudos_button'])){
$message = "Pressed";
echo "<script type='text/javascript'>alert('$message');</script>";
//and then execute a sql query here
}
?>
Should be worke fine.
But you should know that PHP works regardless of the alert. Either way, your SQL statement will be executed after the button is pressed.
JavaScript is a Client Based Script and PHP a Server Based Script two different things.
--- EDIT ---
I builded a Function Based PHP Script which is calling the alert and feel for 5 seconds to sleep so the alert can shown up.
Here is my finished solution:
<form name="form1" method="POST" action="./" >
<input type="submit" name="kudos_button" value="★ Give kudos"/>
</form>
<?php
if(isset($_POST['kudos_button'])){
session_start();
$_SESSION["Button_onClick"] = 1;
$message = "Pressed";
if ($_SESSION["Button_onClick"] == 1) {
Button_onClick();
$_SESSION["Button_onClick"] = 0;
if ($_SESSION["Button_onClick"] == 0) {
BackLoop();
}
}
}
Function Button_onClick(){
$message = "Pressed";
echo ("
<script type='text/javascript'>
alert('$message');
</script>
");
SQL_Statement();
}
Function SQL_Statement() {
//and then execute a sql query here
}
Function BackLoop() {
session_destroy();
echo("
<script>
setTimeout(function () {
//Redirect with JavaScript
window.location.href= './';
}, 5000);
</script>
");
}
?>
Just in case for that someone have questions. I added the setTimeout function so I could see the changes on the website. If you don't want any infos after the alert (user case), you can delete the function. You only need window.location.href= './';.
I am making a news feed something like Facebook and other social media platform. For this, I am making a commenting section for each post on the page. I am trying to make the commenting section live (real time), so that when a comment is posted, the page does not refresh.
I know that the commenting system works because I did a test without real time feature (without the use of any form of javascript code).
The following is my code in brief....i only posted what I believe is necessary based on my issue.
function getposts ()
{
global $con;
$getposts = "SELECT * FROM posts";
if ($result = $con->query($getposts)) {
while ($row1 = $result->fetch_assoc()) {
$postid = $row1['post_id'];
?>
<form action='comments_ins.php' method='post' id='reply'>
<input type="hidden" value="<?php echo $postid;?>"
name="postid"/>
<textarea name="comment" id="comment" class="cmt_form"
placeholder="Type a commmment here..."></textarea>
<input type='submit' name='reply' value='Comment'/>
</form>
<?php
}
}
}
?>
Also, the above script i stored in a file given a name of functions. File is php file.
The following code is stored in a different file that is named as home where the functions file is included:
<?php include("functions.php"); ?>
<?php getposts ();?>
So, as indicated earlier, the above code works well. Now, I have slightly altered the code to make attempts to have the comment system be real time.
The following is the altered code:
function getposts ()
{
global $con;
$getposts = "SELECT * FROM posts";
if ($result = $con->query($getposts)) {
while ($row1 = $result->fetch_assoc()) {
$postid = $row1['post_id'];
?>
<form method='post' id='reply'>
<input type="hidden" value="<?php echo $postid;?>"
name="postid" id="postid" />
<textarea name="comment" id="comment" class="cmt_form"
placeholder="Type a commmment here..."></textarea>
<input type='submit' name='reply' value='Comment'/>
</form>
<?php
}
}
}
?>
//in addition to the java to make it real time
<script type="text/javascript">
$(document).ready(function() {
$(".cmt_form").keypress(function(evt) {
if(evt.which == 13) {
var postid = $("#postid").val();
var body = $("#comment").val();
$.post("comments_ins.php", { postid: postid, comment: body},
function(data) {
$('.log').html(data);
$('#reply')[0].reset();
});
}
});
});
</script>
The above java I included in the same functions.php file but outside of the php tags, not being in any loops. The home file is just the same..no changes.
Finally, the following code is the php file that inserts the comment into the database. File name as seen on previous codes: comments_ins.php
$comment1 = ($_POST['comment']);
$post_id = $_POST['postid'];
global $userId;
$insert1 = "insert into comments (post_id,user_id,comment,date) values
('$post_id','$userId','$comment1',NOW())";
$run1 = mysqli_query($con,$insert1);
The above code works to an extent only:
it's not posting the correct postid value to the database. It's only posting postid 1 even though i commented on another post with a different id number.
Also, it's not inputting the comment into the comment field in the database. I see an empty space..no text.
Finally, the output is some crazy output after posting the comment: some strange numbers and some nonsense.
What have i done wrong?
Please help
I am working on a webpage that takes HTML form input, processes it on a loop using PHP, then displays the PHP echo output in a div using jQuery, then TTS speaks a message using ResponsiveVoiceJS.
The problem that is visible right now is that, upon loading of the page, the TTS starts speaking the webpage file name and some random PHP on a loop, then displays the form twice.
It shouldn't do any of that!
Since I am not sure which part of the code is causing the issue, here is the code in its entirety:
<html>
<head>
</head>
<body>
<form action="<?php
echo $_SERVER['PHP_SELF'];
?>" method="post">
What is your URL? <input type="text" name="pastedurl"><br>
What is your minimum interval? <input type="text" name="interval"><br>
<input type ="submit">
</form>
<?php
set_time_limit(18000);
if (isset($_POST['submit']))
{
// echo "stopped here";
// die; //THIS DOESN'T WORK EITHER
$pastedlink = $_POST['pastedurl'];
$pastedlink2 = $_POST['pastedurl'];
$rate = $_POST['interval'];
parse_url($_POST['pastedurl'], PHP_URL_HOST);
if (parse_url($_POST['pastedurl'], PHP_URL_HOST) == 'www.instructables.com')
{
for ($z = 0; $z < 2880; $z++)
{
$tutorial_json = file_get_contents($pastedlink);
$tutorial_array = json_decode($tutorial_json, true);
$oldviews = $tutorial_array['views'];
sleep(30);
$tutorial_json2 = file_get_contents($pastedlink);
$tutorial_array2 = json_decode($tutorial_json2, true);
$currentviews = $tutorial_array2['views'];
$viewcount1 = (int) $oldviews;
$viewcount2 = (int) $currentviews;
$change = $viewcount2;
$change -= $viewcount1;
$rateasint = (int) $rate;
if ($change >= $rateasint)
{
$sayit = "Alert! Your Tutorial has gained " . $change . " more views";
echo $sayit;
}
}
}
else
{
exit("Error: URL submitted was not from www.instructables.com");
}
}
?>
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script>
$(document).ready(function(readyEvent) {
speakInnerHTML();
});
function speakInnerHTML() {
var speek = document.getElementById("load_updates");
responsiveVoice.speak(speek.innerHTML);
}
</script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_updates').load('<?php
echo $_SERVER['PHP_SELF'];
?>',speakInnerHTML).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<div id="load_updates"> </div>
</body>
</html>
Sorry about the poor formatting, I am a noob and don't know the methods of formatting these programming languages!
Here is a video of the error in action:
youtube
1.
die; //THIS DOESN'T WORK EITHER
die() is a function, and despite the wonders of echo, all functions are called with parentheses.
2.
isset($_POST['submit'])
This doesn't work because there are variables with the name submit.
To fix that, add the name attribute to your submit control, like this:
<input type="submit" name="submit">
3. You are loading the page itself with jQuery, even though it contains... well... itself. It's going to recursively fill the page with its own instances every 10000ms. And every one of that instance is going to do that too. You need to query the page with the data from the form, not just load it. And add a conditional so that if there is $_POST data, the page does not display all the HTML.
i have a form like this (already add jquery latest)
echo '<form name="chat" id="chat" action="/pages/guicsdl.php" method="post">';
echo bbcode::auto_bb('chat', 'text');
echo '<textarea rows="3" name="text" id="text"></textarea><br/>';
echo '<input type="hidden" name="trave" value="'.$trave.'" /><input type="submit" name="submit" value="Gửi" /></form>';
and the js
$(document).ready(function() {
$("chat").submit(function(){
$.post('/pages/guicsdl.php', $("#chat").serialize() );
});
});
and the file guicsdl.php
if(isset($_POST['submit'])) {
$noidung = functions::check($_POST['text']);
mysql_query("INSERT INTO `status` SET `user_id`='".$user_id."', `text`='".$noidung."', `time`='".time()."'");
mysql_query("UPDATE `users` SET `tongchat`= tongchat+1 WHERE id = '".$user_id."' ");
$trave = isset($_POST['trave']) ? base64_decode($_POST['trave']) : '';
header("Location: $trave");
}
i only want when i submit the form, the page doesn't refresh, the data insert to database. can any one help me fix? pls, and thanks. sorry for bad english.
You have to add return false; so that the browser 'understands' that it should not submit the form directly.
$(document).ready(function(){
$("#chat").submit(function(){
$.post('/pages/guicsdl.php', $("#chat").serialize() );
return false;
});
});
Another way (which I myself prefer) is to tell the event to not do it's default behavior.
$(document).ready(function(){
$("#chat").submit(function(ev){ // note the extra parameter
ev.preventDefault();
$.post('/pages/guicsdl.php', $("#chat").serialize() );
});
});
Wilmer also noticed that you had forgotten to put a # for the jQuery identifier when selecting the chat form.
Sorry, I consider myself as a real newbie around jQuery Mobile. I'm not good at all regarding JavaScript. Here's the thing. I want to build a jQuery Mobile site without using AJAX. Just want the nice design from jQuery Mobile and then use PHP to submit forms etc.
I tried to build a simple page that submit first and last name to a MySQL database. It will submit, tell the user that it's submitted and then the user can press [Page 2] to see all the results. Now I use if(isset()) to display the message and else to display the form. So, the user who enter the site will get the form, when press [Submit] he/she will get the message that first and last name was submitted. Then press the button [Page 2] to see all the first and last names.
PHP (index.php)
if(isset($_POST['send'])) {
$insert = $db->prepare("INSERT INTO name (fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $_POST['fname'],
":lname" => $_POST['lname']
);
$insert->execute($insert_array);
$db = NULL;
echo $_POST['fname'] . ' ' . $_POST['lname'] . ' was added!<br><br>';
}
else {
echo '
<form method="post" data-ajax="false">
First name:
<input type="text" name="fname"><br>
Last name:
<input type="text" name="lname"><br>
<input type="submit" name="send" value="Add">
</form><br>';
}
Page 2
PHP (page2.php):
$query = $db->query("SELECT * FROM name");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['fname'] . ' ' . $row['lname'] . '<br>';
}
$db = NULL;
echo 'Index';
Let's say I enter "Test" as first and last name. It will echo out "Test Test was added!". If I now press [Page 2] I will see that "Test Test" was added. BUT when I then press [Index] to go back I want it to display the form again, but the message "Test Test was added!" is displayed again instead of the form, why? I have to update the page to get the form. Now, if I enable data-ajax it's working with submitting and back-button. BUT then I have to press update at page2.php when I get there to see all the first and last names. Do I make myself understood what's the problem?
Sorry, really new at jQuery Mobile and I can't find the answer at Google. Everyone is using JavaScript to submit data. Is it possible this way or do I have to learn JavaScript to submit forms? Read somewhere that using buttons instead of submit-buttons affect it.
Thanks in advance! :)
I think you are looking to modify the DOM after the request? So post the form, add the user then display the results without having to click the button.
So on your ajax call use the done function to hide the form and show the results.
Take a look below and let me know if it helps.
EDIT: Added the .on click for the button. You may also want to look at adding a keypress checker to the inputs or an onsubmit on the form.
<div id="content">
<?php
if(isset($_POST['send'])) {
$insert = $db->prepare("INSERT INTO name (fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $_POST['fname'],
":lname" => $_POST['lname']
);
$insert->execute($insert_array);
$db = NULL;
echo $_POST['fname'] . ' ' . $_POST['lname'] . ' was added!<br><br>';
}
else {
echo '
<form method="post" data-ajax="false" id="contentForm">
First name:
<input type="text" name="fname"><br>
Last name:
<input type="text" name="lname"><br>
<input type="submit" name="send" value="Add" id="sendButton">
</form><br>';
}
?>
</div>
<script type='text/javascript'>
<!-- https://api.jquery.com/jQuery.ajax/ -->
$('#sendButton').on("click", function(){
$.ajax({
type: "POST",
url: "page2.php",
data: $('#contentForm').serialize()
})
.done(function( msg ) {
$('#content').html( msg );
});
});
</script>