Async call not working in vanilla javascript [closed] - javascript

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.

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));
}

On one click open 2 pages but not simultaneously [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
ok I want a help with a code, when user click the "download", it should go to the first link but if link 1 is down, it should go to 2nd link ........link 1 should be a default, it should only send the visitor to 2nd link if 1st link dead or down
please tell me if this kind of thing is possible, or just my imagination
and it will be great if the 2nd link is hidden which can't found out by simple inspect tool,if not possible just forget the last line
You can make a call and check the return status with AJAX. Then based on the status code such as 200,404, you can decide what you want to do. This can be done easier with jQuery.ajax() method if you use jQuery.
One of the approach would be to check the URL and recieve the status with AJAX. Based on the returned status code (example 404), you decide what to do next:
with jQuery
$.ajax({
type: 'HEAD',
url: 'http://yoursite.com/pagename.php',
success: function() {
// NO 404 ERROR
},
error: function() {
// error in HEAD (404)
}
});
with Pure Javascript:
function checkUrl(url) {
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest;
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHttp");
}
if (request) {
request.open("GET", url);
if (request.status == 200) { return true; }
}
return false;

How to access this API without the use of Jquery or AJAX? [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 3 years ago.
Improve this question
I'm looking to get data from the http://dev.markitondemand.com/ API. The API was designed to be used with AJAX calls, but for technical reasons I cannot include JQuery in my project. How do I get the info that this page provides without making an AJAX call to the server? JSON and XML are both fine.
An ajax call is simply an XMLHttpRequest that can be used to fetch data in various formats (like JSON and XML) from a server. Jquery has some functions which simplify the process of making ajax calls, but it is not needed.
You can just use the built-in XMLHttpRequest API to make the request using vanilla javascript.
Example
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://dev.markitondemand.com/Api/v2/Lookup', true);
xhr.send(null);
AJAX is a way to fetch data from a server. Using jQuery is not the only way to perform AJAX. You can do it AJAX requests with VanillaJS (pure JavaScript). To do this :
if(window.XMLHttpRequest){
var xhr = new XMLHttpRequest();
} else {
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://dev.markitondemand.com/Api/v2/Lookup', true);
xhr.send(null);
See this MDN link for a better understanding of AJAX.
See this W3schools.com tutorial to know how to handle Internet Explorer.

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/

faking xmlhttprequests with casperjs [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm writing end-to-end tests with casperjs and would like to fake ajax server responses
I've came up with the idea of including a simple script that mocks the xmlhttprequest object and would always return my expected results, like the following
var ajax_requests = [
['GET', '/jobs', JSON.stringify(jobs)]
], stubs = stubs || {};
function setup_ajax(){
stubs.server = sinon.fakeServer.create();
_.each(ajax_requests, function(r){
//r[1] = "http://localhost:8000" + r[1]
r[2] = [200, { "Content-Type": "application/json" }, r[2]]
stubs.server.respondWith.apply(stubs.server, r)
})
stubs.server.autoRespond = true;
stubs.server.autoRespondAfter = 2;
}
Then I call setup_ajax in my casper test like
casper.then(function(){
this.evaluate(setup_ajax)
}
but seemingly future ajax requests still avoid my xmlhttprequest implementation.
I've tried running setup_ajax on the fly, using $.ready() and having it called from casper too, but neither of these worked
More interestingly, checking for objects' existence strangely fails.
function setup_ajax(){
return typeof(sinon)
}
casper.then(function(){
var x = this.evaluate(setup_ajax)
casper.log(x) // logs 'null'
}
But sinon is properly included, at least casper did not cause any errors when I've made some calls to it outside the setup_ajax function, but caused error when I deliberately had sinon excluded.
Do you have any ideas on mocking xmlhttprequests under casperjs?
You can use sinon.js to fake XmlHttpRequest.
PhantomXHR wraps the XHR mocking of SinonJS for casperjs.
First you need to initialize PhantomXHR:
var xhr = require('phantomxhr');
casper.on('page.initialized', function () {
xhr.init(casper.page, {
libraryRoot: '/path/to/node_modules/phantomxhr/'
});
});
Than you can fake the XHR request:
var fake = xhr.fake({
url: '/jobs',
responseBody: jobs
});
Take care of waiting for the XHR request to finish before evaluating the page. You can check if the request completed by looking for
fake.count() === 1

Categories

Resources