Refresh $(document).ready in JavaScript - javascript

I have a script that runs continuously on my page, and it detects if a new item has been submitted to my database, at which point it adds additional html to my page:
var count_cases = -1;
setInterval(function(){
$.ajax({
type : "POST",
url : "new_lead_alerts_process.php",
dataType: 'json',
cache: false,
success : function(response){
$.getJSON("new_lead_alerts_process.php", function(data) {
if (count_cases != -1 && count_cases != data.count) {
//add new HTML element to page
$('#content').prepend("<div class=\"reportRow\"><div id=\"reportRowLeft\" style=\"width: 63px;\">"+dayOfMonth+"</div><div id=\"reportRowCenter\">"+timeSubmitted+"</div><div id=\"reportRowRight\" style=\"width: 126px;\"><div id=\"claimButton"+data.id+"\"><form action=\"\" method=\"post\" name=\""+data.id+"\"><input type=\"hidden\" id=\"lead_id"+data.id+"\" name=\"lead_id\" value=\""+data.id+"\" /><input type=\"hidden\" id=\"client_id"+data.id+"\" name=\"client_id\" value=\""+data.client_id+"\" /><input type=\"hidden\" id=\"user_id"+data.id+"\" name=\"user_id\" value=\"1\" /><input type=\"image\" name=\"submit\" class=\"claimButton\" onClick=\"expand('claimed"+data.id+"');collapse('claimButton"+data.id+"');\" src=\"images/claim.gif\" id=\""+data.id+"\" style=\"width: 126px; height: 29px; margin: 0; border: 0px; padding: 0; background: none;\"></form></div><img id=\"claimed"+data.id+"\" style=\"display: none;\" src=\"images/claimed.gif\" /></div><div id=\"clear\"></div></div>");
}
count_cases = data.count;
});
}
});
},1000);
I have another script that submits an update to the database via AJAX when a user clicks a button in the newly created element. It looks like this:
//update db when lead is claimed
$(document).ready(function(){
$(".claimButton").click(function(){
var element = $(this);
var Id = element.attr("id");
var client_id = $("#client_id"+Id).val();
var user_id = $("#user_id"+Id).val();
var lead_id = $("#lead_id"+Id).val();
var dataString = 'client_id='+client_id+'&user_id='+user_id+'&lead_id='+lead_id;
$.ajax({
type: "POST",
url: "new_lead_alerts_update.php",
data: dataString,
cache: false
});
return false;});
});
My issue, is that the second AJAX submit doesn't appear to be working. I think this is due to the fact that the $(document).ready command only fires when the page first loads, and due to the fact that I'm updating the page content dynamically via AJAX, any new elements added to the page can't be submitted.
I've tried .delegate and .live, as opposed to .ready and neither appeared to work.
Any help would be greatly appreciated.

Make the functionality from document.ready into a callback, and then do that every time you append a new element to the page from ajax like this:
$(document).ready(function(){ MakeClaim(); });
function MakeClaim(){
$(".claimButton").click(function(){
var element = $(this);
var Id = element.attr("id");
var client_id = $("#client_id"+Id).val();
var user_id = $("#user_id"+Id).val();
var lead_id = $("#lead_id"+Id).val();
var dataString = 'client_id='+client_id+'&user_id='+user_id+'&lead_id='+lead_id;
$.ajax({
type: "POST",
url: "new_lead_alerts_update.php",
data: dataString,
cache: false
});
return false;});
}
success : function(response){
$.getJSON("new_lead_alerts_process.php", function(data) {
if (count_cases != -1 && count_cases != data.count) {
//that huge string
MakeClaim();
}
count_cases = data.count;
});
}
EDIT
try changing this:
onClick=\"expand('claimed"+data.id+"');collapse('claimButton"+data.id+"');\"
to
onClick=\"expand('claimed"+data.id+"');collapse('claimButton"+data.id+"');return false;\"

Please try this:
function TryIt(getId)
{
var element = $(getId);
var Id = element.attr("id");
var client_id = $("#client_id"+Id).val();
var user_id = $("#user_id"+Id).val();
var lead_id = $("#lead_id"+Id).val();
var dataString = 'client_id='+client_id+'&user_id='+user_id+'&lead_id='+lead_id;
$.ajax({
type: "POST",
url: "new_lead_alerts_update.php",
data: dataString,
cache: false
});
}
just use javascript onclick function in claimButton and call TryIt() function whenever you want.

Related

Update image after it's been clicked, without reloading page

I'm making this Flag/Unflag system, and it works okay. The only thing I'm struggeling with is how to update the Flag_icon, after it's been clicked? It's should be so it just changes after it's been clicked, and if it's clicked again then it changes back. Right now I have to click the flag, and then reload the page manually, and then it's changed.
$FlagStatus[$count] has the value YES/NO, from my database, and $testjobids[$count] is a unique ID from db table. I've been looking at some Ajax and Javascript to do this, but i can't seem to wrap my head around how to implement it right. I just need to be pointed into the right direction, because I'm a bit stuck.
Index.php
if ($FlagStatus[$count] == ('YES')) {
echo'<img class="Unflagging" onclick="changeImage('.$testjobids[$count].')" id="'.$testjobids[$count].'" data-id = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagMarked.png">';
} elseif($FlagStatus[$count] == ('NO')){
echo'<img class="Flagging" onclick="changeImage()" id="'.$testjobids[$count].'" data-id2 = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagUnmarked.png">';
}
Flagging.php / Almost same as Unflagging.php
<?php
require("../resources/MysqliHandler.class.php");
require("../resources/layoutfunctions.php");
require("GetData.php");
$ICON_DIMENSION = "16px";
// Used to connect the right server Testreportingdebug or Testreporting
$db = ServerConn();
// -------------------------------------
$MysqliHandler = new mysqliHandler($db);
$MysqliHandler->query("SET NAMES UTF8");
$receiver = $_POST["FlagID"];
$MarkYes = "UPDATE `testreportingdebug`.`testjob` SET `FlagStatus` = 'YES' WHERE id = $receiver";
$query = $MysqliHandler->query($MarkYes);
?>
Ajax
echo'
<script type="text/javascript">
$(document).on("click", ".Unflagging", function(){
var FlagID = $(this).data("id");
$.ajax({
method: "post",
url: "unflagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
$(document).on("click", ".Flagging", function(){
var FlagID = $(this).data("id2");
$.ajax({
method: "post",
url: "flagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
</script>
';

How to attach javascript to a font awesome icon

I have a fontawesome icon in my HTML as a button and i'd like to use javascript and trigger it AJAX style
<i id="heart" class="jam jam-heart-f"></i> Like
Here is the attempt at javascript to trigger it - but I dont get any errors to follow up on. I try to post the like attempt to a PHP page like.php to add the link to a database.
$(document).ready(function()
{
$('body').on("click",'#heart',function()
{
var videoId = "<?php echo $video_id; ?>";
var A=$(this).attr("id");
var B=A.split("like");
var messageID=B[1];
var C=parseInt($("#likeCount"+messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {videoId: videoId},
cache: false,
success: function(result){
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
}
});
I dont think #heart seems to be triggered in JS by the id="heart" with the font awesome icon. Any ideas how I can rig this together
You forgot to add closing parenthesis and semicolon for your $('body').on... statement
Try this:
$(document).ready(function()
{
$('body').on("click",'#heart',function()
{
var videoId = "<?php echo $video_id; ?>";
var A=$(this).attr("id");
var B=A.split("like");
var messageID=B[1];
var C=parseInt($("#likeCount"+messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {videoId: videoId},
cache: false,
success: function(result){
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
});
});
Your code triggers the post-request correctly, but you are not closing your functions and scopes correctly.
I tried it out here:
http://jsfiddle.net/4cohrz5p/
And code to keep stackoverflow happy:
$(document).ready(function() {
$('body').on("click", '#heart', function() {
var videoId = "<?php echo $video_id; ?>";
var A = $(this).attr("id");
var B = A.split("like");
var messageID = B[1];
var C = parseInt($("#likeCount" + messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {
videoId: videoId
},
cache: false,
success: function(result) {
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
});
});
Besides, the javascript console shows Uncaught SyntaxError: missing ) after argument list for your code. And you open the network-tab when you click the heart to see outgoing requests and can inspect them to see that they send the correct data (and the response too!).
Any decent js editor would have shown this error before even running the code. Try VS Code. Free and lightweight and pretty great overall.

Retrieving data from myapifilms.com api

I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});

jquery script runs only if page refresh

i have a button with the folowing code
<button type="button" class="btn btn-success btn-xs vote up" id="76" name="up"><span class="glyphicon glyphicon-thumbs-up"></span> Bueno</button>
the button does not work unless i reload the page, and i dont know why. any ideas?
jquery code is at the beginning of the body
jquery
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var _this = this;
if(name=='up')
{
$(this).fadeIn(600).html('<span class="glyphicon glyphicon-ok"></span>');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
$( _this ).remove();
$( ".escondido" ).css( "display", "block" );
} });
return false;
});
});
</script>
If the jQuery code is at the beginning of the code (before the HTML) as you state, the DOM would not have been created yet. Try moving the jQuery code to the bottom of the body (after the HTML).
I would assume you're getting an error in the button click event. Have you tried using the live('click') instead? Can you demonstrate the issue using JSFIDDLE?
In the jsFiddle I created, I'm seeing syntax errors - Original Code
If I change the code to Edited jsFiddle:
$(function () {
$(".vote").click(function () {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id=' + id;
var parent = $(this);
var _this = this;
if (name == 'up') {
$(this).fadeIn(600).html('<span class="glyphicon glyphicon-ok"></span>');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function (html) {
parent.html(html);
$(_this).remove();
$(".escondido").css("display", "block");
}
});
return false;
}; // Removed ) from this line
});
}); // Added this whole line

JS/AJAX Auto submit form: Disabling enter key to prevent page refresh

I am using a function that will submit with ajax and without the help of a button click. But I am currently undergoing two issues which with trial and error haven't found plausible solutions:
First is there any way I can disable the enter button click(this causes the whole page to refresh)?
JSFIDDLE basic example in how the JS function works
Second, It feels like I am going the roundabout way to display what has been posted. How can I change this part of the function $('#special').html('<p>' + $('#resultval', result).html() + '</p>'); to have it POST just inside a div called #special without the need of span or <p> #resultval?
Everytime i echo through php I have to do set it like this to display a result: <div id="special"><span id="resultval">This is the result.</span></div>
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});
</script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(event){// the function call on click or on submit onclick=submitForm(event);
event.preventDefault(); //to prevent enter key
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').text(result); //you can use text() or html() only
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});

Categories

Resources