check txt one by one with jquery - php

what i'm trying to do is check div value one by one via jquery and php, if php is say value is 1 to make the div value color red if its 0 to make the txt color blue, the check script is not working right if i put on php q1 = Tag1 is not making that div red color ...
This is my HTML:
<div class="Tags_Data">
<div class="TagID_1">Tag1</div>
<div class="TagID_1_Status"></div>
<div class="TagID_2">Tag2</div>
<div class="TagID_2_Status"></div>
<div class="TagID_3">Tag3</div>
<div class="TagID_3_Status"></div>
<div class="TagID_4">Tag4</div>
<div class="TagID_4_Status"></div>
<div class="TagID_5">Tag5</div>
<div class="TagID_5_Status"></div>
<div class="TagID_6">Tag6</div>
<div class="TagID_6_Status"></div>
</div>
This is my jquery script
$(document).ready(function() {
var delay = 200;
$("div[class*='TagID_']").each(function() {
$(this).hide().delay(delay).fadeIn(1850);
delay += 200;
var Tag_ID = $(this).attr("class");
var ID_Split = Tag_ID.split('_');
var Tag_Data_ID = ID_Split[2];
var Tag_Scan = $('.TagID_' + Tag_Data_ID);
// ----------------- Post Tag And Check It
$.post("tags_check.php", { q1 : Tag_Scan.attr("value") },
// ----------------- Get The Result
function(result) {
if(result == 1) {
Tag_Scan.css('color','red');
} else {
Tag_Scan.css('color','blue');
}
});
});
});
This is my PHP Code on tags_check.php:
<?php
if($_GET["q1"] == "Tag3") {
echo 1;
} else {
echo 0;
}
?>
Here is my code: http://jsfiddle.net/3C2Pa/1/
Update:
i update the script http://jsfiddle.net/3C2Pa/3 but still the checking is not working ... hope someone can help me with this

You've got three errors in your code:
First one:
var Tag_Data_ID = ID_Split[2];
arrays start from zero as index. So you'll find what you get in the position 1.
var Tag_Data_ID = ID_Split[1];
Second one:
Tag_Scan.attr("value")
you have to use
Tag_Scan.text();
Third one:
you are using "post" to call your php script but you are reading vals through "GET". Use $_POST or $_REQUEST
Moreover I suggest that you use id and class in a better way :)

Related

How to update multiple divs only when new changes is detected jQuery

I want to be updating the divs with posts comments only when new comment is added to MySQL database.
Each of the div have a unique id for posts.
Here what i have but this only update one div leaving the rest empty
Any help is appreciated.
I have 3 php files
Bed.php (index page).
Bed2.php (display last comment time, if changes update with new data from bed1.php)
Bed1.php (post comment from data base for each post id)
<div class="commcommmpost1" idss="1" id="gantt1">comment from post with id 1</div>
<div class="commcommmpost1" idss="2" id="gantt2">comment from post with id 2</div>
<div class="commcommmpost1" idss="3" id="gantt3">comment from post with id 3</div>
<div class="commcommmpost1" idss="4" id="gantt4">comment from post with id 4</div>
<script>
$i = "1";
var auto_refresh = setInterval(function() {
$('.commcommmpost1').each(function(index,
el) {
var thisIDs = $(this).attr('idss');
$.get("bed2.php?id=" +thisIDs, function(data) {
//condition of data
if (data != $i) {
$('#gantt' +thisIDs).load('bed1.php?id=' +thisIDs).fadeIn("slow");
// alert(thisIDs);
$i = data;
}
});
});
}, 2000);
</script>

Data from MySQL to JSON to AJAX within PHP website, how?

I've got really ambitious problem today as I want to achieve something ridiculously stupid but satisfying.
Basically, I do have a database with data for gym exercises
CREATE TABLE IF NOT EXISTS `gp_progs` (
`prog_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`exer` varchar(250) NOT NULL,
`pic` varchar(15) NOT NULL,
PRIMARY KEY (`prog_id`),
UNIQUE KEY `prog_id` (`prog_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
--
-- Dumping data for table `gp_progs`
--
INSERT INTO `gp_progs` (`prog_id`, `name`, `exer`, `pic`) VALUES
(1, 'ABS', 'TO DO ABS YOU NEED TO DO THIS AND THAT', 'abs.jpg'),
(3, 'Arms2', 'this is what we want', 'abs.jpg'),
(7, 'Biceps', 'curls', 'abs.jpg');
I have treated it after digging the code for many hours with this code in PHP
$jsondb = "data/prog.json";
$q = "SELECT * FROM gp_progs";
$r = #mysqli_query ($dbc, $q);
/*$json = array();
while ($row = mysqli_fetch_assoc($r)){
$json[] = $row;
}
$jsondata = json_encode($json, JSON_PRETTY_PRINT);
if(file_put_contents($jsondb, $jsondata)) {
echo 'Data successfully saved';
}
It gave me a json file from which I realy want to build AJAX functional app like this one.
JS:
$(function() { // When the DOM is ready
var times; // Declare global variable
$.ajax({
beforeSend: function(xhr) { // Before requesting data
if (xhr.overrideMimeType) { // If supported
xhr.overrideMimeType("application/json"); // set MIME to prevent errors
}
}
});
// FUNCTION THAT COLLECTS DATA FROM THE JSON FILE
function loadTimetable() { // Declare function
$.getJSON('data/events.json') // Try to collect JSON data
.done( function(data){ // If successful
times = data; // Store it in a variable
}).fail( function() { // If a problem: show message
$('#event').html('Sorry! We could not load the timetable at the moment');
});
}
loadTimetable(); // Call the function
// CLICK ON THE EVENT TO LOAD A TIMETABLE
$('#content').on('click', '#event a', function(e) { // User clicks on event
e.preventDefault(); // Prevent loading page
var loc = this.id.toUpperCase(); // Get value of id attr
var newContent = ''; // Build up timetable by
for (var i = 0; i < times[loc].length; i++) { // looping through events
newContent += '<li><span class="time">' + times[loc][i].time + '</span>';
newContent += '<a href="data/descriptions.html#';
newContent += times[loc][i].title.replace(/ /g, '-') + '">';
newContent += times[loc][i].title + '</a></li>';
}
$('#sessions').html('<ul>' + newContent + '</ul>'); // Display times on page
$('#event a.current').removeClass('current'); // Update selected item
$(this).addClass('current');
$('#details').text(''); // Clear third column
});
// CLICK ON A SESSION TO LOAD THE DESCRIPTION
$('#content').on('click', '#sessions li a', function(e) { // Click on session
e.preventDefault(); // Prevent loading
var fragment = this.href; // Title is in href
fragment = fragment.replace('#', ' #'); // Add space after#
$('#details').load(fragment); // To load info
$('#sessions a.current').removeClass('current'); // Update selected
$(this).addClass('current');
});
// CLICK ON PRIMARY NAVIGATION
$('nav a').on('click', function(e) { // Click on nav
e.preventDefault(); // Prevent loading
var url = this.href; // Get URL to load
$('nav a.current').removeClass('current'); // Update nav
$(this).addClass('current');
$('#container').remove(); // Remove old part
$('#content').load(url + ' #container').hide().fadeIn('slow'); // Add new
});
});
HTML:
<section id="content">
<div id="container">
<h2>Upcoming Events in Yorkshire</h2>
<div class="third">
<div id="event">
<a id="sh" href="sh.html"><img src="img/sheffield.fw.png" alt="Sheffield, South Yorkshire" />Sheffield</a>
<a id="hu" href="hu.html"><img src="img/hull.fw.png" alt="Hull, East Yorkshire" />Hull</a>
<a id="ls" href="ls.html"><img src="img/leeds.fw.png" alt="Leeds, West Yorkshire" />Leeds</a>
<a id="yk" href="yk.html"><img src="img/york.fw.png" alt="York, West Yorkshire" />York</a>
</div>
</div>
<div class="third">
<div id="sessions">
<p>Select an event from the left</p>
</div>
</div>
<div class="third">
<div id="details"></div>
</div>
</div><!-- #container -->
</section><!-- #content -->
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/events.js"></script>
So the result I want to see is to click on the group of exercises e.g. Arms, which will open next exercises e.g. Biceps and then onclick I want to see programme with pictures. But I cannot find out how to change JS so it will give me what I want. Spent on it already 13 hrs and still cannot find anything online.
If something is not clear please let me know as I am still learning how to use overflow.
Thanks in advance!
This is for PHP website with an use of JS, MySQL, Google API and HTML of course.
Edit:
If it was not too clear, I want to get MySQL data to JSON (which I have done already)
[
{
"prog_id": "1",
"catg": "chest",
"name": "Chest",
"exer": "Three exercises per muscle group. Chest: Bench Press (3 sets of 10), Chest cable fly(3 sets of 10) and dumbbell fly (3 sets of 10)",
"pic": "abs.jpg"
}
]
And now I want to use it in AJAX in way of: on page I want to see Groups - 'catg' which on click will open list next to group on the same page with Muscle to train 'name' which afterwards open last list next to previous also on the same page showing Descirption 'exer' and Picture/s 'pic'. Just like in the picture below:
I think your problem is that you don't know how to get data from MySQL to JSON in PHP, then get that JSON into Javascript in a form that lets you manipulate it easily.
Here's how I do it. The key here is the use of str_replace.
PHP, using my own SQL() function to retrieve the result set via fetch_all(MYSQLI_ASSOC):
$subcategorydata =
SQL("select * from subcategoryoptions order by category, subcategoryoption");
$subcategories =
str_replace('\\"','\\\\"',
str_replace("'","\'",
json_encode($subcategorydata)));
Javascript (direct rather than via ajax in my case):
var subcategories = '<?php echo $subcategories; ?>';
var jsonSubcategories = JSON.parse(subcategories);
for (var row in jsonSubcategories) { ....
EDIT: Additional code to load 2 layers, toggling the display of the lower level on/off according to user clicks. This version assumes you've pulled all the data out of MySQL in one go (I've just hard-coded it) - you would probably want to use ajax to load stuff dynamically in practice - and my code is definitely not optimal, but it should do the job.
Main div into which the data is loaded is followed by the javascript to load it. Note the hide(), show(), toggle() and set() functions and the onclick.
<div id=main></div>
<script>
function set(div, value) {
document.getElementById(div).innerHTML = value;
}
function hide(div) {
var x = document.getElementById(div);
x.style.display = "none";
}
function show(div) {
var x = document.getElementById(div);
x.style.display = "block";
}
function toggle(div) {
var x = document.getElementById(div);
if (x.style.display === "none") { show(div); } else { hide(div); }
}
var json='[{"heading":"This is the first heading","detail":"This is the first detail"},{"heading":"This is the second heading","detail":"This is the second detail"}]';
var jsonData = JSON.parse(json);
var html = '';
for (var row in jsonData)
{
html += '<div id=hdr' + row + ' onclick=toggle(\'dtl' + row + '\')>';
html += '<b>' + jsonData[row].heading + '</b></div>';
html += '<div id=dtl' + row + '>' + jsonData[row].detail + '</div>';
}
set('main','Click on the headings to toggle the detail<br>' + html);
for (var row in jsonData)
{
hide('dtl' + row);
}
</script>
you have the name of the image already in the records and you should also know, were on the server the images can be found.
You can combine this knowledge and forge a URI from path and filename

Dynamic Form with Dependent drop down

Hey Developers i'm building a application form where the user input data into the different fields. One part of the application is a dynamic form from https://github.com/wbraganca/yii2-dynamicform. Now inside the dynamic form i have a dependent drop down but when i click the [+] sign the dependent drop down change data on the first row and not the second.
Here's my code.
in my controller
public function actionLists($name)
{
$countHs= Hs::find()
->where(['hscode'=> $name])
->count();
$Hs = Hs::find()
->where(['hscode'=> $name])
->all();
if($countHs > 0)
{
foreach ($Hs as $H)
{
echo "<option value='".$H->hsproduct."'> ".$H->hsproduct."</option>";
}
}else{
echo "<option> - </option>";
}
}
and my form
<div class="col-sm-6" style="width: 135px">
<?= $form->field($modelsItems, "[{$i}]hscode")->dropDownList(
ArrayHelper::map(Hs::find()->all(),'hscode','hsproduct'),
[
'prompt'=>'',
'onchange'=>
'$.get( "'.Url::toRoute('/hs/lists').'", { name: $(this).val() })
.done(function( data ) { $( "#'.Html::getInputId($modelsItems, "[{$i}]hsproduct").'" ).html( data ); } );'
])->label('HS.Code');
?>
</div>
<div class="col-sm-6" style="width: 135px">
<?= $form->field($modelsItems, "[{$i}]hsproduct")->dropDownList(
ArrayHelper::map(Hs::find()->all(),'hsproduct','hsproduct'),
[
'prompt'=>'',
])->label('HS.Product');
?>
</div>
Im a newbie sorry for my english
Updated for your case.
What I did was I declared global variable in JS file var i and assigned 0. After the first event is fired, I increase variable i by one. Now it contains 1 in memory. Next time it will take 1 and add 1 again. And so on:
var i = 0;
$(document).on('change', 'select', function(e) {
i++;
})
Note that this will only work if you choose in each row just once and you will not come back to specific row. If you want to do something like that, you should instead get element ID's number, parse to float (instead of string) and use that number to your event script.
parseFloat($('#hs-0-hscode')[0].id.split('-')[1])
Leaving below one additional solution (but not according to yours). Just in case.
Use Inspect source and find how your input fields are named (name or ID). Let's say, we have name="hs-0-hscode". This is for just Then your jQuery:
$(document).on('change', 'select', function(e) {
if ($(this)[0].id.indexOf('hscode') > 0) {
// Now you can use Ajax to get a list of items you want to show.
// Element itself can be reached: $(this).parent().parent().parent().children().eq(1);
// For example:
// var data = $.parseJSON(results);
// $.each(data, function(key, value) {
// $('#client-company_size')
// .append($("<option></option>")
// .attr("value", key)
// .text(value));
// });
}
});

How Make Div Sortable And Updating Value In Database

i want to make my divs sort-able using jquery and getting their current new position so i can update that into database. i tried but not succeed. my code is
<div id="d">
df
</div>
<div id="d">
df
</div>
<div id="d">
df
</div>
jquery code is
$(document).ready(function(){
$('#d').sortable({
placeholder: "ui-state-highlight",
helper: 'clone'
});
});
})
anyone please help me out .thanks
jQuery UI sortable feature includes a serialize method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.
$('#el1').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
It creates an array of the elements using the elements id. So, I usually do something like this:
<div id="el1" class="ui-sortable">
<div id="item_1">
df
</div>
<div id="item_2">
df
</div>
<div id="item_3">
df
</div>
</div>
Serialize option will create a POST query string like this: item[]=1&item[]=2 . So if you make use - for example - your database IDs in the id attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}

My mess that I'm trying to do with PHP, MySQL, jQuery and css

Let's see if I can explain what I'm trying to do here..
I've got a MySQL Database with some info stored in it. I am using PHP to query the database, pull my selected entries out, put each one into a separate <div> (with Bootstrap framework). I have accomplished this part.
Below is a snippet of what I'm doing...
$query = "SELECT `quote`,`id` FROM `db`";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
echo ' <div class="panel panel-info">
<div class="panel-body text-muted" id="'.$row['id'].'">
'.$row['quote'].'
</div>
</div>';
}
Then I am wanting to use jQuery to add a css class on "click" to an individual <div> and be able to then use PHP to store the text of the "selected" <div> to a variable, for later use.
This is the part I am struggling with, I can not figure out how to separate each individual <div> specifically and have jQuery add the class to it, because the "id" of div differs with every result from the db query.
To add a class to a div when it is clicked -
jQuery
$('div').click(function() {
$(this).addClass('foo');
var divText = $(this).text(); // store to JavaScript variable
});
Now that you have the JavaScript variable stored you can send it to a PHP function via AJAX.
What I would do is add a class to the <div>s, and use that to attach the event.
<div class="panel-body text-muted click-panel" id="'.$row['id'].'">
Then in your JavaScript, do something like:
$(function(){
$('div.click-panel').click(function(){
var div_id = this.id,
div_text = $(this).text();
if(/* some condition eg. div_id === 5 */){
$(this).addClass('clicked');
}
});
});

Categories