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

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()
});
});
});

Related

How to navigate when button, check box response

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

how to call php function from jqgrid button

I'm trying when i submit a value to jqgrid box on multiple selected rows to Update the data of specific columns.My code is this but when i click OK in jqgrid nothing happens and function is not called :
jQuery(document).ready(function(){
jQuery('#list1').jqGrid('navButtonAdd', '#list1_pager',
{
'caption' : 'Resubmit',
'buttonicon' : 'ui-icon-pencil',
'onClickButton': function()
{
var str = prompt("Please enter data of Column")
var selr = jQuery('#list1').jqGrid('getGridParam','selarrrow');
$(selector).load('Updatestatus.php', {'string': str,'box[]' : selr })
},
'position': 'last'
});
});
The function that updates the column of the table:
function update_data($data)
{
// If bulk operation is requested, (default otherwise)
if ($data["params"]["bulk"] == "set-status")
{
$selected_ids = $data["cont_id"];
$str = $data["params"]["data"];
mysql_query("UPDATE out_$cmpname SET cont_status = '$str' WHERE cont_id IN ($selected_ids)");
die;
}
}
I'm new to jqgrid and Jquery.What can i do to call and execute this function when i click ok?
Thanks in advance!
You'll need a Ajax-call for this. I see you're using jQuery, have a look at http://api.jquery.com/load/
With this function, you can load PHP or HTML with jQuery to a certain element.

ie and jquery $.get not working

I am trying to update the content of a div with a $.get call but it is failing in ie(9).
the js is this
function UpdateElementOfParent(box_id, page_ref, template_ref)
{
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref } )
.done(function(data) {
$('#'+box_id).html(data);
});
}
and the get_content.php is this
<?php
include("connect.php");
$page_ref = $_GET['page_ref'];
$template_ref = $_GET['template_ref'];
$box_id = $_GET['box_id'];
$sql = mysql_query("SELECT * FROM site_content WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_id='$box_id' AND box_type='text'");
while($row=mysql_fetch_array($sql))
{
echo stripslashes($row['content']);
}
?>
it works fine in firefox/chrome/safari and opera.
the php updates the db but the div ("#"+box_id) doesnt update in ie (only have ie9 at hand so dont know if its just 9 or other versions also)
any clues?
QUICK UPDATE
it seems that ie is holding some data from a previous $.get call in the cache. Basically I have a div on the screen and when the user clicks a button, a layer opens with a textarea that is editable with nicedit.
The textarea is populated with a $.get, then the user clicks save, the layer is hidden and the original div on the parent page is updated with the same $.get call.
In ie, if I change the content, the db is updated but the div is not and when I open the layer, it still shows the old data.
the first $.get call is this
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref } )
.done(function(data) {
document.getElementById("edit_content").value=data;
area1 = new nicEditor({fullPanel : true}).panelInstance("edit_content",{hasPanel : true});
});
the alerted data doesnt show the updated text in IE so its definately something to do with the $.get call
I figured out the problem. Nothing to do with the selector, but with the scope of the parameter variable box_id.
Change your function to:
function UpdateElementOfParent(box_id, page_ref, template_ref) {
myBox = box_id;
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref })
.done(function(data) {
$('#'+myBox).html(data);
});
}
Explanation:
The AJAX callback function does not have access to the local variable in UpdateElementOfParent
This isn't an answer, as the question is incomplete, but I need to post a code comment to assist OP.
As you mentioned that the PHP works just fine, the problem might be that IE doesn't like dynamic selectors in jQuery. Do try these few options:
1) Change $('#'+box_id).html(data); to:
var id = '#'+box_id;
$(id).html(data);
2) Try logging or alert-ing the element out, to see if IE actually got the element right:
var elem = $('#'+box_id);
alert(elem);
elem.html(data);
This would display as [HTMLDivElement] or something similar if the element is there.
3) If all else fails, see if this vanilla JS works in IE, to verify that it isn't a jQuery selector problem.
var elem = document.getElementById(box_id);
alert(elem);
elem.innerHTML = data;
ok problem solved and I knew it was something very obvious.
inside the original $.get function call I have to set the document.ready state
function get_edit_content(box_id,page_ref,template_ref)
{
$(document).ready(function() { <<<<<HERE
if(area1) {
area1.removeInstance('edit_content');
area1 = null;
document.getElementById("edit_content").value="";
}
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref } )
.done(function(data) {
document.getElementById("edit_content").value=data;
document.getElementById("page_ref").value=page_ref;
document.getElementById("template_ref").value=template_ref;
document.getElementById("box_id").value = box_id;
area1 = new nicEditor({fullPanel : true}).panelInstance("edit_content",{hasPanel : true});
});
});
}
thanks for all the input

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*/
})

ajax jquery doesnt work on ie

Hey guys. I'm usign a js/ajax script that doesnt work with internet explorer. Firefox its ok.
Btw the head tag, im using this:
$(document).ready(function () {
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "http://pathfofolder/js/loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('slow');
}
});
}
The loader.php contain the php code to get pages, something like:
switch($_GET['page']) {
case '#link1' : $page = 'contenthere'; break;
}
echo $page;
So, on the links, i'm using Link 1 to load the content into the div content.
The script does works well with firefox, but with internet explorer it doesnt load the content. Could someone pls help me to fix this?
It not go into the success function at all on IE, and i'm getting no html error from IE too.
Best Regards.
Make sure your html is sounds. FF tends to auto fix the syntax.

Categories