AJAX post - {"readyState":0,"responseText":"","status":0,"statusText":"error"} - javascript

I have this javascript but it is not working : I receive the following error : {"readyState":0,"responseText":"","status":0,"statusText":"error"}
This script is included in a webpage of my site which is in a subdirectory of the site.
From my debugging, I do not understand where the error can come from... (since I do quite exactly the same for the index webpage of my site with another javascript which looks almost the same)
$(document).ready(function() {
//if submit button is clicked
$('#filterbtn').click(function () {
//Get the data from all the fields
var a = JSON.stringify( $("#multiselect").val() );
var b;
if ($('#b').prop('checked')) {
b = 0;
} else {
b = 1;
}
var c = JSON.stringify($("#Sliderstart").slider("value"));
var d = JSON.stringify($("#Sliderend").slider("value"));
//organize the data properly
var data = 'b=' + b + '&c=' + c + '&d=' + d + '&a=' + a;
//start the ajax
$.ajax({
url: "./filter.php",
type: "POST",
data: data,
crossDomain: true,
cache: false,
success: function (html) {
document.getElementById("message").innerHTML=html;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
return false;
});
});
Thank you guys !
Cheers

This is the kind of error you get when you request an url that doesn't exist.
Try changing this:
url: "./filter.php"
to an aboslute path like this:
url: "/PATH_TO_FILTER/filter.php"

Related

AJAX is not working in macOS WebView

I have created a WebView for macOS app and it contains one AJAX call. The same WebView is working fine when the app calls my local URL, but when it calls the live URL, the AJAX call is not working.
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: 'http://mywebsite.com/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});
My local PHP version is 7.1.8 and my live server PHP version is 5.4.
Change your function to onclick of checkbox directly,put this code in your checkbox onclick="MyFuncion",why I'm telling this is for web view we need to give exact command in exact position it's not a browser
And your AJAX call will be like below,
function myFunction()
{
var pripolcheck = $("#pripolcheck").val();
var app = $("#app").val();
var user_id = $("#user_id").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1='+ pripolcheck + '&app1='+ app + '&user_id1='+ user_id;
if(pripolcheck=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxformsubmit.php",
data: dataString,
cache: false,
success: function(result){
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$("input.pripolcheck").attr("disabled", true);
}
});
}
return false;
}
"My local PHP version is 7.1.8 and my live server PHP version is 5.4."
I think this explains everything.
However, try setting an absolute URL in your call:
url: 'ajaxformsubmit.php',
to
url: '/ajaxformsubmit.php',
Or whatever the actual path would be. Just a single slash will give you
http://wherever.com/ajaxformsubmit.php
if u use same site url plz use relative path not absolute path then its ok.
if use defrant site url plz comment me so give me new solution
PLZ try
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: '/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});

Is my JavaScript code correct?

I am trying to get JSON out of my Rest API and want to use this JSON information to show them on my application.
Is the function renderUserState ever called? Because the rest of my Code should work fine.
function testSubmit() {
var card = getQueryVariable("select_card");
var action = getQueryVariable("select_action");
var urlGet = "/test/api/getting-ready?cardId=" + card + "&action=" + action;
$.ajax({
type : 'GET',
url : urlGet,
dataType : 'json',
encode : true
}).done(renderUserState);
}
function renderUserState(userState){
$("#gold").text(userState.goldAmount);
}
Thanks for your help!
Yup, your code is correct you just need to call a function in the done since the done will receive the data returned by your endpoint.
Hope this will help you click on the button and see the log.
function testSubmit() {
// var card = getQueryVariable("select_card");
// var action = getQueryVariable("select_action");
// var urlGet = "/test/api/getting-ready?cardId=" + card + "&action=" + action;
var urlGetTest = "https://jsonplaceholder.typicode.com/posts";
$.ajax({
type : 'GET',
url : urlGetTest,
dataType : 'json',
encode : true
}).done((userState) => {
renderUserState(userState);
});
}
function renderUserState(userState){
console.log(userState);
// $("#gold").text(userState.goldAmount);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="testSubmit();">Click Here</button>

Unable to display results using jquery ajax

I am trying to implement a comment feature on my page. I have an itemID 123. on that page, I would like to display the comments that people have posted about itemID 123. However as of now, I am unable to display these comments on my page. There are no errors in the console.
Javascript:
function mywall() {
var url = serverURL() + "/viewwall.php"; //execute viewwall.php in the server
itemID = decodeURIComponent(getUrlVars()["itemID"]);
var JSONObject = {
"itemID": decodeURIComponent(getUrlVars()["itemID"])
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_mywallresult(arr); //success. execute _mywallresult()
},
error: function () {
validationMsg();
}
});
}
function _mywallresult(arr) {
var i;
//for all the shouts returned by the server
for (i = 0; i < arr.length; i++) {
//append the following:
//<b>
//time of posting </b>
//<br/>
//the message
//<br>
//userid
$("#wallcontentset").append("<b>" + arr[i].timeofposting + "</b><br/>" + arr[i].message + "<hr>" + arr[i].userid);
}
}
HTML:
<div data-role="content" class="ui-content" id="wallcontentset"></div>
Try the following :
success: function (response) {
_mywallresult(response.arr);
},

Multiple AJAX calls and show div on finish

I have a JS script doing multiple AJAX requests. First I'm requesting a product by ID and then I'm requesting every single variant of this product. I can't do any form of backend coding since the environment I'm working in is closed.
My requests works fine, but right now I'm appending every single variant to a div, and my client don't really like this, so I was thinking is it possible to load all data into a variable and then fade in the parent div of all variants at the very end?
My script looks like this:
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
variants.find('.variant').fadeIn(300);
}
});
});
}
});
Some fast and dirty solution, but idea and concept of solution is clear. It is bad solution, but works for you in your case when you have no access to backend code.
var all_load_interval;
var is_all_data_ready = false;
var all_data_count = 0;
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
var data_count = $(data).find('Combinations Combination').length;
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
// make div with class variant hidden
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
// count every variant
all_data_count += 1
if (all_data_count == data_count) {
// when all data got and created, lets trigger our interval - all_load_interval
is_all_data_ready = true;
}
}
});
});
}
all_load_interval = setInterval(function() {
// Check does all data load every second
if (is_all_data_ready) {
// show all div.variant
variants.find('.variant').fadeIn(300);
clearInterval(all_load_interval);
}
}, 1000);
});

How to display a progress bar during an ajax request (jquery/php)

I have an ajax request, whereby I am installing a magento shop automatically, and when the process is done, it would redirect the user to the newly created shop. Here are my codes:
function postSuccessFormData() {
var targetUrl = '/index.php/install/wizard/successPost';
jQuery('.form-button').addClass('loading');
setInterval(installStatus(),4000);
jQuery.ajax({
url: targetUrl,
global: false,
type: 'POST',
data: ({
finish: 1,
password_key: jQuery('#password_key').val()
}),
async: true,
dataType: 'json',
error: function() {
alert("An error has occurred. Please try again.");
},
success: function(data) {
window.location.href = '/';
}
});
function installStatus() {
var installerUpdatesUrl = '/index.php/install/wizard/installerStatus';
//showProgressBar();
jQuery.ajax({
url: installerUpdatesUrl,
// global: false,
type: 'GET',
async: true,
dataType: 'json',
error: function (data) {
// alert(data.result);
},
success: function (data) {
handle data.result
var dataKeys = Object.keys(data);
var lastElementKey = dataKeys[dataKeys.length - 1];
var lastMessage = data[lastElementKey]['message'];
if(data[lastElementKey]['progress'] == '') {
updateProgressBar(data[dataKeys[dataKeys.length - 2]]['progress'],100);
}
setting message
jQuery("#message").html(lastMessage);
if (data[lastElementKey]['state'] == 'Failure') {
var stepStr = lastElementKey.split('_');
var stepString = stepStr[0].toUpperCase() + ' ' + stepStr[1] + ':';
alert(stepString + "\n" + data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
return false;
} else if (data[lastElementKey]['state'] == 'Finish') {
alert(data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
//window.location.href = '/';
} else {
// installStatus();
}
},
complete: function () {
installStatus();
jQuery('.form-button').removeClass('loading');
}
});
}
The way this is done:
After every 4 seconds the function installStatus is run, which will output the current progress in JSON format. My problem is, this function needs to be executed simultaneously with the function post().
This is not happening, the installStatus is only run after the first function has been completed.
What is wrong?
You are executing installStatus when you define it. So this:
setInterval(installStatus(),4000);
needs to be
setInterval(installStatus, 4000);
The new XMLHttpRequest has a nice progress event you can listen to show the user the upload progress.
Here's the spec with a nice demo: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
Initially you should call installStatus() only once and then inside the method inside ajax success you should update the procent in the progress bar and call it recursively the same method. On the server side you can save the current procent in a cookie and with every recursive call you can update the cookie and return the procent.

Categories