Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 3 years ago.
Improve this question
I'm trying to get better at writing my code in JavaScript and not using jQuery. I've got an $.ajax request which i'm trying to rewrite as an XMLHttpRequest, but getting errors "POST http://localhost:3000/wp-admin/admin-ajax.php 400 (Bad Request)".
The jQuery version works fine, but the JS version doesn't. I get the same error from the jQuery version if I remove data: filter.serialize(), so I feel the issue lies here as there isn't an equivalent version in the JS request, but i'm unsure how to write/add this into it.
If anyone can point me in the right direction that would be great : )
/** Working jQuery filter */
jQuery(function($) {
$("#filter").change(function(e) {
e.preventDefault();
var filter = $(this);
$.ajax({
url: WP.ajax,
data: filter.serialize(),
type: "POST",
beforeSend: function(xhr) {
$("#response").append("Loading...");
},
success: function(data) {
$("#response").html(data);
}
});
return false;
});
});
/** NOT working JS filter */
var af = new XMLHttpRequest();
document.getElementById("filter").addEventListener("change", function(e) {
e.preventDefault();
document.getElementById("filter").value = this.value;
af.onload = function() {
if (af.status === 200) {
document.getElementById("response").innerHTML = af.responseText;
console.log(af.responseText);
}
};
af.open("POST", WP.ajax);
af.send();
});
I've worked it out and got the data sending. For reference the working code is below:
var articleFilter = new XMLHttpRequest();
var filter = document.getElementById("filter");
filter.addEventListener("change", function(e) {
e.preventDefault();
filter.value = this.value;
articleFilter.onload = function() {
if (articleFilter.status === 200) {
document.getElementById("response").innerHTML = articleFilter.responseText;
}
};
articleFilter.open("POST", WP.ajax, true);
var formData = new FormData(filter);
articleFilter.send(formData);
}); // END
Related
This question already has answers here:
What does "async: false" do in jQuery.ajax()?
(7 answers)
Closed 3 years ago.
I have an ajax function and thought it would be nice to include a little ajax-spinner to tell the enduser something is actually happening. This is my current jQuery function:
$('#contact-form').submit(function(e)
{
e.preventDefault();
let overlay = $('#overlay'),
loader = $('#loader-popup');
console.log(overlay);
console.log(loader);
console.log('===================');
//show overlay
overlay.removeClass('hidden');
loader.removeClass('hidden');
console.log(overlay);
console.log(loader);
let formData = new FormData($(this)[0]),
params = [];
$.ajax({
data: formData,
type: 'post',
url: '/pages/contact-us/action/send.php',
cache: false,
contentType: false,
processData: false,
success: function(res)
{
if (res == 1) {
params['type'] = 1;
params['msg'] = 'We will be with you as soon as we can!'
} else {
try {
res = $.parseJSON(res);
let data = [];
$.each(res, function(key, value) {data.push(value)});
params['type'] = 2;
params['msg'] = data.join('<br />')
} catch(e) {
console.log(e);
alert('Huh. that\'s weird, something went wrong! Please try again');
//cause syntax error to stop script working
die()
}
}
validator.displayAlert(params['type'], params['msg'])
},
error: function(res)
{
console.log(res);
alert('Don\'t worry.. it\'s not you, it\'s us.')
}
});
//hide overlay
overlay.addClass('hidden');
loader.addClass('hidden');
});
But weirdly the overlay doesn't show, nor does the loader. What makes this hard to kinda debug and fathom is the console.log output.
first console.log(overlay)
Object [ div#overlay.hidden ]
second console.log(loader)
Object [ div#loader-popup.hidden ]
third console.log(overlay)
Object [ div#overlay ]
fourth console.log(loader)
Object [ div#loader-popup ]
So I can see that my .removeClass() function is working, however, inspecting my page once the form is being submitted shows the elements with the hidden class. If I manually remove that hidden class in the inspector tab then everything shows, so I know it's not a CSS issue.
You can see this happen on a much simpler scale here
I've also tried with .toggle() with no avail.
How do I even begin to debug something that seems to work behind-the-scenes but, not on screen?
You should call hide the overlay in your callback, because it'll be executing asynchronously.
Something like
try {
res = $.parseJSON(res);
let data = [];
$.each(res, function(key, value) {
data.push(value)
});
params['type'] = 2;
params['msg'] = data.join('<br />')
} catch (e) {
console.log(e);
alert('Huh. that\'s weird, something went wrong! Please try again');
//cause syntax error to stop script working
die()
} finally {
//hide overlay
overlay.addClass('hidden');
loader.addClass('hidden');
}
The logic within the $.ajax() call is asynchronous. As such you remove the class then immediately add it back in as the AJAX request is in progress.
To fix this, change the addClass() calls to be made after the AJAX request completes. In your case the best place to do this would be in the complete callback as it will fire whether the AJAX request completed successfully or with an error:
$('#contact-form').submit(function(e) {
e.preventDefault();
let $overlays = $('#overlay, #loader-popup').removeClass('hidden');
let formData = new FormData(this),
params = [];
$.ajax({
// ajax settings...
complete: function() {
$overlays.addClass('hidden');
}
});
});
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 7 years ago.
Improve this question
anyone can tell me why this wont work? It does work when i dont use a if else statement so im a bit stunned atm, i am using a html5 player where the play/pause button toggles, it needs to include the ajax watching when playing and stop watching when paused. thnx
<script>
var test = 0;
if (test == 0) {
$("#play").click(function(){
$.ajax({
url: "start_watching.php",
success: function(result){
$("#fix").html(result);
}
});
)};
test = 1;
} else if (test == 1) {
$("#play").click(function(){
$.ajax({
url: "stop_watching.php",
success: function(result){
$("#fix").html(result);
}
});
)};
test = 2;
}
</script>
Here's a really verbose example of how to solve the logic, with the conditions inside the event handler
var test = 0,
url;
$("#play").click(function(){
if (test === 0) {
url = "start_watching.php";
test = 1;
} else {
url = "stop_watching.php";
test = 0;
}
$.ajax({
url : url,
success : function(result){
$("#fix").html(result);
}
});
});
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 7 years ago.
Improve this question
I am seeking some help. I am very new to programming and I’m working on a new project.
The objective is to display the contents of a plain text file in a web page.
The text file (named title.txt) and has a single line of text
The text file is located on my server
The text content changes every three minutes or so.
I wish to read this file and display its content in a web page
The web browser is to automatically re-read the file every three minutes or so.
I have looked at a number of websites to achieve this, however i am confused by the options available. I read that Jquery/ajax can perform this task.
Can anyone help me by providing some example code.
Many thanks
Colin
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<Body>
<p><center>Current Track: <span id="trackinfo">No track information available at this time</span></p></center>
<script>
function radioTitle() {
var url = 'http://XXX.no-ip.org:8000/tracktitle.txt';
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) {
$("#trackinfo").html(data)
},
error: function(e) {
console.log(e.message);
}
});
}
$(document).ready(function(){
setTimeout(function(){radioTitle();}, 2000);
setInterval(function(){radioTitle();}, 15000);
});
</script>
</body>
</head>
</html>
var tid = setInterval(mycode, 2000);
function mycode() {
// do some stuff...
// no need to recall the function (it's an interval, it'll loop forever)
readTextFile("your file path");
}
function abortTimer() { // to be called when you want to stop the timer
clearInterval(tid);
}
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 7 years ago.
Improve this question
I cannot find the right solution how hide a certain content on new part of page generated from PHP. (I am new in javascript)
I have a page, which loads new content below the actual, if a visitor scrolling down (like on Facebook.)
Each time, when a new content will displayed, I want run a function, which will hide certain content on the page.
Here is the code which loads new content. This works great.
(function() {
var $loadMore = $('.load-more').first();
if (!$loadMore.get(0)) {
return;
}
var timeout;
var $loadMoreLink = $loadMore.children('a'),
$list = $loadMore.prev('ul');
$loadMoreLink.on('click', function(event) {
event.preventDefault();
getMore();
});
function checkForMore() {
if (($window.scrollTop() + $window.height()) > ($list.offset().top + $list.height())) {
getMore();
}
}
function getMore() {
if (!$loadMoreLink.is(':visible')) {
return;
}
$loadMoreLink.attr('hidden', true);
$.get($loadMoreLink.attr('href'), function(response) {
$list.append(response);
var moreUrl = $list.children().last().data('more-url');
if (moreUrl) {
$loadMoreLink.attr('href', moreUrl);
$loadMoreLink.removeAttr('hidden');
}
else {
$loadMore.attr('hidden', true);
}
console.log(moreUrl)
});
}
$window.on('scroll', function() {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(checkForMore, 50);
});
checkForMore();
})();
Here is my code, with help of which I want to hide certain content. That does not work :(. I have tried really much, and spent many days on that.
var hideUnity = document.getElementsByClassName("load-more");
for (var i = 0; i < hideUnity.length, i++) {
hideUnity[i].addEventListener("click", function() {
if (something && something) {
$(document).ready(function(){
$("li.unity").hide();
});
}
});
}
Link to loading file at page
<div class="load-more">
Load more
</div>
Can someone help me, please? :). Thanks.
I don't know if there is a reason to mix native js and jQuery, but you can do your function easily using the framework:
$(function(){
$(".load-more").on('click', function(){
// now $(this) represents clicked object while $('.load-more') still represents all elements with provided class
if( whateveryouwant ){
$("li.unity").hide();
}
});
});
Edit
If you need to use a delegated event, just replace
$(".load-more").on('click', function(){....
by
$(document).on('click', '.load-more', function(){....
This is my code, which sometimes works and sometimes doesn't.
var resolve_ajax_login=function(){
$.ajaxSetup({cache:false });
var loginvar=$("#inputlogin").attr("value");
var senhavar=$("#inputsenha").attr("value");
$.post("../model/php/login_ajax.php",
{login:loginvar, senha:senhavar},
function(responseText){
if (responseText=="ok"){
window.location="areatrab.php";
}else{
$("#inputlogin").attr("value","");
$("#inputsenha").attr("value","");
$("#divmensagem").html("<span style='color:red;font-size:70%;'>"+responseText+"</span>");
}
}
);
return false;
};
Ok. It's in portuguese but I think you get the general picture. Sometimes this works, no problem, but some other times (only in IE, no problem whatsoever in Firefox) it throws a javascript error in my jquery.js file (minified). The error description is as follows:
Object doesn't support this property or method: jquerymin.js line 123 character 183..
which amounts to...
{return new A.XMLHttpRequest}
somewhere in the middle of the jquery.js file. It seems to be very IE-specific, as I had no such problems on Firefox. This guy apparently had the same problem as I did, but got no responses yet.
Has anyone else seen this? Thanks in Advance
P.S.: I run IE 8
Have you tried using a full URL instead of ../model...? For example: http://www.mysite.com/model/login_ajax.php
Also, maybe try modifying the 'xhr' property using jQuery's .ajax method... something like:
var loginvar = $("#inputlogin").val();
var senhavar = $("#inputsenha").val();
var ajax_obj = null;
var resolve_ajax_login = function() {
if(ajax_obj !== null) {
try {
ajax_obj.abort();
} catch(e) {
}
}
ajax_obj = $.ajax({
type: 'POST',
cache: false,
url: '../model/php/login_ajax.php',
data: {login:loginvar, senha:senhavar},
dataType: 'text',
timeout: 7000,
success: function(data)
{
if(response == 'ok') {
alert("right on!");
} else {
alert("not ok");
return;
}
},
error: function(req, reqStatus, reqError)
{
alert("error");
return;
},
'xhr': function() {
if(ajax_obj !== null) {
return ajax_obj;
}
if($.browser.msie && $.browser.version.substr(0,1) <= 7) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
return new XMLHttpRequest();
}
}
});
}
It's something to do with the order in which you try all the different types of browsers in order to create the right kind of XMLHTTP REQUEST object.. I'll explain it in more detail in the following page:
AJAX inconsistency in IE 8?