I have a link that looks like this:
<p class="half_text">
<?php echo $upvotes; ?>
<strong><a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a></strong> |
<?php echo $downvotes; ?>
<strong><a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#">Vote Down</a></strong>
</p>
and I have the jQuery code that looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.vote_up').click(function()
{
alert("up");
alert ( "test: " + $(this).attr("problem_id") );
// $(this).attr("data-problemID").
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
//Return false to prevent page navigation
return false;
});
});
</script>
How can I get the parameter value which is problem_id ? If I add a url in the href parameter, I think the browser will just go to the url, no? Otherwise - how can I pack parameter values into the jQuery?
Thanks!
Because your $.ajax is defined in the same scope of the variable, you can use problem_id to obtain the variable value.
An overview of your current code:
var problem_id = "something"; //Defining problem_id
...
$.ajax(
...
success: function(){
...
//problem_id can also be accessed from here, because it has previously been
// defined in the same scope
...
}, ...)
....
If what you're trying to figure out is how to embed the problem ID in the link from your PHP so that you can fetch it when the link it clicked on, then you can put it a couple different places. You can put an href on the link and fetch the problem ID from the href. If you just do a return(false) from your click handler, then the link will not be followed upon click.
You can also put it as a custom attribute on the link tag like this:
<a class="vote_up" data-problemID="12" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a>
And, then in your jQuery click handler, you can retrieve it with this:
$(this).attr("data-problemID").
do you mean, getting variables from the php page posted?
or to post?
anyway here's a snippet to replace the $.ajax
$.post('/problems/vote.php', {problem_id: problem_id, action: 'up'}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
{problem_id: problem_id, action: 'up'} are the variables posted... use $_POST['problem_id'] and $_POST['action'] to process..
use simple variables names with jQuery.data and make sure you have latest jQuery..
let me try to round it up..
up
down
<script type="text/javascript">
$('.votelink').click(function() {
$.post('/problems/vote.php', {problem_id: $(this).data('problemid'), action: $(this).data('action')}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
});
</script>
Related
I want to show a comments section always. Now a user has to click, to start the javascript code to display the content (onclick). a simple change to "onload" is not working. I tried it.
//Show reviews
function reviews_show(value) {
jQuery.ajax({
type:'POST',
url:'<?php echo site_root?>/members/reviews_content.php',
data:'id=' + value,
success:function(data){
if(document.getElementById('comments_content'))
{
document.getElementById('comments_content').innerHTML = data;
}
}
});
}
html code on .tpl page:
<li>Comments</li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="comments_content"></div> </div>
If you mean with always -> on page load -> then this is the answer:
document.addEventListener("DOMContentLoaded", function(event) {
var value='{ID}'; // use value variable for your ID here
jQuery.ajax({
type:'POST',
url:'<?php echo site_root?>/members/reviews_content.php',
data:'id=' + value, // or replace to => data:'id={ID}',
success:function(data){
if(document.getElementById('comments_content'))
{
document.getElementById('comments_content').innerHTML = data;
}
}
});
});
Edit: Of course this was just an example how to make the browser to execute the jQuery.ajax on Page Loaded Completed. I edited the code and put the var value='{ID}' for your example. Make sure that there is your ID inserted (as it was inserted before in your onclick="reviews_show({ID});".
What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)
I need to click an image and it should run some php script that sets a php variable and reloads the same page.
I know it sounds simple but i've tried every different way I can think of and i'm guessing it's just something basic i've missed.
I've tried onclick of the image, a href and a onclick, making the image the 'submit button' of a form etc..
Any response would be appreciated.
<a href="#" class='lang'><img src="/images/flags/it.png" alt="it_IT" /></a>
<a href="#" class='lang'><img src="/images/flags/fr.png" alt="fr_FR" /></a>
I want the image alt value to pass it,
How it is possible please give some idea..
try this:
Lets say that the PHP variable you want to change is $my_var:
Set it like this:
if(isset($_GET['VarValue']) And !empty($_GET['VarValue'])){
//if it is passed and not empty store it
$my_var = $_GET['VarValue'];
}
else{ die(''); }//else don't let them display the page.
In the image put an On Click Listener hat call this function PHP_var();
In JavaScript add this function:
function PHP_var(){
location = "?VarValue=The_Value_That_You_Want_To_Set";
}
And the URL must be like this when you first call this page(lets say it is http://www.example.com/script.php?VarValue=The_First_Valeu_Of_Variable).
The function will change the VarValue value and will reload the page
try
$('.lang img').on('click',function(){
var lang = $(this).attr('alt');
var postdata = 'lang='+lang;
$.ajax({
type:'POST',
data:postdata,
url:'process/yourscript.php',
success:function(data){
// more processing here
}
});
return false;
});
Use onclick="ajaxFunctionName()" to call an ajax function which executes your script
<a href="javascript:;" onclick="ajaxFunctionName()" class='lang'><img src="/images/flags/it.png" alt="it_IT"/></a>
<a href="javascript:;" onclick="ajaxFunctionName()" class='lang'><img src="/images/flags/fr.png" alt="fr_FR"/></a>
function ajaxFunctionName() {
$.post({
var lang = $( this ).children('img').attr('alt');
url: "script.php?lang="+lang
}).done(function() {
// do something
});
}
or
<img class='lang' src="/images/flags/it.png" alt="it_IT"/>
$('.lang').click(function(){
$.post({
var lang = $( this ).attr('alt');
url: "script.php?lang="+lang
}).done(function() {
// do something
});
});
I'm working with AJAX on a website and I'm currently making some pages to load on a certain div: "pageContent". Now I have another content I want to be opened on another div: "reproductor". I want to open 'page' in 'pageContent' div and 'play' in 'reproductor' div. I don't know how to modify my script.js and load_page.php files in order to make it work. Here's what I got:
HTML:
<script type="text/javascript" src="js/script.js"></script>
PAGE
PLAY
<div id ="pageContent"></div>
<div id="reproductor"></div>
script.js:
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
load_page.php:
<?php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else
echo 'There is no such page!';
?>
I forgot to mention: I have my 'pages' content in a folder named 'pages' and my 'play' content in another named 'plays'.
Thanks for your help!
The easiest way to load content from a resource that serves HTML into an element is to use load:
$('#reproductor').load('public_html/plays/play_1.html', function(){
//stuff to do after load goes here
});
You could also apply this technique to the other div you are trying to load content into.
If I understand, your have two groups of links (for pages and a play list) each one to be loaded in a different container. Here is something you can try: mainly I eliminated the global variables and put the current hash inside each containter's data, and separated the management of the two groups of links.
In this code I supposed you have a separate load_play.php file. If not, then you can use the same page for both kind of links, but you'll have to merge loadPlay with loadPage, change loadPage(newHash) to loadPage(newHash, linkType) and change the ajax parameter from 'page='+newHash to 'number='+newHash+'&type='+linkType, and do the corresponding changes server side in your PHP page. I would recommend you to create two separate PHP files in order to manage the two types of content.
I remember you where doing something with the hash of the current page's url, you can still set it in the ajax's success, inside the loadPage function.
Here is a working sfiddle example with some console calls (open browser's console) but without the ajax call.
UPDATE:
I updated the code, so your can manage the dynamically added links (new content loaded via AJAX) and fixed the management of urls with hashes, which was broken because of the new code.
<div id="#page">
PAGE 1
PAGE 2
PLAY 1
PLAY 2
PLAY 3
<div id ="pageContent"></div>
<div id="reproductor"></div>
</div>
And this is the javascript:
$(document).ready(function(){
$('#pageContent').data('currentPage', '');
$('#reproductor').data('currentPlay', '');
//This will allow it to work even on dynamically created links
$('#page').on('click', '.pageLink', function (e){
loadPage(this.hash);
});
$('#page').on('click', '.playLink', function (e){
loadPlay(this.hash);
});
//And this is for managing the urls with hashes (for markers)
var urlLocation = location.hash;
if(urlLocation.indexOf("#page") > -1){
$('.pageLink[href='+ urlLocation +']').trigger('click')
}
});
function loadPage(newHash)
{
//This is the current Page
var curHash = $('#pageContent').data('currentPage');
//and this is the new one
newHash = newHash.replace('#page', '');
if(curHash===newHash){
//If already loaded: do nothing
return
}
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+newHash,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg).data('currentPage',newHash);
$('#loading').css('visibility','hidden');
}
}
});
}
function loadPlay(newHash)
{//Similar to loadPage...
var curHash = $('#reproductor').data('currentPlay');
newHash = newHash.replace('#play', '');
if(curHash===newHash){return}
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_play.php",
data: 'play='+newHash,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#reproductor').html(msg).data('currentPlay',newHash);
$('#loading').css('visibility','hidden');
}
}
});
}
Check this and comment if this is what you need, or I got something wrong :)
There are a number of reasons why the following is not an ideal solution. The most glaring would be security - by modifying the href attribute of the link before clicking it, the user can certainly get your server to serve up any html on your server.
EDIT I've removed my original answer, because I can't recommend it's usage.
As Asad suggested, you can also use jQuery load and pass it the relevant url using some of the code above
function loadPage(url)
{
// remove the hash in url
url=url.replace('#','');
// extract page or play - only works for four letter words
var contentType=url.substr(0,4);
// extract the number
var contentId=url.substr(4);
if ( $contentType == "page") {
$("#pageContent #loading").css('visibility','visible');
$("#pageContent").load($contentType+'s/'+$contentType+'_'+$contentId+'.html');
$("#pageContent #loading").css('visibility','hidden');
} else if ( $contentType == "play") {
$("#reporductor #loading").css('visibility','visible');
$("#reproductor").load($contentType+'s/'+$contentType+'_'+$contentId+'.html');
$("#reporductor #loading").css('visibility','hidden');
}
}
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>