I am making a simple website which consists of products (Laptop, CCTV). It has a single page. When I click on(Laptop tag, it should display Laptop items stored in JSON - and the same case For CCTV products.
Problem.
The first time I click on a link it does not show anything, when I click 2nd, 3rd times on link then it shows products. But preventdefault is not working.
Where should i apply preventDefault() event and how?
Html code for 2 links
<a
href="displayproducts.html" onloadeddata="fetchproducts('CCTV')";>
CCTV CAMERAS</a>
<a
href="displayproducts.html"
onloadeddata="fetchproducts('Laptop')">
Laptop and COMPUTERS</a>
JavaScript Code which handles that event and using AJAX AND JSON should return data (returning correctly).
function fetchproducts(product, event) {
console.log(product);
//your read json code
var xhr = new XMLHttpRequest();
xhr.open("get", "/jsondata/Products.json");
xhr.onload = function (event) {
console.log();
event.preventDefault();
var obj = JSON.parse(this.responseText);
try {
if (product === "CCTV") {
fillProducts(obj.CCTV);
} else if (product === "Laptop") {
fillProducts(obj.Laptop);
} else if (product == "Biometric") {
fillProducts(obj.Biometric);
}
} catch (error) {
console.log("some_error_occur");
}
};
xhr.send();
}
function fetchproducts(product, event) {
console.log(product);
var xhr = new XMLHttpRequest();
xhr.open("get", "/jsondata/Products.json", true);
xhr.onload = function () {
console.log();
try {
var obj = JSON.parse(xhr.responseText);
if (product === "CCTV") {
fillProducts(obj.CCTV);
} else if (product === "Laptop") {
fillProducts(obj.Laptop);
} else if (product == "Biometric") {
fillProducts(obj.Biometric);
}
} catch (error) {
console.log("some_error_occur: " + error);
}
};
xhr.send();
event.preventDefault();
}
Related
I've got an API that returns me {"html", "Css" and "JS"} that i'd ideally like to render on client side.
Issue:
Looks like something's failing for some reason and clicking on the button does not do anything. (I have accept button)
JavaScript:
function postAjax(success) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('GET', '/myaccount/profile/api/accept');
xhr.onreadystatechange = function() {
if (xhr.readyState > 3 && xhr.status == 200) {
success();
}
};
xhr.setRequestHeader('Accept', 'application/json', 'Content-Type', 'application/json');
xhr.send(null);
return xhr;
};
document.onreadystatechange = function() {
if (document.readyState == "interactive") {
// some logic
var cookieLanguage = document.getElementById("CookieContent_wrapper");
var cookieBanner = document.getElementById("CookieBanner");
var acceptAllButton = document.getElementById("acceptAllButton");
acceptAllButton.onclick = function() { // Does not get trigerred.
// Does not get trigerred.
// Do some logic.
};
}
};
However, acceptAllButton.onClick event is not triggerred.
This is my directive.js (angular)
populate() {
this.cookieBannerData = this.models.CookieData; // We are getting { "js", "html", "css"}
//CSS
$("head").prepend( this.cookieBannerData.css );
// HTML
let div = document.getElementById( 'cookie-banner-outerwrap' );
div.insertAdjacentHTML( 'beforeend', this.cookieBannerData.html );
//JS
$("head").append( this.cookieBannerData.js );
}
template.html
<div id="cookie-banner-outerwrap"></div>
When I click on the button, nothing happens. Is there anyway I can bind the onclick event with window so that I can get my
Trying to access yahoo weather api using ajax and jquery. Works fine if searched and submitted using submit button but i wish to search it using enter keypress only. It takes one letter at a time instead of the complete search term.
function makeAjaxCall(url, methodType,callback){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
console.log("xhr done successfully");
var resp = xhr.responseText;
var respJson = JSON.parse(resp);
callback(respJson);
} else {
console.log("xhr failed");
}
} else {
console.log("xhr processing going on");
}
}
console.log("request sent succesfully");
}
function processUserDetailsResponse(userData){ //Callback function
console.log(userData.query.results.channel.astronomy);
}
$('#inpt_search').keypress(function(e){
if(e === 'Enter'){
var city = $("#sunrise").value;
console.log(city);
e.preventDefault();
}
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20astronomy%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+ city +'%2C%20%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
makeAjaxCall(url, "GET", processUserDetailsResponse); enter code here //calling api using ajax
});
As I understand you need to make the ajax call and update once Enter is pressed. Try the following code, it only calls the API when enter is pressed.
$('#inpt_search').keypress(function(e){
if(e.which === 13){
var city = $("#sunrise").value;
e.preventDefault();
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20astronomy%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+ city +'%2C%20%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
makeAjaxCall(url, "GET", processUserDetailsResponse);
}
});
I would not use the "keypress" event since it's not intended for non printable characters, and you can't prevent its default behaviour without freezing the entire field. Rather use "keyup". Here is a possible solution (replace the submit function with whatever suits your needs) :
$("input").focus().on("keyup", function (ev) {
ev.preventDefault();
// if key is ENTER
if (ev.which === 13) {
submit($(this).val());
}
});
function submit (val) {
$("p").text(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input></input> <span>Press <kbd>ENTER</kbd> when you're done.</span>
<p style="border:1px solid black;padding:1em"></p>
As an alternative, you could submit along the way when the user stops writing for a given delay :
$("input").focus().on("keyup", debounce(250, function (ev) {
ev.preventDefault();
submit($(this).val());
}));
function submit (val) {
$("p").text(val);
}
function debounce (ms, f) {
var tid = null;
return function () {
var subject = this;
var args = arguments;
if (tid) clearTimeout(tid);
tid = setTimeout(function () {
tid = null;
f.apply(subject, args);
}, ms);
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input></input> <span>No need to press <kbd>ENTER</kbd>.</span>
<p style="border:1px solid black;padding:1em"></p>
How do I add the slideDown jquery animation when I knew message is loaded? Perhaps I can't with my method for loading... A file takes user input and inserts into database. Another file pulls from database onto chatbox and styles.
Javascript Code:
var form = document.querySelector('form[name="chatbox"]');
form.addEventListener("submit", function (event) {
event.preventDefault();
});
function submitChat() {
if(chatbox.message.value == '') {
alert('Error: Missing Fields.');
return;
}
var message = chatbox.message.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4&&xmlhttp.status==100) {
document.getElementById('chatlog').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','chat.php?message='+message, true);
xmlhttp.send();
chatbox.reset();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlog').load('logs.php');}, 200);
});
Please let me know if you need the PHP attached.. Thanks for the help! :)
I have link <a href="/MyData/Delete/"> Delete data
How can I implement onclick to popup confirm action with text are you sure and if yes selected to proceed to HttpPost action on MyData/Delete?
<a href="/MyData/Delete/" onclick="someFunction(this, event)">
In javascript:
function someFunction(target, event) {
if(confirm("Are you sure to delete?")) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
// successfully deleted
}
};
xhr.open("POST", target.url, true);
xhr.send();
} else {
event.preventDefault();
}
}
More cleaner way of doing:
<a href="/MyData/Delete/" class="confirmlink">
document.querySelector(".confirmlink").addEventListener("click", function(event) {
if(confirm("Are you sure to delete?")) {
window.location.href = this.href;
} else {
event.preventDefault();
}
});
Avoid using inline js scripts in HTML. It will pollute the markup and tough to manage later.
I want to stop the submit button in the js function checkUni()
Usually in js you can just return false, but that it not gonna work in my case because its an asynchronous (ajax)function, so the outer function will return before the inner function is able to determine wether to return false or true.
Here is the js function:
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var container = document.getElementById("container_ID"); //destination of returned data
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
request.open("GET", URL, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
//SOME CODE
//IF <something> then STOP SUBMIT BUTTON
container.innerHTML = request.responseText;
}
}
request.send(null);
}
Simply return false in the onclick listener.
<input type="submit" onclick="checkUni(); return false;"/>
You can set the action of the form element to "#" which will have the same effect.