Sending value from jQuery autocomplete back to PHP - javascript

I got a bit stuck and would appreciate any help.
Intro
In short (I hope): I am creating a website (only local at the moment) which has stored city names and some important/interesting values (for example population, time, currency). I use a MySQL database to store the data. Three of these tables relevant to this case: Table 1. stores cities as values. table 2. stores the "title" of the relevant data (population, current time, currency). The third table the actual value (100 000, 12:30, Euro). I am using php to communicate between the database and the html.
Desired outcome:
A search box is used to find a city of interest. The web page prints the selected city in the top of the page and some relevant data of the city inside two divs.
Problem
How can I get the value of autocomplete back to php in order to make three different SQL queries on the same page depending on the selection?
I read that you could use a php -file as the source of the autocomplete (now on an array, values stored from the database) and somehow autocomplete could retrieve other data based on the users' selection. But will it work if I am not using any other jquery-ui component? How would it actually be written in code?
EDIT
I read shortly about:
Sending it as POST, but can it be done in the same page?
Use sessions
Use AJAX
What is the easiest/best to understand/use?
Any other suggestions?/help?/tips?
At this point my stack has overflown.
Summary
What is a easy to learn and correct way to handle communication from javascript/jQuery back to PHP while staying on the same page?
Code
<?php
require_once "dataPDO.php"; //All of the sql-queries
$databaseHandler = new dataPDO();
$list=$databaseHandler->allCities(); //a list of all the cities
?>
<!doctype html>
<html>
<head>
<title>Choose a city</title>
<meta charset="utf-8">
<!-- needed by autocomplete -->
<link rel="stylesheet" href="js/jquery.ui.all.css">
<script src="js/jquery-1.10.2.js"></script>
<script src="js/jquery.ui.core.js"></script>
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.ui.position.js"></script>
<script src="js/jquery.ui.menu.js"></script>
<script src="js/jquery.ui.autocomplete.js"></script>
<script>
$(function() {
var names=<?php echo json_encode($list); ?>;
$("#cities").autocomplete({
source: names, minLength: 2
});
});
$(document).ready(function () {
$('#cities').on('autocompletechange change', function () {
var data = $('#city').html('Chosen city: ' + this.value);
}).change();
});
</script>
</head>
<body>
<div>
<div class="ui-widget">
<label for="cities">Search for a city:</label>
<input id="cities">
<div id="city"></div>
</div>
</div>
<div>
<section class="left">
<?php
try {
$databaseHandler->information(1);//(hardcoded) information belonging to the first city
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
</section>
<section class="right">
<?php
try {
$databaseHandler->values(1);//(hardcoded) information values belonging to the first city
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
</section>
</div>
</body>

You certainly do not need to use JQuery or another framework, however, it sure does make it a lot easier to do these types of things. RyanS' comment about using JQuery makes a lot of sense for this reason. You'd just be reinventing the wheel.
Basically, the process will be to make a PHP file that takes some parameters through GET or POST and then uses those parameters to display the data. Once you have that file in place, you can use Javascript to trigger an event to call that PHP script. For instance, you can say when someone selects a value from a drop down menu, then pass these parameters to the PHP script and display the output from there into a div that you have on the same page as the drop down menu.

Related

Jquery and AJAX script to run a PHP script in the background to avoid any refreshing

I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?

Can't get post data from jQuery UI sortable (sent to the same file)

I have a little quiz written in php with questions of two types : single choice answer via radio buttons and multiple choice answers via checkboxes. The code run in a single file ("quiz.php") that handles the display of the questions as well as the treatment of the answers.
Everything was working smoothly until I had to add a third type for "sortable list" of answers --where people have to re-order a list of choices.
After some research, I've found what I think is the answer : the "sortable" interaction of jQuery UI. Simple, straightforward and easy to implement… even if I can't seem to make it work !
My problem is that if I know a little bit of PHP/MySql, I know very little of Javascript and certainly not know enough to write or debug it properly.
Here's the code, starting with all the php for the display of questions and the process of the answers :
// File quiz.php
<?php session_start();
// if the form has just been submitted, handle the answers
if (isset($_POST['submit'])) {
// Do something, on a case by case basis :
switch ($_SESSION['questionType']) {
case 1 : // for radio buttons
// some code to process and save the answer to the database
break ;
case 2 : // for checkboxes
// some code to process and save the answer to the database
break ;
case 3 : // for sortable lists
// some code to process and save the answer to the database
break ;
}
}
// Here, get the elements to show from the DB, including
// the question type for the switch below
// questionType = 1 for single choice answer
// questionType = 2 for multiple choice answer
// questionType = 3 for sortable choice answer
?>
Next, the html to display the questions :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Quiz</title>
<link rel="stylesheet" href=./quiz.css">
<script src="./js/jquery-1.11.3.min.js"></script>
<script src="./js/jquery-ui.min.js"></script>
</head>
<body>
<?php // A bunch of code to echo the question ?>
<form action="quiz.php" method="POST">
<?php // A switch to adapt the display to the type of questions :
switch ($_SESSION['questionType']) {
case 1 : // for single choice answer
// A bunch of code to echo the possible choices w/ radio buttons
break ;
case 2 : // for multiple choice answer
// A bunch of code to echo the possible choices w/ checkboxes
break ;
case 3 : // for sortable lists ?>
<!-- the following would normaly be generated via php with info from the DB -->
<ul id="sort">
<li id="choice_1">Item 1</li>
<li id="choice_2">Item 2</li>
<li id="choice_3">Item 3</li>
<li id="choice_4">Item 4</li>
<li id="choice_5">Item 5</li>
</ul>
<?php break ; ?>
<?php } ?>
<input type="submit" name="submit" value="Submit">
</form>
and this is where it breaks
<script type="text/javascript">
$(function() {
$("#sort").sortable({
var newOrder = $(this).sortable('serialize');
// the 'quiz.php' file called below is the one we're in
$.post('quiz.php', {sort: newOrder };
});
$("#sort").disableSelection();
});
</script>
</body>
</html>
What has me stumped is that not only is the result not sent to $_POST after the form has been submitted --so nothing happens-- but the 2 lines of code inside the $("#sort").sortable() function breaks the interaction behavior completely i.e the list isn't sortable AND the text can be selected.
Any hint, help ?
[EDIT] : Thanks to Jordan, I've got the sortable part runing but the data still isn't being sent.
The code in use now :
<script type="text/javascript">
$(function() {
$('#sort-form').on('submit',function(event){
// Prevent the form from being submitted normally
event.preventDefault();
var newOrder = $(this).sortable('serialize');
$.post('quiz.php', {sort: newOrder };
});
</script>
doesn't result in anything, with the console in Chrome now saying that there is an "Uncaught SyntaxError : Unexpected end of input" juste before the closing tag.
I don't know if it's relevant or not but it has me thinking that
either I'm missing a typo somewhere or the function needs more arguments…
[EDIT 2] Replaced the "-" on the <li> id's with underscores (more compliant w/ jQuery UI guidelines)
The serialization and ajax call won't work in the sortable function because you're trying to define them as options on the sortable component itself. You should listen for when a button is pressed and then get your serialization and call the ajax function
So you could add an id to the form like
<form action="quiz.php" method="POST" id="sort-form">
And then listen in jQuery for when the form is trying to be submitted
$('#sort-form').on('submit',function(event){
// Prevent the form from being submitted normally
event.preventDefault();
var newOrder = $('#sort').sortable('serialize', {
key: 'sort'
});
$.post('quiz.php', newOrder);
});
And now when you're calling the sortable component just call it like this
$("#sort").sortable();
$("#sort").disableSelection();
UPDATE
If you don't wish to use Ajax to submit the form data you can try to set a hidden input to have the value set as the serialized sort data, something like this
$('#sort-form').on('submit',function(event){
// Prevent the form from being submitted normally
event.preventDefault();
var newOrder = $('#sort').sortable('serialize', {
key: 'sort'
});
$('.hidden-input-class').val(newOrder);
// Submit the form like normal
$(this).submit();
});
well I removed it anyways as I should not have placed it here anyway. Should have thaught it over a bit more I guess. I believe it was relevant but maybe not clear at all. But anyho, to avoid further strange things from happing on my server I removed it so considder it never said. Good luck with it, hope you get your answer soon.

Update content of div using javascript/jquery/php

I am currently making a webpage where I want the user to view different database results depending on which result they pick. The results will either be picked through a button, or by a query typed in by hand into a textarea.
I have the connection to the database and everything set up in an external PHP script which I am currently linking in to my site using "require".
Within this PHP script I have a "query" variable.
I would like for this variable to be dependent on whatever value is entered by the user.
I suppose this should be doable using some sort of $query = $POST['entry'] and some kind of Ajax call in a javascript? I just don't know how this whole thing should be fitted together.
If we assume that my menu and container looks something like this, where getData.php is where the $query variable is and what returns the database data.
<div id="menu">
<textarea class="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input class="menuButt" type="button" value="Submit" onclick="JavaScript:ChangeDivVal();"/>
</div>
<div id="container">
<?php
require 'getData.php';
?>
</div>
Here is a picture if that helps my explanation of what I want to do.
I'm very grateful for any help I could possibly get!
//Ambrose
There are neat and simple mechanisms to pass the input of your textarea (the query string) to php and return the database output back to javascript. From there you then can easily attach it to any dom node you wish.
I personally do stuff with jQuery since its so handy. You might wanna use the load function for your simple purpose:
$( document ).ready(function() {
$('#querySubmitButton').click(function (evt)
{
evt.preventDefault(); // stops the submit taking place
var myQuery = $('#queryText').val(); // get the query value
// load data received from php script into the dom container
$('#container').load('getData.php', { query:myQuery, anotherVar:null });
});
});
The load function simply loads everything the desired script outputs into the given domnode. You can add as many parameters as you want in the second argument and could even use a callback to perform some more js after loading.
For details see http://api.jquery.com/load/.
Oh and by the way I changed your html to this:
<div id="menu">
<textarea id="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input id="querySubmitButton" type="button" value="Submit"/>
</div>
<div id="container"></div>
In your getData.php (which I assume produces plain html) you can then use php's $_POST var to get the query.
$query = $_POST['query'];

Get php variable from url on reload without refresh

I'm working on a hobby project (usually working as a designer, so not all that familiar to php – please have oversight with all or any redundant code), trying to learn new things. Now I've bumped into a problem that I don't quite seem to get the hang of.
I have an index.php used to display random sentences from data.php, this works fine – however I want to be able to sort out specific types of sentences for different people if necessary. This is done with a dropdown containing Designer, Illustrator and Developer.
If for example you choose Developer from the dropdown menu, the page reloads with index.php?yrke=developer in the URL as a result. This is all fine and as expected, and when i echo $_GET['yrke']; from data.php it displays the text "developer" fine the first load, but upon clicking the randomizerButton button (note that the content is loaded from data.php without refreshing the page in the browser when clicking this button) $_GET['yrke']; does not seem to be able to get a read on the value in the url (putting $_GET['yrke']; in index.php obviously works regardless, but I need to access the url variable in data.php).
If there's a way to do this while maintaining the "update-content-without-browser-refresh" function that'd be awesome, the other easiest solution would perhaps be to remove said "update-content-without-browser-refresh" and go for good old refreshes and thus solving the problem – but why make it that easy right?
index.php (excerpt)
<button data-href="data.php" class="randomizerButton">Randomize sentences</button>
<form action="index.php" method="get">
<select name="yrke" onchange="this.form.submit()">
<option value="designer"<?=$_GET['yrke'] == 'designer' ? ' selected="selected"' : '';?>>Designer</option>
<option value="illustrator"<?=$_GET['yrke'] == 'illustrator' ? ' selected="selected"' : '';?>>Illustrator</option>
<option value="developer"<?=$_GET['yrke'] == 'developer' ? ' selected="selected"' : '';?>>Developer</option>
</select>
</form>
<?php include('data.php'); ?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('button.randomizerButton').click(function(){
scriptUrl = $(this).attr('data-href');
$.post(scriptUrl, function(response){
$('#results').html(response);
});
});
});
</script>
data.php (excerpt)
echo $_GET['yrke'];
If you want $_GET['yrke'] on data.php you would have to use $.get() and just use the full URL, like:
$.get('data.php?yrke='+encodeURIComponent($('[name=yrke]').val()), function(response){
$('#results').html(response);
}
I would use
$.post('data.php', {yrke:encodeURIComponent($('[name=yrke]').val())}, function(response){
$('#results').html(response);
}
with $_POST['yrke'] on data.php. Usually, I would not have a form that submits in the traditional manner. It's all about the AJAX.
Not sure if this will help but you could do something like this...
<div id ="content">
<?php
$pages_dir ='pages';
if(!empty($_GET['p'])){
$pages =scandir($pages_dir, 0);
unset($pages[0], $pages[1]);
$p = $_GET['p'];
if (in_array($p.'.inc.php', $pages)){
include($pages_dir.'/'.$p.'.inc.php');
}else {
echo'Page not found';
}
}else{
include($pages_dir.'/home.inc.php');
}
?>
HERE
</div>
Make a folder called pages then name the files within the folder "aboutus.inc.php" ect. the important part of the file extension is .inc.php , you can name anything before .inc.php anthing you like here is an example of how to write the navigation "About us"
IF need be I can send you a blank template

Overwriting JavaScript variables to save permanently?

I'm creating a website with the option to Login with an administrative account and I want to be able to edit different elements in the HTML set to javascript variables. When you log in, there will be an input box to take a value from the user and apply it to a widget on the page. I haven't yet found a way to save the input value by overwriting the variable set for the widget and have it save to the webhost (GoDaddy) and stay throughout all sessions for anyone who shall be looking. I don't want to use Cookies or localStorage because I would like for the value to not only save on that user's session but all looking at the site. Ideas?
(EDITED CONTENT BELOW)
Alright, I've used a database. I've gotten the code below:
<html>
<head>
<title>
MyAccount
</title>
</head>
<body>
<center>
<h1>
Welcome to your account!
</h1>
<input name="alertVal" type="text" placeholder="Alert Value">
<input type="button" text="Save" onclick="<?php saveAlert()?>">
<?php
// Connects to your Database
function saveAlert(){
mysql_connect("My IP is here. Not sharing that.", "adminLog", "Yeah, not putting my pass on a forum...") or die(mysql_error());
mysql_select_db("adminLog") or die(mysql_error());
$data = mysql_query("SELECT * FROM Alert")
or die(mysql_error());
while($info == mysql_fetch_array( $data ))
{
mysql_query("Update Alert SET Value = '$cleanURL'")
INSERT INTO Alert (Value);
VALUES ($_GET['alertVal']);
}
}
?>
</center>
</body>
</html>
And that doesn't work. Raises a T_STRING error. I don't really understand that. Help?
I don't want to use Cookies or localStorage because I would like for
the value to not only save on that user's session but all looking at
the site. Ideas?
If you don't want to use the various client-side stores stored (such as cookies or localStorage) you might consider storing this information on the server, in a database or a file. Depending on the server side language you are using there might be different approaches to achieve that.
You should use some sort of a database or just a simple text file. If you don't want to use a database, I recommend using Yaml.
BTW all GoDaddy plans include MySql. you can use that.

Categories

Resources