I would like to make different news feed and trigger them on click. Currently i have different subpage on my website and when I click there it redirects me on another page, API shows the information. It looks like this.
Any ideas how i can setup same way but to trigger api on button without redirecting on another page. Ideal - I want to have a container which gonna keep different news feed and trigger different ones on click.
Sorry for lame question, novice in API's.
$(document).ready(function(){
let url = "https://newsapi.org/v2/everything?q=bitcoin&from=2020-04-01&to=2020-04-20&apiKey=APIKEY";
$.ajax({
url:url,
method: "GET",
dataType: "Json",
beforeSend: function(){
$(".progress").show();
},
complete: function(){
$(".progress").hide();
},
success: function(news){
let output = "";
let latestNews = news.articles;
for(var i in latestNews) {
output +=`
<div class="col">
<div class="card-content">
<h5>${latestNews[i].title}</h5>
</div>
</div>
<div class="published">
<h6>${latestNews[i].publishedAt}</h6>
</div>
<div class"card-reveal">
<p>${latestNews[i].description}</p>
</div>
`;
}
if(output !== ""){
$("#newsResults").html(output);
}
},
error: function(){
$("#newsResults").html("Some error occured");
}
})
});
You can add a listener to a button click using jQuery like so:
// Suppose your button has id='target'
$( "#target" ).click(function() {
your api call here
});
https://api.jquery.com/click/
Related
I would like to know how to keep a tab open after a button postback event, I could not get it to work using HiddenFields. I would like the second tab to stay open after a button click on the second tab however my code would always refresh to the first tab.
I have also tried to use an update panel instead of refreshing the entire page however the tabs would not toggle properly using this method.
I would prefer to not postback on every tab click as it affects the user experience. Is there any other codes to do this without affecting the fade aesthetics?
$(function () {
$('.tab-content:first-child').show();
$('.tab-nav').bind('click', function (e) {
$this = $(this);
$tabs = $this.parent().parent().next();
$target = $($this.data("target"));
$this.siblings().removeClass('active');
$target.siblings().css("display", "none");
$this.addClass('active');
$target.fadeIn("slow");
});
$('.tab-nav:first-child').trigger('click');
});
<ul class="tabs-nav d-flex" style="padding-left: 35px;">
<li class="tab-nav d-flex justify-content-center align-items-center" data-target="#tab_1">Overview</li>
<li class="tab-nav d-flex justify-content-center align-items-center" data-target="#tab_2">Expenses</li>
</ul>
<div id="tab_1" class="tab-content">
<p>abc</p>
</div>
<div id="tab_2" class="tab-content">
<p>abc</p>
<asp:Button ID="saveexpense" runat="server" Text="Save"/>
</div>
You may be better off creating a web method and calling that from your jQuery instead of trying something with update panels. Especially considering the performance problems update panels can cause.
You would move your save functionality into a web method like this
[WebMethod]
public static void SaveExpense(string data, string moredata)
{
//your save code here
}
and something like this in your front end
<button id="saveexpense">Save</button>
Then you can call your webmethod like this
$('#saveexpense').click(function () {
$.ajax({
type: "POST",
url: "CurrentPage.aspx/SaveExpense",
data: JSON.stringify({ data: $("#textbox").val(), moredata: $("#textbox2").val() }) ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("data saved");
},
error: function (jXHR, textStatus, err) {
console.log(err);
}
});
});
I have been trying to create a chatting system using php+ ajax + mysql.
<?php
session_start();
?>
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">You Are : <?php echo $_SESSION['name'];
?></h3><br />
<div id="live_data"></div>
</div>
<div id="messages"></div>
<div class="area" style="display:none">
<textarea id="text" name="text"></textarea>
<input type="submit" id="sub" name="sub" value="Send" />
</div>
</div>
</body>
</html>
<script>
$(document).ready(function() {
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '.first_name', function() {
var id = $(this).data("id1");
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: id
},
dataType: "text",
success: function(data) {
$('#messages').html(data);
$("div.area").show();
}
});
}
function myTimeoutFunction() {
fetch_chat();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);
fetch_chat();
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: id,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
alert(text);
});
});
});
</script>
but the problem with this code is that it worked only for the first user I chat with but the screen starting blinking frequently when I click on other users' name. for example: user 'a' is logged in and click on user 'b' and starts the chat. everything works fine till now, but when user 'a' thinks to chat with a another user 'c' the whole chat part start blinking with all chats stored in database. plz tell me where I m goin wrong.
This needs a complete rethink really, to be rid of all the potential bugs.
The problem you describe above is because you're creating a new timed interval every time someone clicks on a name, so gradually this builds up and you are requesting every few milliseconds instead of every second. This is unsustainable. There's no need really to be declaring intervals, functions etc etc within the "click" handler of the name. I think you're doing this because of the dependency on the user ID which results from selecting a name. However you can overcome that by assigning the value to a global variable.
Doing this means you can move all the functions outside the click handler, removing any danger of re-creating the same intervals / events multiple times. I've also changed it so it doesn't use an interval. Instead, fetch_chat calls itself again 2 seconds after the previous response is received. That way, if a fetch takes longer than normal, you don't have multiple competing fetch operations running in parallel and causing potential confusion. I also increased the time interval to something which is still reasonable, but won't overload the server.
Here's a complete rework of your code:
<script>
var currentID = null;
var chatTimer = null;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
fetch_chat();
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$('#messages').html(data);
$("div.area").show();
chatTimer = setTimeout(fetch_chat, 2000); //request the chat again in 2 seconds time
}
});
}
$(document).ready(function() {
$(document).on('click', '.first_name', function() {
currentID = $(this).data("id1");
//immediately fetch chat for the new ID, and clear any waiting fetch timer that might be pending
clearTimeout(chatTimer);
fetch_chat();
});
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
alert(text);
});
fetch_data(); //this will also trigger the first fetch_chat once it completes
});
</script>
P.S. If you want anything faster than 2 seconds refresh, then really you probably need to consider re-architecting the solution using websockets to get full 2-way communication, so the server can "push" chat items to the client instead of the client having to poll the server.
You are using setInterval, this is wrong, this will start a loop every time you click on a chat, you should have a single loop running over all your chats. Also consider using setTimeout instead of setInterval to ensure you get the response first.
I know My question Title is not perfectly describe my question extremely sorry about that. I don't know how to tell this as a summery. anyway this is my question.
I am making a admin panel to change some of the content in my web page. this scenario is for change slideshow images.
ok then after someone logged into my page I am loading three pages. like this.
$this->load->view('admin/header');
$this->load->view('admin/menu');
$this->load->view('admin/table_and_editor_holder');
all the page contents I have mentioned below. so basic path is like this. once someone logged he can click the button [slide manage] to load the images and details of already inserted slides. these are getting from a database. so once he clicked the menu button. this jquery function is executing.
$('.menu-item > a').on('click', function() {...})
this function simply getting a html page. filled with previous slide details. this is the controller function handle the menu request.
function slider_edit_delete() {
$sdata['slide_imgs'] = $this->admin_basic_curd->get_all_items('sider_images');
$slide_manager = $this->load->view('admin/slider_manager', $sdata, TRUE);
echo $slide_manager;
}
so previous jquery function is then appending this page content to a div like this.
$('#table_container').html(data);
so inside this page content I have a buttons call edit for each slide already inserted. so by clicking on of this button I can edit that slide image or some test content of it. that button is like this.
<a class="onclick_post_by_a" href="<?php echo base_url() . 'adm_edit_this_slide/' . $sl->id; ?>">
<button class="btn btn-info"> Edit </button>
</a>
so by clicking this button must execute this function in the header section and this function must add a html form (in a separate page) to the #editor-form-container div as previously
$('.onclick_post_by_a').on('click', function() {...})
but the problem is once I click the edit button it couldn't find this function. so it is opening the content as a separate page
How can I make this to work? Thank you
the header page contains all the css and js file links. and some jquery functions. like this.
<script>
$(document).ready(function() {
$('.menu-item > a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#table_container').html(data);
});
return false;
});
$('#editor-form-container').css({
display: "none"
});
function posting_url(url, pdata) {
return $.ajax({
url: url,
data: pdata
});
}
$('.onclick_post_by_a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#editor-form-container').css({
display: "block"
});
$('#editor-form-container').html(data);
});
return false;
});
$('.post_with_image').on('submit', (function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("success");
console.log(data);
},
error: function(data) {
console.log("error");
console.log(data);
}
});
}));
});
</script>
</head>
then I have load menu page. it is like this.
<div class="admin-navi">
<div class="menu-item">
Home
</div>
<div class="menu-item">
Side Manage
</div>
</div>
<div class="clearfix"></div>
table_and_editor_holder.php page. it is like this.
<div class="col-lg-12">
<div class="col-lg-2"></div>
<div id="table_container" class="col-lg-8">
</div>
</div>
<div id="editor-form-container" class="col-lg-6">
</div>
Dynamically created element does not respond to direct call to events like below -
$('.onclick_post_by_a').on('click', function() {...})
So you have to write like this
$(document).on('click', '.onclick_post_by_a', function() {...})
Just try it out.
I'm new to jquery and javascript and have no idea how to solve this problem: I have a simply jquery chat and there is a div with the id 'show_messages' in which I load all the messages from my ajax request. All works fine, the only problem ist, that the div for show messages gets longer and longer and I have absolutely no idea how to implement a scrollbar. I tried to use the jquery scroll function, but I hasn't worked and I don't know how to use it right. How can I make a simple scrollbar like in the facebook messenger or in similar messengers.
My Code:
<div id="message_dialog" class="message_box">
<div id="show_messages"></div>
<div id="feedback"></div>
<form action="#" method="post" id="message_form">
<label>Say something:</label>
<textarea id="message"></textarea>
<input type="submit" id="send_message" value="Send Message">
</form>
</div>
...
$(document).ready(function(){
$('#start_conversation').click(function() {
$('#message_dialog').dialog();
var interval = setInterval(function() {
$.ajax({
type : "POST",
url: 'get_messages.php',
success: function(data) {
$('#show_messages').html(data);
}
});
}, 1000);
return false;
});
});
$('#message_form').submit(function() {
var username = ...
var message = ...
$.ajax({
type : "POST",
url: 'send_message.php',
data: { 'username' : username, 'message' : message },
success: function(data) {
$('#feedback').html(data);
$('#feedback').fadeIn('slow', function() {
$('#feedback').fadeOut(6000);
});
$('#message').val('');
}
});
return false;
});
Setting a max-height property and overflow-y to auto doesn't solve the problem ?
#show_messages{
max-height:200px;
overflow-y:auto;
}
Let's say for example that a message is displayed within his proper div, you can scroll to the last message by using this function.
$("#show_messages").scrollTop($("#show_messages").children('div').last().offset().top);
I suggest to use AlternateScroll jquery plugin:
http://www.dynamicdrive.com/dynamicindex11/facescroll/
It's very useful and you can easily customize it. Hope this helps.
I have html elements with class "ajaxem" that are ment to be used in my jquery below. I also have the same for any form elements. For the first few ajax requests the jquery is attached and triggered and work properly. However, after a user logs in or registers, the returned links (which also have class="ajaxem") are not caught by jquery and not triggered.
I have tried all three implementations. and also tried to reapply them AFTER each ajax request. but none have worked.
<script type="text/javascript">
function updateajaxem() {
$(document).on("click", "a.ajaxem", function (e) {
e.preventDefault();
var action = $(this).attr('href');
//alert(action);
if (action.indexOf('register') > 0) {
$("div#logininfo").load("http://localhost/testrun/auth/register/").fadeIn();
} else if (action.indexOf('password') > 0) {
$("div#logininfo").load("http://localhost/testrun/auth/forgot_password/").fadeIn();
}
}); //end
}
</script>
<script type="text/javascript">
updateajaxem();
//$("a.ajaxem").live("click", function(e){
$(document).on("click", "input:submit", function (e) {
e.preventDefault();
var formaction = $(this).closest('form').attr('action');
var dataString = $(this).closest('form').serialize();
alert(dataString);
//$("div#logininfo").load(formaction,data);
$.ajax({
type: "POST",
url: formaction,
data: dataString,
// dataType: "json",
success: function (data) {
alert(data);
$("div#logininfo").html(data);
updateajaxem();
} // end of success
});
});
</script>
the outputted html at which the scripts stop working is below:
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
Logout Home
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the User Guide.</p>
</div>
<p class="footer">Page rendered in <strong>1.0343</strong> seconds</p>
<div id="logininfo">You have successfully registered. Login</div>
</div>
which makes no sense since it includes the class "ajaxem" which should be caught by jquery but is not.
Since the returned link's href does not contain the words 'register' or 'password' neither of the following conditions are met:
if (action.indexOf('register') > 0) {
$("div#logininfo").load("http://localhost/testrun/auth/register/").fadeIn();
} else if (action.indexOf('password') > 0) {
$("div#logininfo").load("http://localhost/testrun/auth/forgot_password/").fadeIn();
}
so no ajax request happens.
You will probably need to account for the 'login' scenario, e.g.:
} else if (action.indexOf('login') > 0) {
$("div#logininfo").load("http://localhost/testrun/auth/login/").fadeIn();
}
...and why hard-code the URLs when they can be extracted from the clicked anchor?
if (action.indexOf('register') > 0) {
$("div#logininfo").load(this.href).fadeIn();
} else if (action.indexOf('password') > 0) {
$("div#logininfo").load(this.href).fadeIn();
} else if (action.indexOf('login') > 0) {
$("div#logininfo").load(this.href).fadeIn();
}