how Start PHP Session when click with jquery - php

i have problim in jquery
i working in interactive map, in click form href for city i wnat insert the city name or number in sql query .
this link
link citys :
<a href='#' class='city_pr' id=aden> </a>
mysql query:
$sql="select * from project where city='$_SESSION[CITY]' AND active =1 ";
How to make a change when the session to mysql query on click the link below Download Page Navigation with jquery

It is not possible to use PHP session directly with jQuery, you need to do an ajax call.
Try this.
Explanation:
This will capture the value inside the link, do a post to a PHP file and print the data in "result" div without refreshing the page.
(Don't forget to read my observation at the end of the post)
HTML:
<a href='#' id='country'>USA</a>
<br/>
<div id="result"></div>
JS:
​$('#country').click(function(){
// get the value inside the <a> tag
var country = $(this).html();
$.post('process.php', { country:country }, function(data){
// Everything is Ok, so data won't be 0
if(data != 0){
// Print country information
$('#result').html(data);
}
});
});
process.php
<?php
if($_POST() && isset($_POST['country'])){
/* Connect to DB */
$link = mysql_connect('server', 'user', 'pwd');
if (!$link) {
// No connection
print(0);
exit();
}
$db = mysql_select_db('db', $link);
if (!$db) {
// DB selection error
print(0);
exit();
}
/* sanitize the value */
$country = mysql_real_escape_string($_POST['country']);
/* do your query */
$sql = "SELECT * FROM country WHERE country_name = '$country'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
// At this point I am supposing that you stored in your table
// latitudes and longitudes of countries.
echo "Latitude is: ".$row['latitude']." Longitude is: ".$row['longitude'];
}
} else {
// No results found
print(0);
}
}
?>​
Observation:
Try using other way to send the country value to the server.
For example:
if I have:
<a href='#' id='country'>United States of America</a>
In SQL query I will have:
SELECT * FROM country WHERE country_name = 'United States of America';
A better way could be:
<a href='#' id='us'>United States of America</a>
So in my JS I will have to replace var country = $(this).html(); for this:
//outputs 'us'
var country = $(this).attr('id');
Then in your SQL query you will get this:
SELECT * FROM country WHERE country_name = 'us';
It is more reasonable to use codes and no names (names are just to show the user, for better understanding because then you will have more problems to sanitize the value for using it with your query and also use functions like trim(); to remove spaces and others). If you do that you will have to change your query to find the country by code:
SELECT * FROM country WHERE country_code = 'us';
Hope this helps :-)

Related

Removing Selected Option From Database

I have a select element created dynamically with items from my database. I would like to be able to delete the record from the database if the delete button is selected. Currently I have an AJAX function that is sending a GET request to my current page to remove it, and it removes the item from my options, however, my PHP used to access my database is never called and therefore when I refresh, the query is ran and what I just "removed" is displayed again because it is still in my db. I know I must be missing something simplistic, I just can't quite put my
finger on it and would appreciate any help or advice. I'm open to other methods as well. This is definitely not my strong suit.
My AJAX:
window.onload = function () {
document.getElementById("deleteLoc").onclick = function () {
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "adminLocationEdit.php", //Where to make Ajax calls
data:{deleteLoc : $("#lList option:selected").val() },
dataType:"text", // Data type, HTML, json etc.
});
$("#lList option:selected").remove();
}
};
My HTML:
<select id ="lList" multiple="multiple" style="width:400px;height:400px;">
<?php
//Query that selects all locations from the database and creates the list dynamically.
$qry = "SELECT * FROM location";
$qry_result = odbc_exec($admconn,$qry) or die("A database error has been detected. Err: adminLocationListEdit-1");
//Echo the db results into the select box.
while($row = odbc_fetch_array($qry_result)){
//Sets each row to variable.
$locID = $row['locationName'];
echo "<option id =\"$locID\" name = \"$locID\" onclick =\"$('#form1').load('incl/adminLocationEdit.php?loc='+$(this).attr('id'));displayFieldsets('form1', 'locList', 'lList');\">" . $locID . "</option>";
}
?>
My PHP:
//If user wants to add a new location
if(isset($_POST['addLoc'])){
//Re-directs
//header("Location: adminLocation.php");
exit;
}
//If user wants to Delete a location from the database.
if(isset($_POST['deleteLoc'])){
$contentToDelete = $_POST['deleteLoc'];
//Deletes current location from the database.
$qry = "DELETE FROM location WHERE locationName = '" . $contentToDelete . "'";
$qry_result = odbc_exec($admconn,$qry) or die("A database error has been detected. Err: adminLocationListEdit-2");
}
You are mixing both GET and POST
If you are looking for post,
This should be
data:{deleteLoc : $("#lList option:selected").val() },
Or if you are looking fr GET
type: "GET",// this should be GET not POST

Displaying output of php within jquery colorbox ... getting undefined index error

I hope someone can help me, I have created a simple html form with drop down menu's, the drop down menus are populated from a mysql data base, the user must select from two drop downs and this will then display the data ( both selections make the sql query)
This all works correctly within the HTML however I am trying to jazz it up a bit and have the output display within a jquery colorbox (popup).
I am not sure how to format the syntax for the jquery function .. this is what I have so far
<script>
$(document).ready(function(){
$(".inline").colorbox({inline:true, width:"50%"});
$("input#formsubmit").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
return url;
}, innerWidth:920, innerHeight:"86%", iframe:true});
});
</script>
This correctly launches the colorbox pop up and fires the php "action" from my form but the $_POST attributes are not sent across and I just get an unidentified index error from mysql.
Can some one please help me ?
Im sure its something simple, but I cant figure it out.
Many thanks
Adding PHP ...
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("verify") or die(mysql_error());
$result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$_POST[product]' AND CustomerType = '$_POST[customer]'")
or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['Entitlement'] ;
echo "<br />";
}
?>
Can you please tell how may this code works with you :)
<?php $result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$_POST[product]' AND CustomerType = '$_POST[customer]'");?>
You have 2 error the first one the single quote beside the index in your post variable and must be like this $_POST['product'],$_POST['customer'] then the second error is that you must encapsulate your variable inside the string as following {$_POST['product']},{$_POST['customer']}
Try these work around then tell me the result :)
try this
<?php
// Checking for valid post data
if (isset($_POST['product']) && isset($_POST['customer']) && !empty($_POST['product']) && !empty($_POST['customer'])) {
// Cleaning post data
$proudct = mysql_escape_string($_POST['product']);
$customer = mysql_escape_string($_POST['customer']);
// db connnection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("verify") or die(mysql_error());
// Quering
$result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$proudct' AND CustomerType = '$customer'") or die(mysql_error());
// Printing result
while ($row = mysql_fetch_array($result)) {
echo $row['Entitlement'];
echo "<br />";
}
}
?>

Drop down with MySQL and PHP sample

I have tried out this example but not sure where I have gone wrong - I've created the database and relative fields. When I select UK it gives me a blank result. Here is my script
main.php
<?php
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
$dbselect=mysql_select_db("test");
$sql_country = "SELECT * FROM COUNTRY";
$result_country = mysql_query($sql_country) or die("Query problem");
echo "<form method='POST'>";
echo "<select name='country' onChange='get_cities(this.value)'>"; //get_cities is defined below
echo "<option value=''></option>";
while($row_country = mysql_fetch_array($result_country))
{
echo "<option value='".$row_country['id']."'>".$row_country['country']."</option>";
}
echo "</select>";
echo "<select name='city' id='city'></select>"; //We have given id to this dropdown
echo "</form>";
?>
<script type="text/javascript">
function get_cities(country_id)
{
$.ajax({
type: "POST",
url: "cities.php", /* The country id will be sent to this file */
beforeSend: function () {
$("#city").html("<option>Loading ...</option>");
},
data: "country_id="+country_id,
success: function(msg){
$("#city").html(msg);
}
});
}
</script>
cities.php
<?php
// Code for cities.php
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
$dbselect=mysql_select_db("test");
$country_id = $_REQUEST['country_id'];
$sql_city = "SELECT * FROM CITY WHERE country_id = '".$country_id."'";
$result_city = mysql_query($sql_city);
echo "<select name='city'>";
while($row_city = mysql_fetch_array($result_city))
{
echo "<option value='".$row_city['id']."'>".$row_city['city']."</option>";
}
echo "</select>";
?>
Sample code: http://www.x-developer.com/php-scripts/loading-drop-downs-with-ajax-php-and-fetching-values-from-database-without-refreshing-the-page
There doesn't seem to be any error checking in your example, and you should be aware that with databases, plenty of things can go wrong!
Try making these amendments. Change this:
$connect=mysql_connect("localhost","root","");
to:
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
And this:
$result_country = mysql_query($sql_country);
to:
$result_country = mysql_query($sql_country) or die("Query problem");
This will highlight two common problems - connecting or not finding the specified table.
Also, cities.php doesn't appear to connect to the database at all. Add in the mysql_connect and the mysql_select_db from the first file into the second, and that should connect it correctly.
Lastly, there is a serious security vulnerability with this tutorial, which would permit internet users to run arbitrary SQL on your database server. Change this:
$country_id = $_REQUEST['country_id'];
to this:
$country_id = (int) $_REQUEST['country_id'];
That will force the country ID to be an integer, rather than just accepting it uncritically as a string.
In your cities.php there is no database connection. Write the DB connection there also after that it will give you drop down.
You have not any databse connection in cities.php, so SELECT statement does not work.
If you are open to use jquery, which is a great help when it comes to ajax driven web apps,
Try this for your jquery code
//ensure the select name 'country' has the id 'country'
$("#country").change(function(){
//get country id of the selected country option
var countryid = $("#country option:selected").val();
//here we post the id of the country to the php page. note that within the curly braces, the first parameter is what corresponds to the variable in php e.g $countryid=$_POST[country_id]. The second parameter is the javascript variable
$.post("cities.php",{country_id:countryid},function(data){
//check that the json object returned is not empty
if(!$.isEmptyObject(data))
{
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
var cityid = [data[i].id];
var cityname = [data[i].city];
html += '<option value = '+cityid+'>'+city+'</option>';
}
//append the results of the query. The prepend part is to make a blank option first and make it selected so as to force a user to actually select a city.
$("#city").html(html).prepend("<option value='' selected='selected'></option>").show();
}
else{
alert('No cities found for this country');
}
},'json')
})
Your php page for cities remains as it is but make the following adjustments
<?php
// Code for cities.php
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
$dbselect=mysql_select_db("test");
//change it from request to post.
$country_id = $_POST['country_id'];
//the below code is not safe!!! You are open to sql injection. To make it worse you are connected as root. A malicious user can drop your database.
$sql_city = "SELECT * FROM CITY WHERE country_id = '".$country_id."'";
$result_city = mysql_query($sql_city);
while($row_city = mysql_fetch_array($result_city))
{
$data[] = $row_city;
}
//return the json onject to the client.
echo json_encode($data);
?>
The above code might help you should you choose the jquery way of writing javascript. You will need to download jquery first.
The response from the server contains a dropdown menu, but the current code appends the HTML result not into a div or span, but into into another dropdown menu, thus:
<select name='city' id='city'><select name='city'>....</select> </select>
This is incorrect. To avoid this, change:
echo "<select name='city' id='city'></select>";
to
echo "<div id='city'> </div>";
Or, removeecho "<select>" line from cities.php
<?php
// DB CONNECTION
$country_id = $_REQUEST['country_id'];
$sql_city = "SELECT * FROM CITY WHERE country_id = '".$country_id."'";
$result_city = mysql_query($sql_city);
while($row_city = mysql_fetch_array($result_city))
{
echo "<option value='".$row_city['id']."'>".$row_city['city']."</option>";
}
?>

How can I solve this mysql search query

I'm working on a chained select drop down that pulls data from the database to populate the category combobox while the subcategory combo box populates when an option from the category combobox is selected. The category dropdown box pulls data from database without any issue but I am having problems with getting the subcategorycombo box select data from database based on the 'id' of the option selected in the category combo box.Any help pls?below is my php code and the jquery code that display the data
<?php
include ('../storescripts/connection.php');
function ShowCategory(){
$sql = "SELECT * FROM category";
$res = mysql_query($sql) or die(mysql_error());
$category = '<option value="0">Choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value = "'.$row['category_id'].'"> '.$row['category_name']. ' </option>';
}
return $category;
}
function ShowSubCategory(){
if (!isset($_POST['id']))
{
//If not isset -> set with dumy value
$_POST['id'] = "";
}
$sql1 = "SELECT * FROM subcategory WHERE category_id = '$_POST[id]'";
$res1 = mysql_query($sql1) or die(mysql_error());
$subcategory = '<option value="0"> Choose...</option>';
while($row = mysql_fetch_array($res1)){
$subcategory .= '<option value="'.$row['subcategory_id'].'"> '.$row['subcategory_name'].' </option>';
}
return $subcategory;
}
?>
//jquery code
<script type="text/javascript">
$(document).ready(function() {
$("select#category").change(function(){
var id = $("select#category option:selected").attr('value');
$.post("select_subcat.php", {id:id}, function(data){
$("select#subcategory").html(data);
});
});
});
</script>
Try to narrow down what could be the problem. Have PHP print out the SQL statements to the page when you make a selection.
Then you can feed that exact statement into MySQL (through command line or via phpmyadmin) and see if you get the results you want. If you do, then the problem is later down the line. What do you see?
I will agree with earlier poster - if the $_POST id is not set, you fill it with ""? That probably won't get any results.
One last note: at very least use mysql_real_escape_string() before you ever touch any $_POST or $_GET variables. You are opening your site up to a number of SQL injection attacks otherwise.

linking the AJAX Autocomplete answer from JSON answer to a specific URL/Webpage

I'm trying to link each Ajax Autocomplete result with a specific URL ("landing Page").
URL: www.aebli.com, search field in the upper right corner, try with "h" or "ho"
Ajax-Code for the Search-Box:
<script type="text/javascript" src="js/dimensions.js"></script>
<script type="text/javascript" src="js/autocomplete.js"></script>
<script type="text/javascript">
$(function(){
setAutoComplete("searchField", "results", "php/autocomplete.php?part=");
});
</script>
here the file "autocomplete.php" which select the specific table form the MySQL Database:
<?php
$link = mysql_connect('localhost', 'root', 'root');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db("dreampix")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$result = mysql_query("SELECT name FROM treffer");
while ($row = mysql_fetch_assoc($result)) {
$colors[]=$row['name'];
}
mysql_free_result($result);
mysql_close($link);
// check the parameter
if(isset($_GET['part']) and $_GET['part'] != '')
{
// initialize the results array
$results = array();
// search colors
foreach($colors as $color)
{
// if it starts with 'part' add to results
if( strpos($color, $_GET['part']) === 0 ){
$results[] = $color;
}
}
// return the array as json with PHP 5.2
echo json_encode($results);
}
?>
As you can see on www.aebli.com, the Search-Field works, try with "ho". The MySQL-Database-Table contents only two rows: id and some entries like "hochzeit". How can I "connect" the AJAX Autocomplete-Results with an <a href="#"> to an specific landing page such as aebli.com/searchresluts for "hochzeit".php ?
I wish that the user search for "ho", gets an list an can click on one of the results to open the target webpage..
First you should add the url column to the treffer table, so the script knows which URL is each term associated with. Then modify your script so it also returns the URL in the JSON response.
So instead of:
["hochzeit"]
The response will look something like this:
[{"url":"/searchresluts", "name":"hochzeit"}]
Then you need to modify the javascript part. Looking at the autocomplete documentation, I found out you need to replace the default formatItem function. Refer to this answer how to do it.

Categories