How to navigate when button, check box response - php

My code igniter web page has side bar check boxes and news articles on main panel updated from database. when i select check box i want to pass check box ID to controller and return only relevant news articles according to check box value. How to do it? What is the mechanism using here?
example web site same as i expected
<?php
foreach ($data as $add) {
echo "<div>";
echo '<p class="target">' .$add->news_data. '</p>';
echo "</div>";
}
?>

To Do that ...You have to make an ajax call "onclick" of checkbox group and then on ajax call you have to fire query with the IDs which have been passed
So,set AJAX function
$("#sidebar input[type='checkbox']").click(function(e){
var values = [];
$( "input[name='post_type']:checked" ).each(function(){
values.push($(this).val());
});
var Type = values.join(", ");
$.ajax({
type: "POST",
url: "filterpost.php",
data: "typID="+Type ,
cache: false,
success: function(){
alert("success");//just to check only
}
});
});
Step 2:Now create filterpost.php file
Now get the post value at the other side
$id = $_POST['typID'];
and from here fire the appropriate query using "IN" keyword
Step 3:
and pass that data to the view after that.
I can't give you the whole example directly...just follow this steps
I hope you will get solution

$('input[type="checkbox"][name="change"]').change(function() {
if(this.checked) {
// some ajax request
}
});
Similarly with plain JavaScript:
// checkbox is a reference to the element
checkbox.onchange = function() {
if(this.checked) {
// some ajax request
}
};
And your function function return an JSON as your example

Related

JQuery to change div when link created from mysql data is clicked

I have a navigation bar that is created from a MySQL table. I want to click on the link and only change the contents of two divs on the page. However, I cannot figure out the proper way to write the jQuery code.
I've attempted to include a single class for all the links and use
$(".class").click(function(){
//the code to change the div
}
But it doesn't seem to be working.
PHP code
<?php
require(__DIR__.'/dbconf.php');
require(__DIR__.'/db_functions.php');
$db_con = mysqli_connect($host, $username, $pass, $dbname);
$column = "playerName";
$table = "Players";
$condition = "";
$key = "";
$query = selectData($db_con, $column, $table, $condition, $key);
while($row=mysqli_fetch_assoc($query)){
$res[] = $row[$column];
echo "<a href = # class = 'player' name ='".$row[$column]."'>".$row[$column]."</a>";
}
mysqli_close($db_con);
?>
JQuery code
$(".player").click(function(){
var player = $(this).val()
var dataString = 'playerName'+ player;
$.ajax({
type: "POST",
url: "coin_amount.php",
data: dataString,
cache: false,
success: function(postresult){
$(".coins").html(postresult);}
});
return false;
});
It seems like this should work. That when any link with the class "players" is clicked, it should change the value of the player variable and call the coin_amount.php file. But it doesn't. What am I not understanding? I do know the ajax function is correct because I call that function on page load and it works. So it has to be something in the click function.
If player is created after the DOM has loaded, you will have to attach the click listener to the document, like so:
$(document).on('click', '.player', () => {
// execution code here
}
ADD It in the <script></script> tag in the head of page after have loaded the jquery library
Jquery code:
$(document).ready(function() {
$("#cercaButton").click(function () {
$(".divClass").load("./action/loadDdtGiornalieri.php");
});
});
In your case add the id at the link tag generated from the php code that print the menu.
I suggest you to add different ID at every link of the menu in order of load different contenent
From php you have to generate a string as
<a id="cercaButton">Cerca</a>
This is a complete example of load, including also the parameter post at the php web page
If you have to post data at the page loaded from jquery simplest code is
$(document).ready(function() {
$("#cercaButton").click(function () {
$(".divClass").load("./action/loadDdtGiornalieri.php", {
dateIn: $("#dateIn").val(),
tipoInterrogazione: $("#tipoInterrogazione").val()
});
});
});

Add a link to an online user's div, and remove for online

Right now, every time a user logs in, all the posts made by that user will turn green, while all the offline users' posts are grey.
I want to add a link to a javascript function for when the div is green, and a different link for when it's grey. I did this in php no problem but I want it to work realtime just like the color change without a page refresh.
The html
<div class="main_ads status" id="user'.$user_id.'">post</div>
status.php
header('Content-Type: application/json');
$array = array();
$res = mysql_query("SELECT * FROM `users` WHERE `status` = 1");
if(mysql_num_rows($res) > 0){
while($row = mysql_fetch_assoc($res)){
$array[] = 'user'.$row['user_id']; // this adds each online user id to the array
}
}
echo json_encode($array);
ajax code
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'status.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data.length > 0){ // if at least 1 is online
$('.status').each(function(){ // loop through each of the user posts
var userid = $(this).attr('id'); // get the user#
if($.inArray(userid, data) !== -1){ // if userid # in the returned data array set to online
$(this).css({background: '#40A547'});
} else{ // if not, set to offline
$(this).css({background: '#7f8c8d'});
}
});
} else { // if no one is online, set all to offline
$('.status').css({background: '#7f8c8d'});
}
}
});
}, 2000);
});
I tried to think of a way to do this and thought to assign a variable with a html tag that will be different for online and offline but wasn't sure how to call that variable from the ajax code into html.
All help is much appreciated!
You could make use of the wrapInner() property of jQuery. This could enclose the text place inside your div into <a></a> tags such as:
if($.inArray(userid, data) !== -1){ // if userid # in the returned data array set to online
$(this).css({background: '#40A547'});
//for the online users, you could fill in the javascript function
$(this).wrapInner('');
} else{ // if not, set to offline
$(this).css({background: '#7f8c8d'});
//over here write the link for offline users
$(this).wrapInner("<a href='www.google.com'></a>");
}
Fiddle
Do not add inline styles, use css classes.
In case the request takes longer than 2 seconds, abort it!
I suggest not using id's, mabye data-user or .user# as class
HTML
<div class="main_ads status" id="user1">post1</div>
...
<div class="main_ads status" id="user10">post10</div>
CSS
.online{
background:red;
padding:3px;
}
JQUERY
var global_ajax_request = null;
$(document).ready(function() {
setInterval(function(){
if (global_ajax_request){
global_ajax_request.abort();
}
global_ajax_request = $.ajax({
url: 'ajax.php',
dataType: "json",
type: 'GET',
success: function(data) {
$('.status').removeClass('online');
for(var i in data){
$('#'+data[i]).addClass('online');
}
}
});
}, 2000);
});
$('.status').on('click',function(e){
e.preventDefault();
if ($(this).hasClass('online')){
alert('function for ONLINE');
}else{
alert('function for OFFLINE');
}
});
Explanations:
global_ajax_request holds the reference to a request. Just before launching a new one, kill the old one. (!) This will make the browser not listen for a response, but the server will continue to work.
Each time you get a response, clear the online class and add it only to the returned userId's. (This should be Optimized.)
The last bit $('.status').on(...) will be fired each time someone clicks on a div. Then inside you see if it's green (online) or not and launch the appropriate function.

jquery post data to a php script and display it immediately in the same php script file

How to post data to a php script (showitemid.php) using ajax and open the same script (showitemid.php) immediately in a thickbox on a hyperlink click and display that posted data. Below is my code:
postitemid.php
This file consists of multiple check-boxes. The user will tick the checkboxes and click a hyperlink. On clicking the hyperlink all the selected check-box values would be posted to showitemid.php and then immediately showitemid.php would open in a thickbox and display the received values. But it isn't receiving any values in my code ? Need help.
$('#showitem).click(function()
{
var data = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
$.ajax({type: 'POST',
url: 'showitemid.php',
data: data,success: success,dataType: dataType});
});
showitemid.php
$data = '';
if (isset($_POST['data']))
{
$data = $_POST['data'];
}
elseif (isset($_GET['data']))
{
$data = $_GET['data'];
}
echo 'd='.$data;
use something like this
$('#showthickbox').click(function()
{
var data = $('input:checkbox:checked').map(function() {
return this.value;
}).get();//your code
$.post("showitemid.php",{data:data},function(data){
$("#thickbox").html(data);
})
})
})
in your showitemid.php
echo "your data";
The main problem with the original code is the data being sent has no key named data to match $_POST['data']) so $_POST['data']) is empty. You have to send key/value pairs, you are only sending a value with no key. You are likely getting a bit confused since you use the same variable name constantly
var dataArray = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
var dataToServer= { data : dataArray} /* now have the key to match $_REQUEST in php */
Now can use AJAX shorthand method load() to populate content
$('#myContainer').load( "yourfile.php", dataToServer, function(){
/* new html exists run open thickbox code here*/
})

Building a form dynamically

I have a drop down menu, that a user selects a criteria from, based on the criteria a form gets built.
What I am trying to do now is make sure they cannot build the same for twice, so for example, if the users selects appearance from a dropdown, I do not want them to be able to select appearance from the dropdown, while that form is built.
Does that make sense? Currently here is my code,
$('img.toggleadd').live({
click: function() {
var rowCount = $("#advanced_search > table > tbody > tr").length;
f(rowCount < 3) {
$.ajax({
url: site_url + 'ajax/row/empty',
success: function(data) {
console.log($(this));
$('#advanced_search table').append(data);
}
});
}
}
});
and the PHP
public function row($name) {
if ($this->input->is_ajax_request()) {
return $this->load->view('search/rows/'.$name);
}
}
$name relates to the name of a view which contains the corresponding form elements for the selected value.
As Jared mentioned, the solution could be something as simple as a boolean value indicating whether or not a request is in progress...
Take this code for example -
var request_in_progress = false;
$("#selector").on('change',function(){
if (!request_in_progress){
request_in_progress = true;
$.ajax('/path_to_ajax_module.php',{'data':data},function(response){
// handle the AJAX response
request_in_progress = false; // AJAX request complete.
},'json');
}
});

jQuery/JavaScript ajax call to pass variables onClick of div

I am trying to pass two variables (below) to a php/MySQL "update $table SET...." without refreshing the page.
I want the div on click to pass the following variables
$read=0;
$user=$userNumber;
the div Basically shows a message has been read so should then change color.
What is the best way to do this please?
here's some code to post to a page using jquery and handle the json response. You'll have to create a PHP page that will receive the post request and return whatever you want it to do.
$(document).ready(function () {
$.post("/yourpath/page.php", { read: "value1", user: $userNumber}, function (data) {
if (data.success) {
//do something with the returned json
} else {
//do something if return is not successful
} //if
}, "json"); //post
});
create a php/jsp/.net page that takes two arguments
mywebsite.com/ajax.php?user=XXX&secondParam=ZZZZ
attache onClick event to DIV
$.get("ajax.php?user=XXX&secondParam=ZZZZ". function(data){
// here you can process your response and change DIV color if the request succeed
});
I'm not sure I understand.
See $.load();
Make a new php file with the update code, then just return a json saying if it worked or not. You can make it with the $.getJSON jQuery function.
To select an element from the DOM based on it's ID in jQuery, just do this:
$("#TheIdOfYourElement")
or in your case
$("#messageMenuUnread")
now, to listen for when it's been clicked,
$("#messageMenuUnread").click(function(){
//DO SOMETHING
}
Now, for the AJAX fun. You can read the documentation at http://api.jquery.com/category/ajax/ for more technical details, but this is what it boils down to
$("#TheIdOfYourImage").click(function(){
$.ajax({
type: "POST", // If you want to send information to the PHP file your calling, do you want it to be POST or GET. Just get rid of this if your not sending data to the file
url: "some.php", // The location of the PHP file your calling
data: "name=John&location=Boston", // The information your passing in the variable1=value1&variable2=value2 pattern
success: function(result){ alert(result) } // When you get the information, what to do with it. In this case, an alert
});
}
As for the color changing, you can change the CSS using the.css() method
$("#TheIdOfAnotherElement").css("background-color","red")
use jQuery.ajax()
your code would look like
<!DOCTYPE html>
<head>
</head>
<body>
<!-- your button -->
<div id="messageMenuUnread"></div>
<!-- place to display result -->
<div id="frame1" style="display:block;"></div>
<!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
//attach a function to messageMenuUnread div
$('#messageMenuUnread').click (messageMenuUnread);
//the messageMenuUnread function
function messageMenuUnread() {
$.ajax({
type: "POST",
//change the URL to what you need
url: "some.php",
data: { read: "0", user: "$userNumber" }
}).done(function( msg ) {
//output the response to frame1
$("#frame1").html("Done!<br/>" + msg);
});
}
}
</script>
</body>

Categories