XMLHttpRequest Dosen't complete - php

I'm calling a PHP file with XMLHttpRequest, but now the call doesn't complete and I
have no idea why. The req.readyState isn't 4, and I don't know why because the PHP file is okay and does exactly what supposed to (just echo a string).
Can anyone see what I can not see?
function processAjax(id, option) {
if (option == "lpath") url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?id=" + id;
else url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?cat=" + id;
//create AJAX request
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv();
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv();
req.open("GET", url, true);
req.send();
}
}
}
//this function handles the response from the ajax request
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
//all of the code below doesn't happen because its not the option
if (option == "lpath") {
var response = req.responseText.split('##');
var articles = response[0].split(';');
var quizes = response[1].split(';');
document.getElementById("article_id").innerHTML = "";
document.getElementById("quiz_id").innerHTML = "";
for (var i = 0; i < articles.length; i = i + 2) {
if ((i + 1) <= articles.length) {
var option = new Option( /* Label */ articles[i + 1], /* Value */ articles[i]);
document.getElementById("article_id").options.add(option);
}
}
for (var i = 0; i < quizes.length; i = i + 2) {
if ((i + 1) <= quizes.length) {
var option = new Option( /* Label */ quizes[i + 1], /* Value */ quizes[i]);
document.getElementById("quiz_id").options.add(option);
}
}
delete req, articles, quizes;
} else {
document.getElementById("catdiv").innerHTML += req.responseText;
document.getElementById("allchildren").value = req.responseText;
}
} else { //failed to get response
alert("Problem: " + req.statusText);
}
}
document.getElementById("catdiv").innerHTML += "Y U NO COMPLETE?!";
}

req.onreadystatechange = targetDiv();
should be
req.onreadystatechange = targetDiv;
The original code calls targetDiv() immediately after that line of code is run, which is probably not what you wanted to do. The fixed code calls the function correctly, after the Ajax request is received.

Related

err_empty_response error when clicking a button

I have a website, and all its files (html/js/css/php) are on the same remote host. I have a button on the site, when clicked it sends a httprequest to a PHP file, waiting for a response.
My site works perfect almost everywhere, but there is one place which when I connect to the wi-fi, when clicking the button it return whit the error ERR_EMPTY_RESPONSE. Other buttons and PHP files work. It is only this specific button and in this specific wi-fi.
Does anyone know why does it happen and how to fix it?
details:
the button is <button class="btn btn-default col-sm-5" type="submit">
the onClick function:
function search() {
var param = "";
var firstParam = true;
var form = document.getElementById("formCS");
var name = document.getElementById("songName").value.trim();
if (name != "") {
firstParam = false;
param += "name=" + name;
}
var creator = document.getElementById("creator").value.trim();
if (creator != "") {
if (firstParam) {
param += "creator=" + creator;
firstParam = false;
} else {
param += "&creator=" + creator;
}
}
var type;
if (document.getElementById("partners").checked) {
type = "partners";
} else if (document.getElementById("circle").checked) {
type = "circle";
} else if (document.getElementById("lines").checked) {
type = "lines";
} else if (document.getElementById("none").checked) {
type = "";
}
if (type != "") {
if (firstParam) {
param += "type=" + type;
firstParam = false;
} else {
param += "&type=" + type;
}
}
var year = document.getElementById("year").value;
if (year != "none") {
if (firstParam) {
param += "year=" + year;
} else {
param += "&year=" + year;
}
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
handleResponse(xhttp.response);
}
};
xhttp.open("GET", "search.php?" + param, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
the search.php file connects to a DB on the remote host and runs a sql query. nothing different from other buttons on the site.
the wi-fi is a free wi-fi provided by an academic institue.
after clicking the button there is an error in the console:
GET http://rikudim.info/search.php? net::ERR_EMPTY_REPONSE

How can i validate file type using ajax in codeigniter

I am working on Codeigniter, i am facing one problem i have to show the user error message when he is uploading any other file type to server using ajax. I do not want to load view again to show the error message. My code is as follows:
Please help me to solve my problem.'
View:
function upload_video_Data(a)
{
var fd = new FormData(document.getElementById('posting_comment_'+a));
fd.append("file_m_id",a);
var bar = $('.bar');
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById("nameTest").value=xhr.responseText;
}
}
xhr.open("POST", "Dashboard/do_upload_video");
xhr.send(fd);
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
$("#status").animate( { width: percentComplete.toString()+"%"}, 5);
}
}
}
Controller:
public function do_upload_video()
{
$lecture_id=$_POST['file_m_id'];
$output_dir = "./uploads/";
$fileName = $_FILES["save_movie_".$lecture_id]["name"];
if(!move_uploaded_file($_FILES["save_movie_".$lecture_id]["tmp_name"],$output_dir.$fileName))
{
echo '0';
}
else
{
echo '1';
}
}
Use this code before your ajax to validate the extension of file
var ext = $('#my_file_id').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
Now your code look like this
function upload_video_Data(a)
{
var ext = $('#my_file_id').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
return false;
}
var fd = new FormData(document.getElementById('posting_comment_'+a));
fd.append("file_m_id",a);
var bar = $('.bar');
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById("nameTest").value=xhr.responseText;
}
}
xhr.open("POST", "Dashboard/do_upload_video");
xhr.send(fd);
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
$("#status").animate( { width: percentComplete.toString()+"%"}, 5);
}
}
}

Autocomplete URL AJAX

I want to know where is gsmarena.com put ajax url when they do a search. I tried to explore the source of it and I found this function:
function autocompleteLoadList() {
if (AUTOCOMPLETE_LIST !== null) return;
AUTOCOMPLETE_LIST = false;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP")
} catch (x) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
} catch (x) {
AUTOCOMPLETE_LIST = null
}
}
}
xhr.open("GET", AUTOCOMPLETE_LIST_URL, true);
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4)
if (xhr.status == 200) {
var data;
if (window.JSON) {
data = JSON.parse(xhr.responseText)
} else {
data = eval("(" + xhr.responseText + ")")
}
AUTOCOMPLETE_MAKERS = data[0];
AUTOCOMPLETE_LIST = data[1];
if (typeof AUTOCOMPLETE_CALLBACK != "undefined") AUTOCOMPLETE_CALLBACK()
} else {
AUTOCOMPLETE_LIST = null
}
};
xhr.send(null)
}
http://cdn2.gsmarena.com/w/js/autocomplete.js?ver=2
I do not know where they put the url to doing a search.
when I open the network tab in Google Chrome console there is also no url to POST or GET. how could they do it?

JavaScript AJAX PHP issue

Ok. I need help with this. For some reason the onreadystatechange is fired multiple times. I really need to get this figured out tonight. It's the last task I have left and I don't know what to do or what's causing it. Please help.
I'm using AJAX (ndhr) to send over JSON 'Y-m-d h:i:s' to PHP to use the strtotime() function to return 'm-d-Y' back through AJAX. The JSON and PHP work great, but when the onreadystatechange is fired it does it multiple times. Almost like the readyState == 4 more times than it does.
var divs_d = ["d_2009", "d_2010", "d_2011"];
function ajax_get_json(cdiv,ocdv,ed){
var hr = new XMLHttpRequest();
hr.open("GET", "/json/sample.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
cdiv.innerHTML = "";
var data = JSON.parse(hr.responseText);
var cad = data.comm_archive;
var rndate;
var nda = new Array();
var ndac = 0;
var ec = 0;
for (ni = 0; ni < cad.length; ni++) {
if (cad[ni].year == ocdv) {
ec = ec + 1;
ed.innerHTML = '<h4>' + ocdv + ' (' + ec + ' entries)</h4>';
var ndhr = new XMLHttpRequest();
var url = "/inc/strtotime.php";
var vars = "ndate=" + cad[ni].publish_date;
ndhr.open("POST", url, true);
ndhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ndhr.onreadystatechange = function () {
if (ndhr.readyState == 4 && ndhr.status == 200) {
nda[ndac] = ndhr.responseText;
ndac = ndac + 1;
}
}
ndhr.send(vars);
}
}
nda.sort(function (a, b) { return b - a });
for (ndai = 0; ndai < ndac; ndai++) {
cdiv.innerHTML += '<h4>' + nda[ndai] + '</h4>';
}
}
}
hr.send(null);
}
function optionCchange() {
var ocdv = document.getElementById("optionCdate").value;
var ed = document.getElementById("ediv");
for (i = 0; i < divs_d.length; i++) {
var cdiv = document.getElementById(divs_d[i]);
if (divs_d[i] == "d_" + ocdv) {
cdiv.className = "bddiv show";
ajax_get_json(cdiv,ocdv,ed);
} else {
cdiv.className = "bddiv hide";
}
}
}
In your ndhr.onreadystatechange function ndhr represents the last ndhr created in the loop not the calling one, to reference the calling object use this.
ndhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
nda[ndac] = this.responseText;
ndac = ndac + 1;
}
}
The the last for(ndai = 0; ndai < ndac; ndai++) is behaving as you expect because of the asynchronous nature of ajax, by the time that code is executed the ajax requests have not finished yet. You'll have to execute this code in the on ready change state callback. Just use a counter to check if all the ajax requests have finished then execute the code.
If you need run the code once, you don't have to be anxious about how many times readystate 4 was fired. Simply use a boolean variable to check if the block of code has been executed.
Here's a pseudocode example of my idea.
executed = false;
if (readystate && (executed == false))
{
blablabla;
executed = true;
}
else
{
sry your code has been executed;
}

2 javascript functions clashing?

I am trying to implement a Javascript/PHP/AJAX clock into my website so that I can have a simple clock which can operate in different timezones (tutorial is here http://networking.mydesigntool.com/viewtopic.php?tid=373&id=31)
This itself works fine, but I already have a javascript stopwatch running on the page, and the 2 seem to clash and the clock won't display while the stopwatch is working.
This is the script for the clock:
<script type="text/javascript">
function loadTime ()
{
http_request = false;
if(window.XMLHttpRequest)
{
// Mozilla, Safari,...
http_request = new XMLHttpRequest();
if(http_request.overrideMimeType)
{
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
}
else if(window.ActiveXObject)
{ // IE
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
}
}
}
var parameters = "time=";
http_request.onreadystatechange = alertContents;
http_request.open('POST', 'time.php', true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents()
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
result = http_request.responseText;
document.getElementById('clock').innerHTML = result;
}
}
}
</script>
<body onload="setInterval('loadTime()', 200);">
and this is the code for the stopwatch:
<script type="text/javascript">
window.onload = function()
{
stopwatch('Start');
}
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
min = min + 1;
} else {
min = min;
}
if (min == 60) {
min = 0;
hour += 1;
}
if (sec<=9) { sec = "0" + sec; }
document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
if (text == "Start") { document.clock.theButton.value = "Stop "; }
if (text == "Stop ") { document.clock.theButton.value = "Start"; }
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
return true;
}
SD=window.setTimeout("stopwatch();", 1000);
}
function resetIt() {
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop ") {
document.clock.theButton.value = "Start";
}
window.clearTimeout(SD);
}
</script>
Could someone help me get them to work side-by-side please?
Thanks for any help
For one, your’re declaring an onload event handler in your HTML:
<body onload="setInterval('loadTime()', 200);">
which is consequently overwritten in script:
window.onload = function()
{
stopwatch('Start');
}
This means the original onload call is never executed.
You should try using addEventListener so you can add multiple event handlers to the same event.
A couple more points:
Don’t pass a string to setInterval and setTimeout, just pass the function itself. More efficient and less error-prone: setInterval(loadTime, 200);
Instead of writing all that JS code to work with different browsers, use jQuery, mootools, or one of the gazillion other frameworks. They make it a lot easier to get it right on all browsers.
Try this:
See the subtle '+=' instead of '=' !
window.onload += function()
{
stopwatch('Start');
}

Categories