I need to execute the following code, without refreshing the page... this code already includes ajax but where am I going wrong with getting it to execute without refreshing the page....? the .vote class is attatched to an anchor in my index.php file, and I need this all to still work when the anchor is clicked if possible. Re-coding this to perform on a button click would not be ideal.
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,
success: function(html){
parent.html(html);
}
});
}
else
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "down.php",
data: dataString,
cache: false,
success: function(html){
parent.html(html);
}
});
}
});
here is the html from my index.php
<div id="main">
<div id="left">
<span class='up'><img src="up.png" alt="Down" /></span><br />
<?php echo $totalvotes1; ?><br />
</div>
<div id="message">
<?php echo $message1; ?>
</div>
<div class="clearfix"></div>
</div>
<div id="main">
<div id="right">
<br />
<?php echo $totalvotes2; ?><br />
<span class='down'><img src="down.png" alt="Down" /></span>
</div>
<div id="message">
<?php echo $message2; ?>
</div>
<div class="clearfix"></div>
</div>
You need to either enclose your code with $(document).ready(function() {});, or stick your code at the end of the <body> tag. Personally, instead of making the browser parse synchronous javascript before the DOM has loaded (in the <head> section), I stick it near the end. This is also what Bootstrap recommends.
Without a DOM loaded, there are no elements created for jQuery to register Events with, and so your code literally sits there doing nothing after being parsed.
Aside from that, the .click() function is executed on click. It doesn't matter what element it's bound to. If it's clickable, it's executable.
Also to answer your question properly: <a href=""> will refresh the page. You want to use
<a href="#">. This, however, will make you jump to the top of the page. You could also define a <label> and use #labelname instead to avoid this. Or just don't use href at all. It's not needed.
Also, a little trick for echoing variables into HTML is to use <?= $var ?>
Related
jquery mobile app, how can I load other domain web page
i tried iFrame but then having mobiles size problem
i tried PHP file_get_contents the page load but the internal link/script doesn't work
any idea ??
thanks
here is my code
HTML:
<div data-role="header">
<a href="#home" data-role="button" data-inline="true" data-icon="home" >home</a>
<h1>lists</h1>
</div>
<div data-role="content">
<div id="listDetail" style="height:100%;width:100%">
</div>
</div>
JS
var list_url= 'http://lists.php';
$.ajax({
type: 'GET',
data: {area: areaID },
url: list_url,
dataType: 'html',
success: function(result){
$("#listDetail").html(result);
}
});
PHP
echo file_get_contents("http://m.booking.com/searchresults.html?aid=123456&lang=en&lang=en&latitude=55&longitude=56&radius=40");
The link tag "a" may contains the url like this href="/searchresult....." you can replace all or append all link with like this
$content = file_get_contents("http://m.booking.com/searchresults.html?aid=123456&lang=en&lang=en&latitude=55&longitude=56&radius=40");
$content = str_replace ('href="/','href="http://m.booking.com/"',$content);
echo $content;
Similarly watch all link and make it correct path
OK here is my code
portfolio.php
<select name="portfolio" id="portfolio_dropdown" class="service-dropdown">
<?php foreach($years as $year){ ?>
<option value="<?php echo $year['year']; ?>"><?php echo $year['year']; ?></option>
<?php } ?>
</select>
<div class="loading"></div>
<div id="portfolio">
<div id="port-cont">
<?php foreach($portfolios as $portfolio){ ?>
<div class="video">
<div class="play">
Play
</div>
<iframe src="http://www.youtube.com/v/<?php echo $portfolio['url']; ?>"frameborder="0" allowfullscreen></iframe>
<h3><?php echo $portfolio['title']; ?></h3>
<p><?php echo $portfolio['text']; ?></p>
</div>
<?php } ?>
</div>
</div>
my js code
$("body").on('change','#portfolio_dropdown',function(){
var year = $(this).val();
$.ajax({
type: "POST",
url: "catalog/controller/portfolio.php",
data: "year="+year,
beforeSend: function(){
$(".loading").show();
$("#portfolio").empty();
},
success: function(portfolio_data){
$(".loading").hide();
$("#portfolio").html(portfolio_data);
}
});
});
my portfolio controller file
if(isset($_POST['year'])){
include_once "../../system/validation.php";
include_once "../model/DataBase.php";
include_once "../model/Display.php";
$year = integer($_POST['year']);
$get_portfolio_data = new Display("portfolio");
$portfolios = $get_portfolio_data->getDataByColumnName("year",$year);
include_once "../view/themes/default/template/portfolio_data.php";
exit();
}
My portfolio file "the first one " i get my data with another function that i get my last year(2014) portfolio data
so when i change the year i call my controller file to get the data related to that year
my question here is how to return $portfolios that i got from my controller file so i don't have to change my template file code or include another file as i did
i mean i need to reload my portfolio.php template content
i tried something like this
$("body").on('change','#portfolio_dropdown',function(){
var year = $(this).val();
$.ajax({
type: "POST",
url: "catalog/controller/portfolio.php",
data: "year="+year,
beforeSend: function(){
$(".loading").show();
$("#portfolio").hide();
},
success: function(portfolio_data){
$(".loading").hide();
$("#portfolio").show().load("portfolio" + " #port-cont");
}
});
});
but i don't know how to send my new $portfolios data to the same div without including another template file
Actually i'm little confused how to do this properly
So i hope you got what i want to do :)
You can create a separate portfolio-div.php file that only contains the code you want to replace with, and call that from the $.ajax call.
Or you can add a $_GET parameter like ?skiptemplate=1 to portfolio.php so that when you call the file with that parameter, the surrounding template markup is skipped when the file is called from an ajax call.
If you do not have the opportunity to change the server-side code, you can load the whole template file again, but extract only the #port-cont part to replace the existing content. Don't use load() (which itself will call an URL), use html() instead:
$("#portfolio").show().html(portfolio_data);
(though this will insert all HTML, not only the #port-cont part)
$("#portfolio").html(portfolio_data)
Just pass the parameter into html
I have to get the value of something when I press an accordion div. This div=" accordion" has this structure:
<div class="accordion">
<? if ($_SESSION[SITE]['user']['id'] == $message['yp_from']) { ?> <div class="row"><span class="bold">From: </span> <span>Me</span>
<span class="grey9"> <?= $this->tools_lib->date_format($message['yp_time']); ?></span>
<? } else { if ($message['yp_state_from'] == 0) {?>
<div class="row"><span class="bold">From: </span><span><?= $this->tools_lib->name_separate($message['yp_name']) ?></span>
<div id="idMens<?= $message['id'] ?>" style="display:none;" class="showNew"><?= $message['id'] ?></div></span>
<h5 id="new"> New </h5>
<?} else { ?>
<div class="row"><span class="bold">From: </span><span><?= $this->tools_lib->name_separate($mensaje['yp_name']) ?></span>
<? }
} ?>
</div>
<p><?= $message['yp_message'] ?><p>
</div>
I want to get · $mensaje['id'] · value from the "div id="idMens"". I was trying to do it with jquery. but I have problems to get the correct value, it always take the first item value, I mean the last dinamically typed.
Im trying to use this jquery code. but I think is not well formed code..
<script>
$(document).ready(function(){
$('.accordion').find('div').click(function(){
$(this).next().slideToggle();
$('.showNew').on('click', function() {
var idm =this.id;
});
var form_data = {
to: $('#',idm).html()
}
$.ajax({
url: _baseurl+""+_lang+"/messages/updateState/", // ruta del controlador y accion
type: 'POST',
data: form_data,
success: function(data){
$('#new').hide();
}
});
}).next().hide();
});
</script>
Thank you!
Finally I did it. I'm fool... it was so easy. I was in the wrong way.
I did it creating other function:
function changeState(id){
var form_data = {
to: id
}
$.ajax({
url: _baseurl+""+_lang+"/messages/updateState/", // ruta del controlador y accion
type: 'POST',
data: form_data,
success: function(data){
$('#new').hide();
}
});
}
And calling it in the first div. with onclick. I pass the dinamic id as a parameter and therefore I can use it well.
Thank you
I am trying to figure this out and I think I am almost there but I am stuck figuring out how to use the variables properly.
I am making a page that allows a user to vote on one of three color M&Ms. By clicking the picture of one of the M&M's on the main html page, your vote will be carried over to a php page using JQuery/AJAX, and the PHP page will then update teh DBase.
My PHP page and Dbase are fine. I am stuck trying to figure out how exactly I can format my HTML page to send over the proper info to my php page so that when the red M&M is clicked, that info will go, the blue, etc etc.
Here are my HTML links:
<div id="red">
<img src="images/red.jpg" width="100%" />
</div>
<div id="blue">
<img src="images/blue.jpg" width="100%" />
</div>
<div id="green">
<img src="images/green.jpg" width="100%" />
</div>
and I want to send these over to my PHP page using JQuery and AJAX to then receive the updated vote counts. How would I formulate the AJAX/jQuery command so that when each link is clicked it sends over the color for that link? I dont need exact code here, just a pointer or two will help.
HTML:
<div id="red" data-color="red" class="answer">
...
</div>
<div id="blue" data-color="green" class="answer">
...
</div>
<div id="green" data-color="blue" class="answer">
...
</div>
JS:
$('.answer').click ( function (e) {
var color = $(this).attr("data-color");
$.ajax({
url: '/your/relative/endpoint',
type: 'POST',
data: '{ color: "'+color+'" }',
success: function (res) {
...
},
error: function (jqXHR) {
...
}
})
})
This will track each color and make the request to your server on click with the appropriate color. Remember that you should sanitize the input server side.
attach a click handler to each of the anchors
in your ajax request send the id of the parent div as a post parameter
Once the request is complete, update the corresponding div with the count from the result
Nick's answer is good just thought I would give you one more option:
<div id="red">
<a href="/vote.php?color=red" class='vote'><img src="images/red.jpg" width="100%" /></a>
</div>
<div id="blue">
<a href="/vote.php?color=blue" class='vote'><img src="images/blue.jpg" width="100%" /></a>
</div>
<div id="green">
<a href="/vote.php?color=green" class='vote'><img src="images/green.jpg" width="100%" /></a>
</div>
Javascript / jquery:
$('.vote').click(function() {
$.ajax({
type: 'POST',
url: $(this).attr('href'),
cache: false,
success: function(resp){
}
});
return false;
});
Is simple.
/****** JQUERY *******/
/**
* SEND NEW VOTE
* #param int color id of color
*/
function SendVote(color){
var count = '';
if( color == 1){
count = 'red';
}
if( color == 2){
count == 'blue';
}
if( color == 3){
count == 'green';
}
//send data via ajax,
var queryParams = {'color':color};
$.ajax({
data: queryParams,
type: "post",
url: 'path/to/vote.php'
beforeSend: function(){ // here you could add a loader (if you want)
//show loader
},
success: function(response){ // success here you get the response from the server
//response is not empty
if( response.length > 0){
$("#"+count+' span').html(response+' votes'); // then change the number of the counter
}else{
//and error on php, cause there response but is empty
}
},
fail: function(e){ //get fail ajax errors
console.log('fail '+e);
},
error: function(e){ // get errors
console.log('error '+e);
}
});
}
/*** ON vote.php (or your php script) *****/
if( isset($_POST['color']) ){
//do the things to add the new vote
//then echo the total of votes for the color
echo getVotes($_POST['color']); //this is the response that ajax will get
}
/********** html *******/
<div id="red">
<img src="images/red.jpg" width="100%" />
<span>
5 votes
</span>
</div>
<div id="blue">
<img src="images/blue.jpg" width="100%" />
<span>
4 votes
</span>
</div>
<div id="green">
<img src="images/green.jpg" width="100%" />
<span>
0 votes
</span>
</div>
i am building a mpe player for my production website, using the jplayer. the problem i have is i give my visitors the full song to listen to and for that reason i have to attempt to secure my music so heres the problem. jplayer requires a string that is a file location to the track that is to be played. i would like to make a ajax call and return that location. i tried to return a varible after a ajax call to be placed in the string location,but the code runs threw before the call is finish....
heres my code:
html markup:
<div id="player"></div>
<!-- Using the cssSelectorAncestor option with the default cssSelector class names to enable control association of standard functions using built in features -->
<div id="jp_container" class="demo-container">
<p>
<div class="pro"></div>
<span class="play-state"></span> : <span class="track-name">nothing</span><br />
of <span class="jp-duration"></span>, which is
<span class="jp-current-time"></span><br />
</p>
<ul class="toolbar ui-widget-header ui-corner-all">
<li><button class="jp-Prev" href="#">Prev</button></li>
<li><button class="jp-play" href="#">Play</button></li>
<li><button class="jp-pause" href="#">Pause</button></li>
<li><button class="jp-stop" href="#">Stop</button></li>
<li><button class="jp-Next" href="#">Next</button></li>
<li><button class="jp-mute" href="#">Mute</button></li>
<li><button class="jp-unmute" href="#">Unmute</button></li>
<li><div class="jp-volume-bar"></div></li>
</ul>
<ul class="playlist">
<li><span>Select a track :</span></li>
<? Beats(); ?>
</ul>
</div>
Jquery markup:
$("#jp_container .track").on("click",function(event) {
var x = $(this).attr('id');
var mp3File = // maybe a function can go here
my_jPlayer.jPlayer("setMedia", {
mp3: //this is where the string is expected
});
my_jPlayer.jPlayer("play");
my_trackName.text($(this).text());
$(this).blur();
return false;
});
// here is were i get the location in a function i workout already
function url(x){
var mp3;
$.ajax({
type: "POST",
url: "hosts/beats/beat.php",
data: "<?=md5('url')?>="+x+"&ok=<?=md5(rand(1,20))?>",
dataType: "html",
success:function(data){ var mp3 = data; }
});
return mp3;
}
first "A" in AJAX is for ayshnchronous...you can't return mp3 from your function because the ajax hasn't completed when you try returning it.
You need to do the setMedia within success callback of ajax
$("#jp_container .track").on("click", function(event) {
var x = $(this).attr('id');
$.ajax({
type: "POST",
url: "hosts/beats/beat.php",
data: "<?=md5('url')?>=" + x + "&ok=<?=md5(rand(1,20))?>",
dataType: "html",
success: function(data) {
my_jPlayer.jPlayer("setMedia", {
mp3: data
});
my_jPlayer.jPlayer("play");
my_trackName.text($(this).text());
$(this).blur();
}
});
return false;
});