Trigger combo box events using jquery - php

I have this code:
$show_location = mysql_query("SELECT * FROM location ORDER BY location_code");
while($row_location = mysql_fetch_array($show_location))
{
$location_code = $row_location['location_code'];
$show_store = mysql_query("SELECT * FROM store_list WHERE location LIKE '%$location_code%'");
$count_store = mysql_num_rows($show_store);
while($row_store = mysql_fetch_array($show_store))
{
$store_name = $row_store['store_name'];
}
if($count_store==0)
{
$status = "Inactive";
echo '<option value="'.$location_code.'">'.$location_code.'</option>';
$sql1 = "SELECT description FROM location WHERE location_code=$location_code";
$result1 = mysql_query("$sql1");
$row1 = mysql_fetch_assoc($result1);
$description=$row1['description'];
}
else
{
$status = "Active";
}
//echo '<option value="'.$location_code.'">'.$location_code.'</option>';
}
What I want to do is to display the $description somewhere in the form. I have the kind of combobox where you can select as many as you can. I want to display each $description once a location is selected. But I dont know where to put the trigger. Can sombody help me? Thanks!

correct me if i am wrong, but will every location_code have one description right?
well there are two ways:
1) Easy but not so efficient way
Make an ajax call for every selected value.
$("#myDropDown").change(function (event) {
//alert("You have Selected :: "+$(this).val());
$.ajax({
type: "POST",
url: "ajax.php",
data: { type: "1", location: $(this).val() }
}).done(function( msg ) {
("#mydata").html(msg)
});
});
You can check for type == 1 on php side, get the description and print it
The above method will cause a ajax request for every selection
2) A bit complex, but efficient
First of all json_encode your location_code and description. It will become something like {code:"AU", description:"blah blah"}
Then use something like this
$("#sel").change(function(e){
//alert($(this).val());
var array = $(this).val();
for(key in array){
var json = JSON.parse(array[key]);
$("#desiptions").html(json.description);
}
});

Related

How to update dynamically populated content with AJAX

I have some code which populates like so:
<select class="form-control" name="accommodation_ID" id="accommodation_ID">
<option value="-1">-- Please Select --</option>
<?php
$AccomodationID = 13; //For testing purposes
$accommodation_query = mysqli_query($conn,"SELECT ENTITIES.LastName,
ACCOMMODATION.AccomodationID, ACCOMMODATION.PUPoint
FROM ACCOMMODATION, ENTITIES WHERE ENTITIES.Entity_ID =
ACCOMMODATION.Entity_ID")
or die("Error: ".mysqli_error($conn));
while($accommodation_Results = mysqli_fetch_array($accommodation_query)){
if($accommodation_Results['AccomodationID'] == $AccomodationID){
echo '<option selected value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
$PUPoint = $accommodation_Results['PUPoint'];
}
else{
echo '<option value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
}
}
?>
</select>
<label>Pick Up Point</label>
<input type="text" name="PUPoint" readonly value="<?php echo $PUPoint; ?>">
This code works no problem, it checks the database and looks for a match, if it does, set is as the selected option, grab the PUPoint (Pickup point) variable and store it in the input field.
My problem now, is when I go to select a different option from the dropdown list, the pickup point input field doesn't update anymore. This is what I had, working before I implemented the above:
j$('select[name=accommodation_ID]').change(function(event) {
event.preventDefault();
var accommodationID = j$(this).val();
post_data = {'accommodation_ID':accommodationID};
var data = {
"action": "Accommodation_Details"
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
j$('input[name=PUPoint]').val( data["PUPoint"] );
},
error: function (request) {
console.log(request.responseText);
}
});
});
booking_Modify.php
//checks and switch statement related code
$return = $_POST;
$return["accommodation_ID"] = $_POST["accommodation_ID"];
$return["SQL"] = "SELECT * FROM ACCOMMODATION WHERE AccommodationID = ".$_POST["accommodation_ID"]."";
$query = mysqli_query($conn,"SELECT * FROM ACCOMMODATION WHERE AccomodationID = ".$_POST["accommodation_ID"]."")
or die("Error: ".mysqli_error($conn));
$row = mysqli_fetch_array($query);
$return["PUPoint"] = $row["PUPoint"];
$return["json"] = json_encode($return);
echo json_encode($return);
I've done some echoing/console.log and noticed that it's always passing the same Accommodation ID number (13) into booking_Modify.php. It doesn't change when I select a different option now. I don't know if it's because of the "selected" attribute applied to the option element now. Any ideas would be greatly appreciated
You have defined your $AccomodationID = 13; //For testing purposes before which is printed in every iteration of the while loop instead of the current ID. Probably you want to write $accommodation_Results['AccomodationID'] as the option value.

using jquery post to send values to php file

I'm trying to write a script in javascript/jquery that will send values to a php file that will then update the database. The problem is that the values aren't being read in by the PHP file, and I have no idea why. I hard-coded in values and that worked fine. Any ideas?
Here's the javascript:
var hours = document.getElementById("hours");
var i = 1;
while(i < numberofMembers) {
var memberID = document.getElementById("member"+i);
if(memberID && memberID.checked) {
var memberID = document.getElementById("member"+i).value;
$.ajax({
type : 'post',
datatype: 'json',
url : 'subtract.php',
data : {hours : hours.value, memberID : memberID.value},
success: function(response) {
if(response == 'success') {
alert('Hours subtracted!');
} else {
alert('Error!');
}
}
});
}
i++;
}
}
subtract.php:
if(!empty($_POST['hours']) AND !empty($_POST['memberID'])) {
$hoursToSubtract = (int)$_POST['hours'];
$studentIDString = (int)$_POST['memberID'];
}
$query = mysql_query("SELECT * FROM `user_trials` WHERE `studentid` = '$studentIDString' LIMIT 1");
Edit: Updated code following #Daedal's code. I'm still not able to get the data in the PHP, tried running FirePHP but all I got was "profile still running" and then nothing.
This might help you:
function subtractHours(numberofMembers) {
var hours = document.getElementById('hours');
var i = 1;
while(i < numberofMembers) {
// Put the element in var
var memberID = document.getElementById(i);
// Check if exists and if it's checked
if(memberID && memberID.checked) {
// Use hours.value and memberID.value in your $.POST data
// {hours : hours.value, memberID : memberID.value}
console.log(hours.value + ' - ' + memberID.value);
// $ajax is kinda longer version of $.post api.jquery.com/jQuery.ajax/
$.ajax({
type : 'post',
dataType : 'json', // http://en.wikipedia.org/wiki/JSON
url : 'subtract.php',
data : { hours : hours.value, memberID : memberID.value},
success: function(response) {
if( response.type == 'success' ) {
alert('Bravo! ' + response.result);
} else {
alert('Error!');
};
}
});
}
i++;
}
}
and PHP part:
$result = array();
// Assuming we are dealing with numbers
if ( ! empty( $_POST['hours'] ) AND ! empty( $_POST['memberID'] ) ) {
$result['type'] = "success";
$result['result'] = (int) $_POST['hours'] . ' and ' . (int) $_POST['memberID'];
} else {
$result['type'] = "error";
}
// http://php.net/manual/en/function.json-encode.php
$result = json_encode( $result );
echo $result;
die();
Also you probably don't want to CSS #ID start with a number or to consist only from numbers. CSS Tricks explained it well http://css-tricks.com/ids-cannot-start-with-a-number/
You can simple fix that by putting some string in front:
var memberID = document.getElementById('some_string_' + i);
This is not ideal solution but it might help you to solve this error.
Cheers!
UPDATE:
First thing that came to my mind is that #ID with a number but as it seems JS don't care about that (at least not in a way CSS does) but it is a good practice not to use all numbers. So whole error was because document.getElementById() only accepts string.
Reference: https://developer.mozilla.org/en-US/docs/DOM/document.getElementById id is a case-sensitive string representing the unique ID of the element being sought.
Few of the members already mentioned converting var i to string and that was the key to your solution. So var memberID = document.getElementById(i); converts reference to a string. Similar thing could
be accomplished I think in your original code if you defined wright bellow the loop while(i < numberofMembers) { var i to string i = i.toString(); but I think our present solution is better.
Try removing the '' fx:
$.post (
"subtract.php",
{hours : hours, memberID : memberID}
try this
$.ajax({type: "POST",
url:"subtract.php",
data: '&hours='+hours+'&memberID='+memberID,
success: function(data){
}
});
Also you could try something like this to check
$(":checkbox").change(function(){
var thisId = $(this).attr('id');
console.log('Id - '+thisId);
});
$studentID = $_GET['memberID'];
$hoursToSubtract = $_GET['hours'];
Try this:
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
document.body.style.cursor = "auto";
});
Try n use this...
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
$(body).css({ 'cursor' : 'auto' });
});

jquery autcomplete returning source array

I'm using jquery's ajax function to fetch data from an external php file. The data that is returned from the php file will be used for the autocomplete function. But, instead of the autocomplete function suggesting each particular value from the array in the php file, it returns ALL of them. My jquery looks like this.
jQuery('input[name=past_team]:radio').click(function(){
$('#shadow').fadeIn('slow');
$('#year').fadeIn('slow');
var year = $('#year').val();
$('#year').change(function () {
$('#shadow').val('');
$.ajax({
type: "POST",
url: "links.php",
data: ({
year: year,
type: "past_team"
}),
success: function(data)
{
var data = [data];
$("#shadow").autocomplete({
source: data
});
}
});
});
});
The link.php file looks like this:
<?php
session_start();
require_once("functions.php");
connect();
$type = $_POST['type'];
$year = $_POST['year'];
if($type == "past_team")
{
$funk = mysql_query("SELECT * FROM past_season_team_articles WHERE year = '".$year."'")or die(mysql_error());
$count = mysql_num_rows($funk);
$i = 0;
while($row = mysql_fetch_assoc($funk))
{
$name[$i] = $row['team'];
$i++;
}
$data = "";
for($i=0;$i<$count;$i++)
{
if($i != ($count-1))
{
$data .= '"'.$name[$i].'", ';
} else
{
$data .= '"'.$name[$i].'"';
}
}
echo $data;
}
?>
The autocomplete works. But, it's just that when I begin to enter something in the input field, the suggestion that are loaded is the entire array. I'll get "Chicago Cubs", "Boston Red Sox", "Atlanta Braves", .....
Use i.e. Json to render your output in the php script.
ATM it's not parsed by javascript only concaternated with "," to a single array element. I do not think that's what you want. Also pay attention to the required datastructure of data.
For a working example (on the Client Side see the Remote JSONP example http://jqueryui.com/demos/autocomplete/#remote-jsonp )

If else in Jquery

i am a noob to jquery and i want to know how to make use of if else for the following:
on the server side there is a if for number of rows is equal to 0 and else some JSON part.
$age= mysql_query("SELECT title FROM parent WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
if ($age_num_rows==0)
{
echo "true";
}
else
{
$sql ="SELECT * FROM parentid WHERE id = '$name'"; //$name is value from html
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$abc_output = array('title' => $row['title'],'age' => $row['age']);
}
echo json_encode($abc_output);
}
Now coming to Jquery part :
If the above PHP code go to if part then i want to display an alert box or if it goes to else part it needs to insert some values into the forms.
Here is something i tried but it did not work.
$(document).ready(function(){
$("#button1").click(function(){
$.getJSON('script_1.php',function(data){
if (data=='true') {
alert ('hello')
}
else {
$.post('script_1.php',
{ id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
},
"json");
}
});
});
Edited:
$(document).ready(function(){
$("#button1").click(function(){
$.post(
'script.php',
{ id: $('input[name="id"]', '#myForm').val() },
function(json) {
var data = JSON.parse(json);
if (data.length === 0){
alert('no data');
}
else{
$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
}},
"json"
);
});
});
PHP side
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($row) {
$row= array('title' => $row['title'],'age' => $row['age']);
echo json_encode($row);
} else {
echo json_encode(array());
}
You need to parse the JSON before you can use it like that. Modern browsers will have built in support for JSON.parse(yourJSON), but to account for those that don't, you should use Douglas Crockford's JavaScript JSON library. Including it will provide JSON.parse() if the browser doesn't have it already.
For the if-else stuff you're doing in the PHP, the common practice is to echo out an empty JSON object or array, so you don't have to test for things like no rows on the server side. You could do something as simple as this, later accounting for your database column names:
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
echo json_encode($row);
} else {
echo json_encode(array());
}
Back in the JavaScript, you could then do something like this:
var data = JSON.parse(json);
if (data.length === 0) {
alert('no data');
} else {
$("input[name='title']").val(data.title);
$("input[name='age']").val(data.age);
}
jeroen is right though, you only need to use one AJAX call.
There seem to be a few problems:
You are treating the data returned from getJSON as if it is plain
text
The php that you are calling from javascript does not always
return json
You are doing 2 ajax requests; getJSON and post where you only need one: The first call to getJSON without any data will never reach the else condition
By the way, where does $name come from in your php script? For your second ajax call to work, it needs to be something like mysql_real_escape_string($_POST['id']) or (int) $_POST['id'] if it is an integer.
Edit: I think it would be easiest to get rid of the .post and just use the first ajax call. So you will need to change:
$.getJSON('script_1.php',function(data){
to something like:
$.getJSON('script_1.php?id=' + $('input[name="id"]').val(), function(data) {
and in your php you need to use something like:
$name = mysql_real_escape_string($_GET['id']);

how to update PHP variable with Jquery Ajax?

I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});

Categories