jQuery Mobile submit with PHP without AJAX and JavaScript - javascript

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>

Related

An AutoSuggest that returns matches as HTML Form elements and not as JSON data

I have built a simple search tool for my Web App to search through my client database. It returns form submit buttons in a dropdown so that, when a selection is made, the selected clients ID is passed in a POST to the following page. The following page receives this POST and populates with all of the stored information about that client. This works the way I need it to for the most part, but I have a couple questions.
1) most autocompletes/autosuggests that I have seen examples of return JSON data as the results. Is using JSON inherently a smoother or safer process for this?
2) my search results (form buttons) display in a dropdown but are not navigable via TAB or ARROW keys. What is needed to add this accessibility? I tried to add TabIndex to the buttons but that did nothing.
I arrived at this particular solution for my need of a search function after failing miserably to understand some of the pre-packaged Autocomplete solutions out there. They seemed much more complex than what I needed for this Web App.
Here is what I am using.
HTML:
<div class="row">
<div class="col-12">
<input onKeyUp="myFunction()" type="text" id="searchterm" placeholder="Search for existing client">
<div class="searchResults" id="results"></div>
<script>document.getElementById("results").style.visibility='hidden';</script>
<script type="text/javascript" src="js/watchdog.js"></script>
</div>
</div>
JAVASCRIPT:
function myFunction() {
var input = document.getElementById("searchterm").value;
if (input && input.length >= 2) {
$.ajax({
type: "POST",
url: "searchengine.php",
data: {input : input},
success: function(data) {
if (data) {
document.getElementById("results").style.visibility='visible';
document.getElementById("results").innerHTML = data;
}
else {
document.getElementById("results").style.visibility='hidden';
}
}
});
}
else {
document.getElementById("results").style.visibility='hidden';
return false;
}
}
PHP:
<?php
include ('connect.php');
$input = trim($_POST['input']);
$input = htmlspecialchars($input);
$equiv = '%' . $input . '%';
// prepare stmt, bind param, execute
$stmt = $conn->prepare("SELECT client_id, firstname, lastname, city, state FROM client WHERE firstname LIKE ? OR lastname LIKE ?");
$stmt->bind_param("ss", $equiv, $equiv);
$stmt->execute();
$stmt->bind_result($client_id, $firstname, $lastname, $city, $state);
while ($stmt->fetch()) {
echo "
<form name=\"clientSearchResults\" action=\"client.php\" method=\"post\">
<input name=\"client_id\" value=\"$client_id\" type=\"hidden\">
<div class=\"wrapper\">
<input style=\"height: 25px;\" type=\"submit\" value=\"$firstname $lastname - $city, $state\"></input>
</div>
</form>
";
}
// close statement
$stmt->close();
include ('disconnect.php');
?>
Re: TAB key access to submit buttons.
Looking into this further I found the answer to the accessability issue here:
submit-button-not-focused-even-though-tabindex-is-properly-set
This seems to be an issue I encountered because of my laptop being a Mac.

Submit -> Execute PHP script -> Alert User -- while staying on same page

I have a page with two submit buttons using if ($_POST['action'] == 'Test SMS') to executed code for my "Test SMS" button. I need to execute code from a PHP script then give an alert box while not leaving the page.
index.html
<form action="updateUserConfig.php" method="post">
<input type='submit' name='action' value='Test SMS' class='btn-test'>
<input type="submit" name="action" value="Save" class="btn btn-primary">
</form>
updateUserConfig.php
if ($_POST['action'] == 'Test SMS') { //action for Test SMS Button
//grab ntid and phone from header
if(isset($_POST['ntid'])) $ntid = $_POST['ntid'];
if(isset($_POST['phone'])) $phone = $_POST['phone'];
//using the notify_sms_users funtion from send_notification.php
require 'send_notification.php';
notify_sms_users(array($ntid), "", 4);
//alert user that there message has been sent
$alert = "Your message has been sent to " . $phone;
echo '<script type="text/javascript">alert("'.$alert.'");';
echo '</script>';
header('Location: index.php');
} else {-----action for other submit button------}
I asked a similar question that was marked a duplicate at Alert after executing php script while not leaving current page but was able to come up with a solution so I wanted to share.
I was able to accomplish this by adding a URL query string in my header('location: index.php?text=success) function then using JS I was able to use an if statement to look for the query string and alert if so.
index.html
<form action="updateUserConfig.php" method="post">
<input type='submit' name='action' value='Test SMS' class='btn-test'>
<input type="submit" name="action" value="Save" class="btn btn-primary">
</form>
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("settings=success") > -1) {
alert("Your settings have been saved");
}
else if(window.location.href.indexOf("text=success") > -1) {
alert("A SMS has been sent!");
}
});
</script>
updateUserConfig.php
if ($_POST['action'] == 'Test SMS') { //action for Test SMS Button
//grab ntid and phone from header
if(isset($_POST['ntid'])) $ntid = $_POST['ntid'];
if(isset($_POST['phone'])) $phone = $_POST['phone'];
//using the notify_sms_users funtion from send_notification.php
require 'send_notification.php';
notify_sms_users(array($ntid), "", 4);
header('Location: index.php?text=success');
} else {-----action for other submit button------}
header('Location: index.php?settings=success');
The only downside to this solution is that I don't have easy access to my PHP $phone variable to tell the user what number the message was sent to.
AJAX is the method most suited to this job, because what you are trying to achieve is a frontend interaction. Php is a server side language.
AJAX will transmit form data to the backend php script. Once the the php script has handled the data on the server, it can return the data you require to the AJAX script. This is done sometimes using JSON, especially as you have multiple variables.
$formdata = array(
'ntid' => $_POST['ntid'],
'phone' => $_POST['phone']
);
return json_encode($formdata);
The returned JSON code will look something like:
{"ntid":"NT ID","phone":"Phone number"}
Tutorials similar to this are very useful:
[http://www.yourwebskills.com/ajaxintro.php][1]
I have found that taking a break from your main project and investing a little time in learning the mechanics behind what your trying to achieve, enables you to solve your problem faster.

Table form dynamically refresh with php and ajax

I have a page which has a form table. It displays select option when an option is selected the user clicks button and it runs updatephp.php which has query for updating. I need the select to be dynamically updated and display the success/error message like "updated" or "no results" on the screen how can I achieve this. Im not very good at ajax could someone guide me please.
displaytable.php
<form method="POST" action="choosecake.php">
<select id="bakeryid" name="bakeryid">
<option value="">Select</option>
<?php
$sql = "SELECT bakeryid, datefrom FROM cakes";
$sqlresult = $link->query($sql);
$sqllist = array();
if(mysqli_num_rows($sqlresult) > 0) {
while($row = mysqli_fetch_array($sqlresult))
{
echo "<option value=".$row['bakeryid'].">".$row['datefrom']."</option>";
}
$sqlencode = json_encode($sqllist);
echo $sqlencode;
} else {
echo 'No Results were found';
}
?>
</select>
<input type="hidden" value="<?php echo $bakeryid;?>" name="bakeryid"/>
<input type="submit" value="Submit" name="submit"/>
</form>
change your displaytable.php and generate an array of your cakes with id as key and the name as the value. Then echo the json encoded array which can be used directly in js.
Just to get a feeling, didn't test it.
$(document).ready(function() {
window.setTimeout(function() {
$.ajax({
url: "/displaytable.php"
}).done(function(data) {
var select = $('#selectId');
select.empty();
$.each(data, function(val, key) {
select.append($("<option></option>").attr("value", key).text(val);
});
});
}, 10000); // 10 seconds update interval
});
If your page must refresh (no ajax), use displaytable.php to handle the form submission. Then define a variable to hold your success or error message and put this variable where you want the message to display, like
if(!empty($success_message)) {
echo "<h2>$success_message</h2>";
}
When the form is submitted, simply assign a value to $success_message, and since the script handling the form submission is the same script which contains the form, the echo statement in the code above will display your message when the page reloads.

Form not posting variables/mySQL Query not searching corrently

I'm trying to create a player edit system for an admin section of a football website.
The process goes as follows:
Once a coach has logged in on 'coaches.php', they can then choose what coaching session they want to look at via dropdown, which then populates the 'player' dropdown (done via js below)
coaches.php form
<form id="form1" name="form1" method="post" action="coachplayer.php?id=' .$id. '">
<label>Activity :</label>
<select name="activity" class="activity">
<option selected="selected">--Select Activity Group--</option>
<?php
include('dbconnect.php');
$sql=mysql_query("select activity from coaches where username='$coach'");
while($row=mysql_fetch_array($sql))
{
$activity2=explode(",",$row["activity"]);
foreach ($activity2 as $activity)
echo '<option value="'.$activity.'">'.$activity.'</option>';
} ?>
</select> <br/><br/>
<label>Player :</label> <select name="username" class="username">
<option selected="selected">--Select Player--</option>
</select>
<input name="thisID" type="hidden" value="<?php echo $id; ?>" />
<input type="submit" name="button" id="button" value="Log In" />
</form>
coaches.php js function
<script type="text/javascript">
$(document).ready(function()
{
$(".activity").change(function()
{
var activity=$(this).val();
var dataString = 'activity='+ activity;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".username").html(html);
}
});
});
});
</script>
<style>
label
{
font-weight:bold;
padding:10px;
}
</style>
As the js above shows, the player list is handled via a separate page with a query on it as follows:
<?php
if($_POST['activity'])
{
$activity=$_POST['activity'];
$sql=mysql_query("SELECT id, username FROM stats WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$username=$row['username'];
$activity=$row['activity'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
}
?>
Once all of this is done, the coach submits the form, taking them to coachplayer.php. This is where the problem begins.
coachplayer.php is a template page, with empty fields filled with echo's, to echo the player details where necessary. A query runs to get the id of the selected player, bring up their details and fill the page. Instead, however, it echos what usually comes up if the query cannot find a matching result via $playerCount as shown below, saying "Player doesn't exist".
coachplayer.php SQL query
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
$targetU = preg_replace('#[^0-9]#i', '', $_GET['id']);
// Use this var to check to see if this ID exists, if yes then get the player
// details, if no then exit this script and give message why
$sql = mysql_query("SELECT * FROM stats WHERE id='$targetU' LIMIT 1");
$playerCount = mysql_num_rows($sql); // count the output amount
if ($playerCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$username = $row["username"];
$position = $row["position"];
$activity = $row["activity"];
$agegroup = $row["agegroup"];
$coach = $row["coach"];
$goals = $row["goals"];
$assists = $row["assists"];
$cleans = $row["cleans"];
$motm = $row["motm"];
$attend = $row["attend"];
}
} else {
echo "Player doesn't exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
As I'm sure you can tell, I'm not too great of a coder, so it's very possible that it's a simply var that needs changing but any ideas where I have gone wrong will be much appreciated.
Thank you in advance.
You are using a form with post method. And the action URL seems quite different
<form id="form1" name="form1" method="post" action="coachplayer.php?id=' .$id. '">
Change it to
<form id="form1" name="form1" method="post" action="coachplayer.php">
and in coachplayer.php. Use
isset($_POST['thisID']
Ok, I admit this is not an answer to your question BUT, to be honest there is no such thing as 'your question' - there are contents of four files each of them with their own problems, and an implicit request to grock all of those 4 files and tell you what does not work and how it should be made to work.
Having said that:
Divide and conquer. Make sure your first script does exactly what needs to be done. Then second, then 3rd and only then 4th.
Use tools: For javascript - Dev Tools or Firebug. For queries - MySQL Workbench
When testing JS use console (here you can try out your js code interactively.
) and source tabs - there you can set breakpoints and follow execution line by line. Look at network tab - there you can see request (headers) and responses.
When debugging PHP comment out all your code and use var_dump every step of the way. I use PHP Storm so that i can debug PHP line by line real time.
And better ask questions that can be described with the least lines of code
PS. You can simulate GET requests by typing url in browser - that way you know whether your server side works or not without relying on unreliable JS
Just a Quick look, but your sql Statement seems wrong. Your sql query will search for the Player with the id '$targetU'. Make sure to enter the variable correctly

can anyone fix this. jQuery $.post

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.

Categories