How do I fire a function immediately after another function is finished? - javascript

I have the following code:
<script>
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
window.setInterval(function(){
refreshChat();
}, 2000);
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
}
});
</script>
Right now, the refreshChat function calls an ajax script every 2 seconds. When you have entered a message and press enter, it calls a different ajax script. What I would like it to do, is call both functions at the same time. So the script calls the sendMessage function first and refreshes afterwards.
How can I do this? I have already tried changing it to:
<script>
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();refreshChat();
}
});
</script>
But this only enters the message first, and it only refreshes on the second keypress (enter). I would like to thank everybody beforehand on helping me out.

This is actually an illusion. Both functions are being called, but the chat window is refreshing before the chat message is able to save them.
To fix this, you should refresh the chat window only once the new message has been successfully saved:
function refreshChat() {
// Removed for brevity
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
// Now, this will only be called once the ajax is complete
refreshChat();
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
// I removed the refreshChat() call from here and moved it
// into the $.get() callback above ^^
}
});
As you can see, I moved your refreshChat() method to now be called from within the jQuery $.get() callback.

Have you tried using callbacks, that may be what you need?
Here is a link for reference.
http://www.impressivewebs.com/callback-functions-javascript/

MY WORKING AWNSER
Considering for what i asked, i have marked Wes Foster's awnser as correct. What made it work for me is also applying a promises after the get function. This way, the ajax script get's called twice as needed. I hope it will help someone in the future. (Look at me... travelling through time...). You will find my code underneath:
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
refreshChat();
}).done(refreshChat);
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
}
});

Related

Javascript data getting sent letter by letter instead of complete word in search

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>

Cannot communicate between captivate html and parent html

I have a published captivate html file that is loaded into an iframe of another html. I cannot communicate between the two, not even with localStorage. Can anyone tell me what I'm missing?
Parent html
var everythingLoaded = setInterval(function () {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(everythingLoaded);
init();
}
}, 10);
function init() {
ScormProcessInitialize();
var studentID = ScormProcessGetValue("cmi.core.student_id");
var student_name = ScormProcessGetValue ("cmi.core.student_name");
var nameArraya = student_name.split(" ");
var nameArrayb = nameArraya[1].split(",");
var studentNumber = nameArrayb[0];
ScormProcessSetValue("cmi.core.lesson_status", "incomplete");
localStorage.setItem("_studentNumber", studentNumber);
alert("Student Number: " + studentNumber + " Student Mame: " + student_name);
setTimeout(function () {
document.getElementById("iFrame_a").innerHTML = "<iframe name='iframe_1' id='frame_1' src='//somepath.com/sandbox/somecourse/index.html' frameborder='0' width='1000px' height='605px'></iframe>";
}, 250);
}
function sendComplete() {
alert("Send from index start!");
ScormProcessSetValue("cmi.core.lesson_status", "completed");
alert("send status: Completed");
}
window.onbeforeunload = function (){
cpInfoCurrentSlide = localStorage.getItem("_cpInfoCurrentSlide")
alert(cpInfoCurrentSlide);
if(cpInfoCurrentSlide >= 40)
{
alert("onbeforeunload called: " + cpInfoCurrentSlide )
ScormProcessSetValue("cmi.core.lesson_status", "completed");
}
}
iframe code snippet
localStorage.setItem("_cpInfoCurrentSlide", cpInfoCurrentSlide);
I believe your problem is with onbeforeunload. As I remember captivate packages clobber any functions associated with onbeforeunload in the parent frame when they load.
Try this instead, override your SCORM api setvalue method:
var oldLMSSetValue = window.API.LMSSetValue;
window.API.LMSSetValue = function(key, value){
if(key === 'cmi.core.lesson_status' && value === 'completed'){
//do your stuff here
cpInfoCurrentSlide = localStorage.getItem("_cpInfoCurrentSlide")
alert(cpInfoCurrentSlide);
}
//call the original scorm api function so that it runs as expected.
oldLMSSetValue(key,value);
};
edit: this code would go in the parent window, not the iframe.

How to append "user is typing to label", and removing after 5 sec

I'm trying to build a chat program. I have read several guides (such as: http://www.tamas.io/further-additions-to-the-node-jssocket-io-chat-app/),
however I still can't get it to work.
When someone is typing, the "is typing" is not added to the other user's label.
I really hope someone can point out where I have gone wrong.
Thanks,
Here's my code.
client-side:
// Detect typing
var typing = false;
var timeout = undefined;
function timeoutFunction() {
typing = false;
socket.emit("typing", false);
socket.emit("notTyping", true)
}
$("#msg").keypress(function(e){
if (e.which !== 13) {
if (typing === false && $("#msg").is(":focus")) {
notTyping = false;
typing = true;
socket.emit("typing", true);
} else {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 5000);
}
}
});
client.on("isTyping", function(msg) {
$typingActivity.append('<div>' + msg + '</div>');
timeout = setTimeout(timeoutFunction, 5000);
});
server-side:
client.on("typing", function(data) {
console.log("Typing...");
client.broadcast.emit("isTyping", people[client.id] + " is typing...");
});

JavaScript RangeError - Maximum call stack size exceeded when using jQuery.post

When using jQuery's .post() function to submit my form data, I'm getting an Uncaught RangeError: Maximum call stack size exceeded.
I know this generally means recursion but I can't see where the recursion is happening.
I've put the post request into a function ( submitRequest() ) so I can submit data from 2 different points in the code. It originally resided inside the submit event and at that point worked perfectly. The error came as soon as I moved it outside.
Any ideas?
JavaScript code (with commented logs so you can see the flow) :
$(document).ready(function() {
var downloadLink = '',
downloadName = '',
details,
detailsSaved = false;
$('.js--download').click(function(event) {
var self = $(this);
event.preventDefault();
downloadLink = self.data('filePath'); // Store clicked download link
downloadName = self.closest('.brochure').find('.brochure__name').html().replace('<br>', ' ');
if (!detailsSaved) {
$('#brochure-section').addClass('hide');
$('#capture-section').removeClass('hide');
$('html, body').animate({
scrollTop: $("#capture-section").offset().top
}, 500);
} else {
submitRequest();
}
return false;
});
$(".submit-btn").click(function(event) {
var antiSpam = $('input[name=url]').val();
if (antiSpam != "") {
outputResultText('Error - Please leave the spam prevention field blank', 'error');
proceed = false;
event.preventDefault();
return false;
}
var name = $('input[name=name]').val(),
company = $('input[name=company]').val(),
email = $('input[name=email]').val(),
phone = $('input[name=phone]').val(),
proceed = true;
if(name==""){
$('input[name=name]').addClass("error");
proceed = false;
}
if(phone==""){
$('input[name=phone]').addClass("error");
proceed = false;
}
if(email==""){
$('input[name=email]').addClass("error");
proceed = false;
}
if(!proceed) {
outputResultText('Please check all required fields', 'error');
event.preventDefault();
return false;
}
event.preventDefault();
if(proceed) {
console.log('About to request'); // Logged out
submitRequest();
}
return false;
});
//reset previously set border colors and hide all message on .keyup()
$("input, textarea").keyup(function() {
$(this).removeClass("error");
$(".form-result").fadeOut(100);
});
function submitRequest () {
console.log('Start submitRequest'); // Logged out
if (!detailsSaved) {
console.log('Details are NOT saved');
post_data = {
'name': name,
'company': company,
'phone': phone,
'email': email,
'brochure': downloadName,
'brochure_url': downloadLink
};
details = post_data;
} else {
console.log('Details are saved');
post_data = details;
post_data['brochure'] = downloadName;
post_data['brochure_url'] = downloadLink;
}
console.log('Posting data'); // Logged out
// CRASH: Uncaught RangeError: Maximum call stack size exceeded
$.post(bcf_local_args['post_url'], post_data, function(response){
console.log('Response received');
if(response.type != 'error') {
if (detailsSaved) {
outputAlert("Thank you for your request to receive our <strong>'"+downloadName+"'</strong> brochure.<br>We'll send you a copy soon to <strong>'"+email+"'</strong>, so please check your inbox.<br>Want it sent to a different email? Simply refresh the page and try again.");
} else {
//reset values in all input fields
$('#brochure-capture-form input').val('');
$('#brochure-capture-form textarea').val('');
$('#capture-section').addClass('hide');
$('#brochure-section').removeClass('hide');
outputAlert("Thank you for your request to receive our <strong>'"+downloadName+"'</strong> brochure.<br>We'll send you a copy soon to <strong>'"+email+"'</strong>, so please check your inbox.");
}
if (!detailsSaved) {
detailsSaved = true;
}
$('html, body').animate({
scrollTop: $(".brochure__alert").offset().top
}, 500);
} else {
outputResultText(response.text, response.type);
}
}, 'json');
}
function outputResultText (text, status) {
var output = '';
if(status == 'error') {
output = '<div class="error">'+text+'</div>';
} else {
output = '<div class="success">'+text+'</div>';
}
$(".form-result").hide().html(output).fadeIn(250);
}
function outputAlert (text) {
var output = '<div>'+text+'</div>';
$('.brochure__alert').hide().removeClass('hide').html(output).slideDown(250);
setTimeout( function() {
$('.brochure__alert').slideUp(250);
}, 6500);
}
// function accessStorage(action, dataKey, dataValue) {
// if(typeof(Storage) === "undefined") {
// // No support for localStorage/sessionStorage.
// return false;
// }
// if (action == 'store') {
// localStorage.setItem(dataKey, dataValue);
// } else if (action == 'retrieve') {
// return localStorage.getItem(dataKey);
// }
// }
});
I don't know if you already found a solution but I was having the "same" problem.
In my code I had this function where I was calling after an upload of images, and I was passing the images name as paramaters along with others parameters required to my POST data.
After some research I found out that browsers has some limitations on passing parameters so the problem wasn't AT $.post but in my function calling.
I don't know the technical term but I was 'overusing the stack parameters'.
So maybe your problem isn't at your $.post either, but something else exceeding the stack.
Hope this helps.
[]'s

How to submit a form using PhantomJS

I'm trying to use phantomJS (what an awesome tool btw!) to submit a form for a page that I have login credentials for, and then output the content of the destination page to stdout. I'm able to access the form and set its values successfully using phantom, but I'm not quite sure what the right syntax is to submit the form and output the content of the subsequent page. What I have so far is:
var page = new WebPage();
var url = phantom.args[0];
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
console.log(page.evaluate(function () {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].elements["email"].value="mylogin#somedomain.example";
arr[i].elements["password"].value="mypassword";
// This part doesn't seem to work. It returns the content
// of the current page, not the content of the page after
// the submit has been executed. Am I correctly instrumenting
// the submit in Phantom?
arr[i].submit();
return document.querySelectorAll('html')[0].outerHTML;
}
}
return "failed :-(";
}));
}
phantom.exit();
}
I figured it out. Basically it's an async issue. You can't just submit and expect to render the subsequent page immediately. You have to wait until the onLoad event for the next page is triggered. My code is below:
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
//Load Login Page
page.open("https://website.example/theformpage/");
},
function() {
//Enter Credentials
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].elements["email"].value="mylogin";
arr[i].elements["password"].value="mypassword";
return;
}
}
});
},
function() {
//Login
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].submit();
return;
}
}
});
},
function() {
// Output content of page to stdout after form has been submitted
page.evaluate(function() {
console.log(document.querySelectorAll('html')[0].outerHTML);
});
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 50);
Also, CasperJS provides a nice high-level interface for navigation in PhantomJS, including clicking on links and filling out forms.
CasperJS
Updated to add July 28, 2015 article comparing PhantomJS and CasperJS.
(Thanks to commenter Mr. M!)
Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.example/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
As it was mentioned above CasperJS is the best tool to fill and send forms.
Simplest possible example of how to fill & submit form using fill() function:
casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
this.fill('form#loginForm', {
'login': 'admin',
'password': '12345678'
}, true);
this.evaluate(function(){
//trigger click event on submit button
document.querySelector('input[type="submit"]').click();
});
});

Categories