I'm trying to debug a third party script.
It works fine in Chrome. But Firefox won't register the onclick event.
Any idea why FireFox won't play nice?
I tried adding return false; as suggested here but it did not work, adding that above the very last closing bracket just produces more errors when viewed in console.
function ac_event(event, eventdata) {
return ajax({
url: activecampaignevent.ajax_url,
type: 'POST',
data: {
action: 'ac_event',
event: event,
eventdata: eventdata
},
success: function (response) {
console.log('response', response);
}
});
function ajax(options) {
var request = new XMLHttpRequest();
var url = options.url;
var data = encodeData(options.data);
if (options.type === 'GET') {
url = url + (data.length ? '?' + data : '');
}
request.open(options.type, options.url, true);
request.onreadystatechange = onreadystatechange;
if (options.type === 'POST') {
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
} else {
request.send(null);
}
return;
function onreadystatechange() {
if (request.readyState === 4 && request.status === 200){
options.success(request.responseText);
}
}
function encodeData(data) {
var query = [];
for (var key in data) {
var field = encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
query.push(field);
}
return query.join('&');
}
}
}
Click this link to test
you can create event in javascript and assign it with browser event to stop with preventDefault.
document.querySelector("#LinkID").addEventListener("click", function(event){
//do your code here
alert("preventDefault will stop you to go")
event.preventDefault();
}, false);
Related
I am trying to develop a component in Joomla 4. I have a simple button that should fire of a script to update the database.
I can make the call to the JavaScript ok, but the JavaScript does not appear to open the request URL, if anything it opens the current URL or refreshes the page. The script works fine outside of Joomla but not inside.
I have tried both the following, and the same thing happens:
*function buttonLike()
{
var xhr = new XMLHttpRequest();
var parentEl = this.parentElement;
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
console.log('Get Here OK' + parentEl.id);
xhr.open('GET', 'liked.php', true);
// Form data is sent appropriately as a POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function ()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var result = xhr.responseText;
console.log('Never Here Result: ' + result);
}
if(xhr.readyState == 4 && xhr.status == 0)
{
console.log('Always Here');
}
};
xhr.send("id=" + parentEl.id);
}*
OR
function buttonLike()
{
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
var request = new Ajax(url, {
method: 'post',
update: some_div,
data: options,
onComplete: function (){
$('some_field').setHTML('I am finished!');
}
}).request();
Been going round in circles on this one, any help would be appreciated.
I want to run a this code only if a visitor is from a specific country
window.onload=function(){
document.getElementById("buy").click();
};
I tried this but didn't work :
var requestUrl = "http://ip-api.com/json";
var xhr = new XMLHttpRequest();
xhr.open('POST', requestUrl, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function () {
var json = JSON.parse(xhr.responseText)
if(json.country == 'France'){
document.getElementById("buy").click();
};
};
xhr.send(null);
Here's an easy way to do it with that same API:
fetch('http://ip-api.com/json').then(response => {
return response.json();
}).then(data => {
if (data.country == "France") {
document.getElementById("buy").click();
}
});
Or if you prefer jQuery:
$.getJSON("http://ip-api.com/json", function(data) {
if (data.country == "France") {
$("#buy").click();
})
});
I have used JQuery example to send form data and receive back JSON data. Now I would like to do the same thing in plain/vanilla Javascript. Here is example of my JQuery code:
$('.frmSubmitData').on('submit', function(e){
e.preventDefault();
var formData = $('#myForm').serialize();
console.log(formData);
$.ajax({
type: 'POST',
encoding:"UTF-8",
url: 'Components/myTest.cfc?method=testForm',
data: formData,
dataType: 'json'
}).done(function(obj){
if(obj.STATUS === 200){
console.log(obj.FORMDATA);
}else{
alert('Error');
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
});
And here is what I have so far in plain JS:
function sendForm(){
var formData = new FormData(document.getElementById('myForm')),
xhr = new XMLHttpRequest();
xhr.open('POST', 'Components/myTest.cfc?method=testForm');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(formData);
}
I think that something is wrong in way how I handle response with JSON data. If anyone can help me with problem please let me know. Thank you.
Optimally, for Firefox/Chrome/IE and legacy IE support, first determine the request type:
function ajaxReq() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser does not support XMLHTTP.");
return false;
}
}
Then, send the request:
var xmlhttp = ajaxReq();
var url = "http://random.url.com";
var params = "your post body parameters";
xmlhttp.open("POST", url, true); // set true for async, false for sync request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params); // or null, if no parameters are passed
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
var obj = JSON.parse(xmlhttp.responseText);
// do your work here
} catch (error) {
throw Error;
}
}
}
Ajax request is successful but response is null but I can see the result response in firebug as:
<?xml version="1.0" encoding="UTF-8" ?><response><likes>13</likes></response>
And in the console there is error as :
TypeError : response is null
var XMLHttpObject = createXMLHttpRequest();
$Id = null;
function process(id) { //makeAsynchornusRequest
if(XMLHttpObject.readyState == 0 || XMLHttpObject.readyState == 4) {
XMLHttpObject.onreadystatechange = responseHandler;
$Id = id;
XMLHttpObject.open("GET","like/" + id);
XMLHttpObject.send(null);
}
}
function responseHandler() {
if(XMLHttpObject.readyState == 4) {
if(XMLHttpObject.status == 200) { // 200 implies `ok` like 400 implies `page not found`
response = XMLHttpObject.responseXML;
xmlDocumentElement = response.documentElement;
output = document.getElementById("num_likes" + $Id);
output.innerHTML = xmlDocumentElement ;
}
}
}
You have tagged JQuery - try using JQuery for your Ajax call:
$.ajax({
url: '/Likes',
data: { id: id },
success: function (response) {
if (response) {
console.log(response);
}
},
error: function (xhr, s, sa) {
console.log(s, sa);
},
complete: function () {
console.log('complete event');
}
});
Can you try switching this to an onLoad event handler.
From mozilla docs:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);
// If specified, responseType must be empty string or "document"
xhr.responseType = 'document';
// overrideMimeType() can be used to force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
console.log(xhr.responseXML);
}
}
};
xhr.send(null);
With your code (note you may need to tweak the responseHandler() body slightly:
XMLHttpObject.open("GET","like/" + id);
xhr.onload = responseHandler;
XMLHttpObject.send(null);
Im trying to pass parameters to servlet from javascript with :
function selectHandler() {
var selection = table.getChart().getSelection()[0];
var topping = data.getValue(selection.row, 0);
var answer=confirm("Delete "+topping+"?");
if(answer){
document.location.href="/item?_method=delete&id="+topping;
alert(topping+" has been deleted");
location.reload();
}
else return false;
}
The values are getting passed to the servlet and is working fine when I'm using firefox as in I'm getting the url as: http://XXXXXXX/item?_method=delete&id=xxxx
But when I'm using chrome the URL that is send is http://XXXXXXX/item. as the values are not getting passed!! I have tried with window.location.href also with no change. what could be the issue?
What you need is ajax call or say XMLHttpRequest as below:
<script type="text/javascript">
function doAjax () {
var request,
selection = table.getChart().getSelection()[0],
topping = data.getValue(selection.row, 0),
answer=confirm("Delete "+topping+"?");
if (answer && (request = getXmlHttpRequest())) {
// post request, add getTime to prevent cache
request.open('POST', "item?_method=delete&id="+topping+'&time='+new Date().getTime());
request.send(null);
request.onreadystatechange = function() {
if(request.readyState === 4) {
// success
if(request.status === 200) {
// do what you want with the content responded by servlet
var content = request.responseText;
} else if(request.status === 400 || request.status === 500) {
// error handling as needed
document.location.href = 'index.jsp';
}
}
};
}
}
// get XMLHttpRequest object
function getXmlHttpRequest () {
if (window.XMLHttpRequest
&& (window.location.protocol !== 'file:'
|| !window.ActiveXObject))
return new XMLHttpRequest();
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
throw new Error('XMLHttpRequest not supported');
}
}
</script>
You can also do it easily by jquery,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script type="text/javascript">
function doAjax () {
...
$.ajax({
url: "item?_method=delete&id="+topping+'&time='+new Date().getTime()),
type: "post",
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("It worked!");
// do what you want with the content responded by servlet
}
});
}
</script>
Ref: jQuery.ajax()