Why does this code not function correctly? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm currently trying to learn Ajax and have been following a tutorial. I have created the following script:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function MyFunction(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("MyDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "command.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<button onclick="MyFunction()">Execute</button>
<div id="MyDiv"></div>
</body>
</html>
I then have a php file named command.php which just echos the word "success".
Obviously the intended purpose of this script is to return the word "success" when the execute button is clicked. I have followed the tutorial for this very precisely, so I'm unsure of what's wrong with what I've written.
I've also looked at other Ajax tutorials, to see what they might have done differently. It seems that some variants of Ajax look very different to others. I mean by this, a lot of tutorials involve code looking like what I've written, but many others (such as this one) look rather different and involve many '$' signs. Why is this?

Looks like maybe a copy/paste error. I'm guessing:
if(ajaxRequest.readyState == 4){
should be:
if(xmlhttp.readyState == 4){
Also, it doesn't sound like you're using your browsers dev tools. The console should have a message like this in it:
Uncaught ReferenceError: ajaxRequest is not defined
I suggest reading up on the dev tools for your preferred browser.

Related

EmailJS message can't be sent [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 23 hours ago.
Improve this question
I'm new to EmailJS and trying to use it on my portfolio in the contact form. I tried different solutions and still showing the same error, I think I'm stuck now
I created the account, activated it, activated MFA as well, and tried multiple codes from the doc of EmailJS and from tutorials and still showing me the same error on the console. I even changed the service_id, template_id, and public key.
The error: Uncaught The public key is required. Visit https://dashboard.emailjs.com/admin/account
code on HTML:
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/#emailjs/browser#3/dist/email.min.js">
</script>
<script type="text/javascript">
(function(){
emailjs.init("My-Public-Key");
});
</script>
code on JS:
function SendMail(){ event.preventDefault();
var params ={
from_name : document.getElementById("fullname").value,
email_id : document.getElementById("email-id").value,
message : document.getElementById("message").value
}
const serviceID = "service_uzy3k87";
const templateID = "template_btcihm8";
emailjs.send(serviceID, templateID, params)
.then(res=>{
document.getElementById("fullname").value = "";
document.getElementById("email-id").value = "";
document.getElementById("message").value = "";
console.log(res);
alert("Your message sent successfully!!")
})
.catch(err=>console.log(err));
}

Async call not working in vanilla javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
The following code is my frontend code for a http long poll. In this I am expecting the code setTimeout(getChat, 0) to call the method asynchronously. But when the getChat method's XHR is pending all following XHRs of different methods are also getting into pending state.
discussTask = function(taskId) {
taskIdChat = taskId
getChat() // initial call
}
var getChat = function() {
taskId = taskIdChat
payLoad = {
'task_id': taskIdChat,
'recent_message_id': recentMessageId
}
var xmlhttp = XHR('/chat/sync', 'POST', payLoad)
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
buildChat(JSON.parse(xmlhttp.responseText))
setTimeout(getChat, 0) // Async recursive call
}
}
}
var XHR = function(action, method, payLoad) {
var xmlhttp = new XMLHttpRequest()
xmlhttp.open(method, action, true)
xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
xmlhttp.send(JSON.stringify(payLoad))
return xmlhttp
}
Found the issue. The Problem was not client side. I am using flask framework which by default will run in single threaded mode. So it was not serving the async requests from client side.

Restart this script [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
What code do I have to write to restart this script? I want to totally reset / update the script via a code in order to let it process new / updated information. Maybe best way to just stop it and start it again. But how?
<script type="text/javascript">
var _myplug = _myplug || {};
_myplug.key = '12e9u349u43098j8r940rjciocjo';
_myplug.renderTo = '';
window.myplug||(function(d) {
var s,c,o=myplug=function(){ o._.push(arguments)};o._=[];
s=d.getElementsByTagName('script')[0];c=d.createElement('script');
c.type='text/javascript';c.charset='utf-8';c.async=true;
c.src='js/loader.js?';s.parentNode.insertBefore(c,s);
})(document);
</script>
Well, without knowing enough info about the script, here's a hacky method that will be sure to reload the script:
function reloadScript() {
with(document) {
var newscr = createElement('script');
newscr.id = 'reloadMe';
newscr.appendChild(createTextNode(getElementById('reloadMe').innerHTML));
body.removeChild(getElementById('reloadMe'));
body.appendChild(newscr);
}
}
You'll need an ID on your script tag:
<script type="text/javascript" id="reloadMe">
UPDATE:
The above method isn't enough to refresh your code, because your code also appends another script tag in the document, called loader.js.
Here's a special version for your situation:
<script type="text/javascript" id="notTheScriptYouWannaRefresh">
var _myplug = _myplug || {};
_myplug.key = '12e9u349u43098j8r940rjciocjo';
_myplug.renderTo = '';
window.myplug||(function(d) {
var s,c,o=myplug=function(){ o._.push(arguments)};o._=[];
c=d.createElement('script');
c.type='text/javascript';c.charset='utf-8';
c.async=true;c.id='reloadMe'; //<-- CUSTOM ID SET!
c.src='js/loader.js?';d.body.appendChild(c);
})(document);
function reloadScript() {
with(document) {
var newscr = createElement('script');
newscr.id = 'reloadMe';
newscr.appendChild(createTextNode(getElementById('reloadMe').innerHTML));
body.removeChild(getElementById('reloadMe'));
body.appendChild(newscr);
}
}
window.setTimeout(reloadScript, 10000); //Reload after 10 seconds
</script>
Hope this solves the problem.
I know something more.
I found another method, which maybe does the same as what #AaronGillion suggested. Only the trigger differs (it restarts every x seconds).
This is the method:
http://jsfiddle.net/mendesjuan/LPFYB/
I replaced the scriptTag.innerText with my script codes. Since I see that this starts my script succesfully, I also understand that the script is removed and reinserted every x seconds. And since this doesn't update the script, it proves that there is another thing loaded that keeps the script continuing in the old state. Might be the loader.js.
Unfortunately my JS knowledge is limited. How to restart loader.js from my code?
For clarity I paste the code from this topic again below, including the loader.js:
<script type="text/javascript">
var _myplug = _myplug || {};
_myplug.key = '12e9u349u43098j8r940rjciocjo';
_myplug.renderTo = '';
window.myplug||(function(d) {
var s,c,o=myplug=function(){ o._.push(arguments)};o._=[];
s=d.getElementsByTagName('script')[0];c=d.createElement('script');
c.type='text/javascript';c.charset='utf-8';c.async=true;
c.src='js/loader.js?';s.parentNode.insertBefore(c,s);
})(document);
</script>
Question is how to restart loader.js.

Using URL fragment to determine which jquery function is run [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to link to a page like (domain.com/page#loadThickBox1) and have it run jquery function that loads a thickbox by default. What code do I need to run to accomplish this?
For instance, these might be a few links:
domain.com/page#loadThickBox1
domain.com/page#loadThickBox2
domain.com/page#loadThickBox3
NOT like this:
domain.com/page/loadThickBox1
domain.com/page/loadThickBox2
domain.com/page/loadThickBox3
Use location.hash
$(function() {
switch( location.hash.replace('#','') ){
case 'loadThickBox1':
//do something!
loadThickBox1();
break;
case 'loadThickBox2':
//do something!
loadThickBox2();
break;
case 'loadThickBox3':
//do something!
loadThickBox3();
break;
}
});
location.href.split('#')[1]
This will get you the words after the #. Load the appropriate box given this value.
You can listen to the hashchange event, parse the hash and run your function accordingly.
DEMO
function handleHash(hash) {
var hash = hash.replace('#', '');
if (!hash) return;
console.log('Loading thick box ' + hash.slice(-1));
}
window.addEventListener('hashchange', function () {
handleHash(location.hash);
});
//handle initial hash when page loads
handleHash(location.hash);

What is the equivalent of this Ajax code, in jQuery? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
None of the jQuery methods, from the jQuery page could work in the same way, as this simply does.
function enableAjaxTask(removeLink){
var xmlhttp = false;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('foo').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'foo.php?id=22', true);
xmlhttp.send(null);
}
it should be like this
$.ajax({
type: 'GET', //GET/POST
url: 'foo.php',//URL to send request
data: 'id=12', //query parameters here, you can direct pass url: 'foo.php?id=12'
success: function(responseText){
//called if the request succeeds. also check complete ,done, error
$('#foo').html(responseText);
}
});
$("#foo").load('foo.php?id=22');
http://api.jquery.com/load/

Categories

Resources