I'm creating a browser RPG game. I want to allow a user to save their current stats by updating the mysql db without having to reload the page... So I thought jquery could help.
The user will not be adding their own stats. The stats are generated through user actions, such as solving a challenge. I want the user to be able to save those updated stats to the database whenever they would like.
The issues are:
the jQuery is outputting the echo "saved..." . $stats . ", " . $stats2; before I click the Save button.
When I click save, the database field isn't being updated.
I'm wondering why this isn't working. When I click save, the stats fields shouldn't be 0, but should be the stats that are shown- 11. The database fields should also be updated.
For testing purposes, I've just created js variable var stats that is updated when the arrow keys are pressed.
I call the function updateHUD() to do $('#stats').html(stats); which updates the HTML.
function updateHUD() {
$('#stats').html(stats);
}
Then updateHUD is called after arrow key is pressed.
HTML
<div class="span12">
<button onclick="saveData(stats)" name="input" value="">Save Data</button>
<br /><span id="output"></span><br />
<ul>
<li><b>Stats 1:</b> <span id="stats"></span> </li>
</ul>
</div>
jQuery
//Pass saved data to store in DB
$(document).ready(function() {
saveData();
});
function saveData() {
$.get("php/CRUD.php", {"_input" : $('input[name=input]').val()},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
PHP
<?php
//store all player data in array and save to/update db
include 'DbConnect.php';
session_start();
$stats = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$formvars = array();
array_push($formvars, $stats);
echo $stats;
echo $_SESSION['username'];
$qry = 'UPDATE users SET stats="'.$stats.'" WHERE username="' . $_SESSION['username'] . '"';
$mysqli->query($qry) or die(mysqli_error($mysqli));
echo "saved..." . $stats;
mysqli_close($mysqli);
?>
Output
saved...0 //this should be 11
Stats 1: 11
You do a
$('input[name=input]').val()
but you have named the submit button "input" instead of adding a input box with this name.
But the question is unclear anyways.
You want to give a user the permission to update his stat with the value that he wants? You should update the question to make it more clear since it does not make much sense at the moment.
First your selector where you are getting your data from is incorrect. You need to either change your html...
<button name="input"></button>
to an...
<input type="button" name="input" />
or change your jQuery selector...
$('input[name=input]')
to select the correct element
$('button[name=input]')
Second you need to make sure your button's 'value=""' actually has data in it when the ajax function is being called.
<button onclick="saveData(stats)" name="input" value="[Data Value Goes Here]">Save Data</button>
Finally the reason your jQuery is outputting before you click the the save button is because you are executing the function as soon as the document loads.
$(document).ready(function() {
saveData();
});
Try something more like this:
HTML
<button name="input" value="[data goes here]">Save Data</button>
JavaScript / jQuery
//Pass saved data to store in DB
$('button[name=input]').on('click', saveData);
function saveData() {
$.get("php/CRUD.php", {"_input" : $(this).val()},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
Also you can try using load:
//Pass saved data to store in DB
$(document).ready(function() {
saveData();
});
$.fn.saveData=function(){
$('#divforload').css('display','none');
$('#divforload').load("php/CRUD.php?stats="+$('#stats').val(),function(){$('#divforload').fadeIn();});
}
//Just call the function onClick...
//Need an input called 'stats'
});
Related
I am trying to pass the link's text as a value to the next page so I can use it to search the database for the item and retrieve the information related to the value .I have tried using the POST method but regardless the information is not passed. This is the code I tried .
<form action="DetailedMenu.php" method = "POST" action = "<?php $_PHP_SELF ?>">
<?php
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
echo str_repeat(' ', 4); ?>
<a href="DetailedMenu.php" ><?php echo $array[$i]["Food_Name"];?></a>
<?php echo " " .str_repeat('. ', 25). "€".$array[$i]["Food_Price"]."<br>"; ?>
<input type="hidden" name="name" value="<?php echo $array[$i]["Food_Name"];?>">
<?php
}
}
?>
</form>
You don't need the form.
The easiest way to do what you're trying to do....
In addition to including the text in the content of the link, include it as a query string parameter.
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
I would actually recommend something more like this. I obviously don't know the names of your fields, so I've just taken a guess...
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
You'll be able to access "FoodID" as a parameter within your PHP, just as you would if it had been submitted from a form.
You may be looking for AJAX. AJAX lets you send the form data to a back end PHP file (that can then insert data into a DB, and/or get data from the DB) without refreshing the page.
In fact, when you are using AJAX you don't even need to use a <form> structure -- simple DIVs work just fine. Then you don't need to use event.preventDefault() to suppress the built-in form refresh.
Just build a structure inside a DIV (input fields, labels, etc) and when the user is ready to submit, they can click an ordinary button:
<button id="btnSubmit">Submit</button>
jQuery:
$('#btnSubmit').click(function(){
var fn = $('#firstname').val();
var ln = $('#lastname').val();
$.ajax({
type: 'post',
url: 'ajax_receiver.php',
data: 'fn=' +fn+ '&ln=' +ln,
success: function(d){
if (d.length) alert(d);
}
});
});
ajax_receiver.php:
<?php
$fn = $_POST['fn'];
$ln = $_POST['ln'];
//Do your stuff
Check out this post and especially its examples. Copy them onto your own system and see how they work. It's pretty simple.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
html.php
how to call Delete($passid) function in button on Click.
<?php
function Delete($passid)
{
echo "Delete $passid";
}
?>
<button name="Delete" id="Delete" onclick="Delete($row['ID'])" >Delete</button>
I am assuming this is what you're after? - Assuming you're trying to edit the DOM using javascript
JS
function Delete(passid)
{
//Do something with passid variable
}
HTML
<button id="Delete" onclick="Delete(this.id)" >Delete</button>
(also removed name since you don't seem to be using it)
So when the button is clicked, it calls the javascript function "Delete" and passes the button's id to it (in this case "Delete")
If not, perhaps this? - Assuming you are trying to delete a row from a mysql database and you're sending the variable from your HTML to your php on the button's click
Assuming you have a database connection setup, and that there exists a table named 'table' that meets some 'condition' to get all rows matching this criteria's 'id' column value
connection setup should be in all php files that link to the database
(You can use the include function for this instead of writing it 100 times)
i.e. include("path/to/file/connection.php")
PHP populates HTML
<?php
$query = mysql_query("SELECT * FROM table WHERE condition");
while($row = mysql_fetch_array($query))
{
echo '<span>'.$row["id"].'</span>
<button class="Delete" value='.$row["id"].'>Delete</button>';
}
?>
JQuery
$(".Delete").click(function()
{
var id = $(this).attr("id");
$.ajax({
type:"POST",
url:"file.php",
data:{id:id}
});
});
PHP ---> file.php runs function
<?php
if(isset($_POST["id"]))
{
$id = $_POST["id"];
$query = mysql_query("DELETE FROM table WHERE id='$id'");
}
?>
This would delete the database table row where id is set to the id that we pass it from the HTML button's value.
So this function does the following:
Gets all ids from database table where the condition is met
Populates the HTML page with a span tag showing us the id of the element next to the button that will delete the same element
When a button is clicked, our jQuery click event captures it
jQuery function gets clicked button's id and sends it to the ajax function
Ajax function uses the post method to send the variable id to the document file.php
file.php checks to see whether or not the variable id that was sent through the post method actually exists
If the post variable id exists, it sets $id to it.
Query called to delete a table row in our database where id is equal to $id (our initial button's id value generated by the table itself)
You must use a form and submit button to POST data, then call this function with parameter from $_POST['passid'].
Use a AJAX post data and process same option 1
<form action="" method="post">
<input type="hidden" name="delID"> <?php echo $row['ID']; ?>
<input type="submit" value>
</form>
<?php
if($_POST)
{
$id=$_POST['delID'];
function delete($id)
{
echo $id;
}
}
?>
else use ajax --->
<input type="button" onclick="Delete($row['ID'])" name="delete" value="Log In" />
<script>
function Delete(e) {
alert(e);
$.ajax({
type: "POST",
url: "script.php",
data:{"delete":e},
success: function(data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
}
</script>
in php
if(isset($_POST))
{
$id=$_POST['delete'];
echo "Delete ".$id;
}
I want to be able to change the text of some pages. Using contenteditable would be perfect for me.
Problem is that I only know how to program in PHP. I have searched on the internet for hours trying to make it work, but I just don't understand the programming languages used to store the data enough to make it work.
This is how I would like it to work:
Admin hits a button 'edit'
div becomes editable.
When the admin is ready editing, he hits a button 'save'
The data is saved to a file or database (don't really know what would be the best option).
The edited content shows up when the page is opened.
This is all I have for now:
<div class="big_wrapper" contenteditable>
PAGE CONTENT
</div>
I know how to make the part with converting the div to an contenteditable div when the admin hits 'edit'.
My problem is that i really have no idea how to save the edited data.
I also don't know if it would be hard to retrieve the data from a file, depents on the way how the data is saved. If it is saved to a database I would have no problem retrieving it, but I don't know if that is possible and if that is the best option.
Thanks for your help,
Samuël
EDIT:
#gibberish, thank you so much for your super-quick reply!
I tried to make it work, but it doesn't work yet. I can not figure out what i'm doing wrong.
Here's my code:
over_ons.php:
<div class="big_wrapper" contenteditable>
PAGE CONTENT
</div>
<input type="button" value="Send Data" id="mybutt">
<script type="text/javascript">
$('#mybutt').click(function(){
var myTxt = $('.big_wrapper').html();
$.ajax({
type: 'post',
url: 'sent_data.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
</script>
sent_data.php:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
$tekst=$_POST['myTxt'];
$query="UPDATE paginas SET inhoud='" .$tekst. "' WHERE id='1'";
mysql_query($query);
?>
Thanks again for your great help!
Can you also help me to make the div editable only when the user hits a button?
SOLUTION:
It took me over 2 weeks to finally make everyting work. I had to learn javascript, jQuery and Ajax. But now it works flawlessly. I even added some extras for the fanciness :)
I would like to share how i did this if someone wants to do the same.
over_ons.php:
//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php
} ?>
<!--Editable DIV: -->
<div class='big_wrapper' id='editable'>
<?php
//Get eddited page content from the database
$query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
while($inhoud_test=mysql_fetch_array($query)){
$inhoud=$inhoud_test[0];
}
//Show content
echo $inhoud;
?>
</div>
<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
<div id='sidenote'>
<input type='button' value='Bewerken' id='sent_data' class='button' />
<div id="feedback" />
</div>
<?php }
As this is a pretty long and complicated file, I tried to translate most of my comments to english.
If you want to translate something that in't already translated, the original language is Dutch.
javascript.js:
//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Verstuur bewerkingen'){
return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});
//Make content editable
$('#sent_data').click(function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Bewerken'){
$('#sent_data').attr('value', 'Verstuur bewerkingen'); //change the name of the edit button
var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
$('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
}else if(value == 'Verstuur bewerkingen'){
var pagina = $('#pagina').val();
var editor = $('#editor').val();
var div_inhoud = $("#editable").html();
$.ajax({
type: 'POST',
url: 'sent_data.php',
data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
success: function(data){
Change the div back tot not editable, and change the button's name
$('#sent_data').attr('value', 'Bewerken'); //change the name of the edit button
var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div not editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
//Tell the user if the edditing was succesfully
$('#feedback').html(data);
setTimeout(function(){
var value = $('#sent_data').attr('value'); //look up the name of the edit button
if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
$('#feedback').text('');
}
}, 5000);
}
}).fail(function() {
//If there was an error, let the user know
$('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
});
}
});
And finally,
sent_data.php:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
//Look up witch page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);
$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";
}
if(mysql_query($query)){
echo "<p class='opvallend'>Successfully saves changes.</p>";
}else{
echo "<p class='opvallend'>Saving of changes failed.<BR>
Please try again.</p>";
}
?>
Use a client-side language, such as JavaScript (or best, jQuery), to manage whether the input boxes could be edited.
Use AJAX to grab the field data and fire it off to a PHP file, which would stick the data in your database.
Here is a very simplified example of using jQuery to manage enabling/disabling the input fields:
jsFiddle Demo
$('.editable').prop('disabled',true);
$('.editbutt').click(function(){
var num = $(this).attr('id').split('-')[1];
$('#edit-'+num).prop('disabled',false).focus();
});
$('.editable').blur(function(){
var myTxt = $(this).val();
$.ajax({
type: 'post',
url: 'some_php_file.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
PHP file: some_php_file.php
<?php
$myVar = $_POST['varname'];
$secondVar = $_POST['anothervar'];
//Now, do what you want with the data in the vars
Using AJAX is quite easy. I gave a very brief example of what it would look like. Don't look in the HTML or jQuery for the moreTxt variable -- I added that to show how you would add a second var of data to the ajax.
Here are some basic examples to bring you up to speed on ajax:
AJAX request callback using jQuery
There is no short path to learning jQuery or AJAX. Read the examples and experiment.
You can find some excellent, free jQuery tutorials here:
http://thenewboston.com
http://phpacademy.org
UPDATE EDIT:
To respond to your comment inquiry:
To send data from a DIV to a PHP file, first you need an event that triggers the code. As you mentioned, on an input field, this can be the blur() event, which triggers when you leave a field. On a <select>, it can be the change() event, which triggers when you choose a selection. But on a DIV... well, the user cannot interact with a div, right? The trigger must be something that the user does, such as clicking a button.
So, the user clicks a button -- you can get the content of the DIV using the .html() command. (On input boxes and select controls, you would use .val(), but on DIVs and table cells you must use .html(). Code would look like this:
How to send DIV content after a button clicked:
HTML:
<div class='big_wrapper' contenteditable>
PAGE CONTENT
</div>
<input id="mybutt" type="button" value="Send Data" />
jQuery:
$('#mybutt').click(function(){
var myTxt = $('.big_wrapper').html();
$.ajax({
type: 'post',
url: 'some_php_file.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
You could save the whole
page clientside with this:
<script>
function saveAs(filename, allHtml) {
allHtml = document.documentElement.outerHTML;
var blob = new Blob([allHtml], {type: 'text/csv'});
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
</script>
hth
I am making a exam portal in which i have option conducting exam/quiz. Now i have added 2 buttons namely Next and Previous . I wanted to fetch Question and its option on button Click.
My database has following structure: Question(qid,question,option1,option2,option3,option4,right_option)
What I am tryin to do:
<input id="first" type="button" value="NEXT" onClick = "show_next()">
<input id="second" type="button" value="PREV" onClick = "show_prev()">
<script>
function show_next()
{
<?php
$question_no; //my global php variable to keep track of question id
$question_no = $question_no + 1;
show_question($question_no); //php function which shows data according to question no
?>
}
function show_prev()
{
<?php
if($question_no>0)
{
$question_no = $question_no-1;
show_question();
}
else
{
?>
alert("Wrong Operation");
<?php
}
?>
}
</script>
I am new to php and javascript, please suggest the correct method and if possible coding snippet for my question
Use jQuery/AJAX.
All you have to do is manage Offset and Limit dynamically.
e.g.
lets consider you are showing 1 question at a time and its options.
your html file will be.
<input id="first" type="button" value="NEXT" onClick = "show_next()">
<input id="second" type="button" value="PREV" onClick = "show_prev()">
<input id="offset" type="hidden" value="0">
In your javascript file
function show_next()
{
var offset=$('#offset').val();
$.post('GetQuestion.php',{offset:offset},function(data){
$('#question_answer').html(data);
$('#offset').attr('value',offset+1);
})
}
function show_prev()
{
var offset=$('#offset').val();
$.post('GetQuestion.php',{offset:offset},function(data){
$('#question_answer').html(data);
$('#offset').attr('value',offset-1);
})
}
In your GetQuestion.php file you can access offset value using $_POST. All you have to do is use that value in your query.
mysql_query("SELECT * FROM questions LIMIT ".$_POST['offset'].",1");
echo your query result in php file so that it could be available to var data in javascript.
As far as i know, PHP is executed on the server and the JS is executed Client-Side, so you can't mix it.
You have to Options.
Load all Questions in different divs and hide them. Then you can show one by one with the next and the previous buttons.
Build the page with a parameter like this: http://myapp.com/question/1 And make the Next BUtton /question/2 The question page should now contain only 1 question.
Edit:
Here is a fiddle for the 1. method:
http://jsfiddle.net/zj7ts/
$('.question').hide()
$question_shown = $('.question').first().show();
$('.next').click(function(){
$('.question').hide()
$question_shown = $question_shown.next().show();
});
$('.prev').click(function(){
$('.question').hide()
$question_shown = $question_shown.prev().show();
});
I want to send a post from HTML that contains info about a certain form to a controller in code igniter. The I want the controller to process the info and loads a certain page inside a div. Here is my code. I think I'm supposed to use something like .html or something? I'm not quite sure, I dont understand it
The controller
function search_friend(){
//this function gets text from text field and searches for a user and returns all users similar to this dude
// $this->input->post($searchFriendForm);
// $this->input->post($searchFriendText);
$this->load->model('userProfile_m');
$people = $this->userProfile_m->get_user_by_name($this->input->post($searchFriendText));
$this->load->view('addFriendSearchResult',$people);
}
the form in html
<form method="post" action="" name="searchFriendForm" id="add-friend-search">
<input type="text"/ name="searchFriendText">
<input type="button" class="small green button" id="add-friend-button" />
</form>
the jquery function
$("#add-friend-button").click(function(){ //start click
$.post("<?php echo site_url('userProfile/search_friend'); ?>", $("#add-friend-search").serialize());
$("#insert-activity").load("<?php echo base_url().''?>system/application/views/addFriendSearchResult.php");
$("#add-friend-search").slideUp("slow",function(){});
}); //end click
Firstly, in your controller change this line like this (u need to pass the string name of the field here):
$people = $this->userProfile_m->get_user_by_name($this->input->post('searchFriendText'));
Next, change your jQuery to be like this:
$("#add-friend-button").click(function(){ //start click
$.post("<?php echo site_url('userProfile/search_friend'); ?>",
$("#add-friend-search").serialize(),
function(data){
$("#insert-activity").html(data);
});
$("#add-friend-search").slideUp("slow",function(){});
}); //end click
You cant call your view directly, and you don't need to. The post should return the data, which you can write out to your #insert-activity element.