responseText is working but responseXML is null - php

I am trying to open an XML file with Ajax. Its responseText is working fine but responseXML is returning null. I checked the syntax, there is nothing wrong with the syntax. I don't know what the problem is. Here is my code...
My HTML code
<div id='albumBox'>
<input type='file' multiple name='newsfeedAlbum[]' id='newsfeedAlbum' onchange='uploadNewsfeedImages()' />
</div>
<div id='uploadingImages'>
<progress id='newsfeedImageProgressBar'></progress>
</div>
<div>
<input type='button' id='albumButton' value='post' />
</div>
my JavaScript code…
function uploadNewsfeedImages()
{
//alert("loaded");
var files = document.getElementById("newsfeedAlbum").files;
var formData = new FormData();
var unixTimeStamp = Math.floor(((new Date).getTime())/1000);
formData.append("action","post");
formData.append("thing","album");
formData.append("unixTimeStamp",unixTimeStamp);
formData.append("album_to","news_feed");
for(var i = 0;i < files.length;i++)
{
var file = files[i];
//alert("file name is "+files.item(i).name);
formData.append("albumImages[]",file);
}
var xhr = new XMLHttpRequest();
xhr.open("POST","add_newsfeed.php",true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
//alert(xhr.responseText);
alert(xhr.responseXML);
}
}
xhr.upload.onprogress = function(event)
{
showProgress(xhr,event);
}
xhr.send(formData);
}
function showProgress(xhr,event)
{
var uploaded = event.loaded/event.total;
uploaded = Math.floor(uploaded*100);
//alert(uploaded);
document.getElementById("newsfeedImageProgressBar").value = uploaded;
}
Here is my php code...
session_start();
echo '<?xml version="1.0" encoding="UTF-8"?>';
header("Content-type: text/xml");
if(isset($_POST))
{
echo "<newsfeed>";
$action = $_REQUEST["action"];
if($action == "post")
{
$thing = $_REQUEST["thing"];
if($thing == "text")
{
}
elseif($thing == "album")
{
$succeded = array();
$failed = array();
$targetFolder = "images/";
$extensions = array("jpeg","jpg","bmp","png","gif");
foreach($_FILES["albumImages"]["name"] as $key=>$value)
{
//echo $key."=>".$value."<br />";
if($_FILES["albumImages"]["error"][$key] === 0)
{
$extension = strtolower(pathinfo($value,PATHINFO_EXTENSION));
if(in_array($extension,$extensions))
{
$source = $_FILES["albumImages"]["tmp_name"][$key];
$destination = $targetFolder.basename($value);
if(move_uploaded_file($source,$destination))
{
$succeded[] = $value;
}
else
{
$failed[] = $value;
}
}
else
{
$failed[] = $value;
}
}
else
{
$failed[] = $value;
}
}
if(count($succeded)>0)
{
echo "<succeded>";
for($i=0;$i<count($succeded);$i++)
{
echo "<succeded_file>".$succeded[$i]."</succeded_file>";
}
echo "</succeded>";
}
if(count($failed)>0)
{
echo "<failed>";
for($i=0;$i<count($failed);$i++)
{
echo "<failed_file>".$failed[$i]."</failed_file>";
}
echo "</failed>";
}
}
}
echo "</newsfeed>";
}
?>

It's probably because the content type of the file coming back from the sever is not xml.
Try using header('Content-Type: text/xml'); in your PHP code.

Related

Ajax requests out of memory

So I am working on this project where I have to make a photo sharing site, I select the photos and then upload them, send the link via email, and then the person goes on the link and downloads the photos. Everything works great when I have few photos and when not exceeding 100MB of data, when I go beyond that everything becomes unstable.
First of I am using HTML5's FileReader().The logic is the following:
I use FileReader() to transform each photo into a base64 code and every 3 photos transformed I send a 3 photos long base64 string via Ajax to a php file which then transforms the code into photos and uploads them into a folder on the server.
If I have 300 photos selected I do 100 ajax requests.
The first problem if if I exceed ~150MB of data ajax will give me an uncaught exception out of memory error.
The second problem is if I chose over 20-30 files the brower some times gets unresponsive even crashes..
Any suggestions what can I do ? Maybe the whole idea is wrong and I should start somewhere else, please help.
This is the code:
//Forming the inputs
$(document).on("change","#fileUp",function(e){
var file = null;
var files = e.target.files; //FileList object
var picReader = new FileReader();
$(".eventPop").html("");
$(".howMany").html("");
$(".eventPop").show();
$(".eventPop").append('<div class="adding"><img src="../public/cuts/uploading.gif" width="60px"></div>');
countUp = parseInt(countUp) + parseInt(files.length);
for(var i=0; i<=files.length-1; i++){
file = files[i];
var str = file.name.split(".")[0];
//
//var picReader = new FileReader();
if (file.type == "image/jpeg" || file.type == "image/png")
{
picReader.addEventListener("load",function(event){
count++;
var picFile = event.target;
$(".photos").append("<input type='hidden' id='ph"+count+"' get='"+picFile.result+"' /> ");
});
}
else
{
countUp--;
}
picReader.readAsDataURL(file);
}
});
//actual ajax requests
$(document).on('click','.uploadImages',function(){
info[1] = "4hold"+1 + Math.floor(Math.random() * 999999)+"_"+(new Date).getTime();
$.ajax({
type: "POST",
url: "index/loadIntoDB",
dataType:"text",
data: {info: info},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(result){
}
});
if (nrConfig > count)
{
nrConfig = count;
}
$(".eventPop").show();
$(".eventPop").html("");
$(".eventPop").append('<div class="adding"><p>Uploading files...'+( (nrConfig/count) * 100).toFixed(0)+'%</p></div>');
for(var i=1; i<=parseInt(nrConfig)+1; i++)
{
if (i == parseInt(nrConfig)+1)
{
info[2] = info[2].substring(2, info[2].length);
uploadImages(nrConfig,1);
}
else
{
//info[0] = i+"-"+info[0];
info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
}
}
});
function uploadImages(i,d){
info['3'] = i;
info['4'] = d;
$.ajax({
type: "POST",
url: "index/receiveImages",
dataType:"json",
data: {info : info },
beforeSend : function (){
//
},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(result){
for(index=result['leftOff']['1']; index <= result['info']['4']-1; index++)
{
if (result[index]['filesize'] < 1000000)
{
result[index]['filesize'] = Math.floor(result[index]['filesize']/1000)+"kb";
$("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
}
else
{
result[index]['filesize'] = (result[index]['filesize']/1000000).toFixed(2)+"MB";
$("#ph"+result[index]['id']).append("<div class='filesize'>"+result[index]['filesize']+"</div>");
}
if (result[index]['filesize'].length > 0)
{
$("#ph"+result[index]['id']+" .uploading").remove();
$("#ph"+result[index]['id']).append("<img src='layout/cuts/check.png' title='Uploaded' class='done'>");
$("#ph"+result[index]['id']+" .upd").remove();
}
}
$(".eventPop").html("");
$(".eventPop").append('<div class="adding"><p>Uploading files...'+( (result['info'][4]-1)/count * 100).toFixed(0)+'%</p></div>');
if (((result['info'][4]-1)/count * 100).toFixed(0) == 100)
{
setTimeout(function(){
$("progress").remove();
$(".eventPop").html("");
$(".eventPop").append("<div class='adding'>Upload complete!</div>");
setTimeout(function(){
$(".eventPop").html("");
$(".eventPop").append("<div class='adding'><div class='sendPhotos'><form action='#' onsubmit='return false;' method='post' enctype='multipart/form-data'><label>Your email</label><input type='text' class='yemail'/><br/><label>Friend's email</label><input type='text' class='fremail'/><br/><span class='tip'><div class='triangle'></div>You can send photos to multiple friends by typing their e-mail separated by ';'.<br/>Eg. 'thomas#gmail.com ; peter#gmail.com'</span><input type='submit' name='send' class='send' value='Send'></form></div></div>");
},1000);
},1000);
}
if (info[2].length)
{
info[2] = "";
}
if ( (parseInt(result['info']['4'])+parseInt(nrConfig)) >= count )
{
nrConfig = count-result['info']['4']+1;
}
if(result['info']['4'] <= count)
{
for(i=result['info']['4']; i <= parseInt(result['info']['4'])+parseInt(nrConfig); i++)
{
if (i == parseInt(result['info']['4'])+parseInt(nrConfig))
{
info[2] = info[2].substring(2, info[2].length);
uploadImages(nrConfig,result['info']['4']);
}
else
{
info[2] = info[2]+"--"+$("#ph"+i+"").attr("get");
}
}
}
}
});
}
PHP code:
public function receiveImages()
{
$string = strtok($_POST['info'][2],"--");
$currentID = $_POST['info']['4'];
$newArray['info']['3'] = $_POST['info']['3'];
$newArray['leftOff']['1'] = $currentID;
$phAdded = 0;
while($string != false && $phAdded < $_POST['info']['3'])
{
$newArray[$currentID]['id'] = $currentID;
$newArray[$currentID]['filesize'] = $this->saveImages($string,$_POST['info']['1'],$currentID);
$currentID++;
$phAdded++;
$string = strtok("--");
}
$newArray['info']['4'] = $currentID;
echo json_encode($newArray);
}
public function saveImages($base64img = "",$folder = "",$currentID = "")
{
$newArray = array();
if (!is_dir(UPLOAD_DIR.$folder))
{
mkdir(UPLOAD_DIR.$folder,0777);
}
$dir = UPLOAD_DIR.$folder."/";
if (strstr($base64img,'data:image/jpeg;base64,'))
{
$base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
$uniqid = uniqid();
$file = $dir . $uniqid . '.jpg';
$file_name = $uniqid.".jpg";
}
else
{
$base64img = str_replace('data:image/png;base64,', '', $base64img);
$uniqid = uniqid();
$file = $dir . $uniqid . '.png';
$file_name = $uniqid.".png";
}
$data = base64_decode($base64img);
file_put_contents($file, $data);
$size = filesize($file);
if ($size > 1000000)
{
$size = number_format(($size/1000000),2)."MB";
}
else
{
$size = number_format(($size/1000),0)."kb";
}
return filesize($file);
}

Captcha php to js validation

I have written in php I want to write this code, but there is an error in the function onclick javascript
<?php
if(isset($_POST["captcha"]))
{
if($_POST["captcha"]==$_SESSION["code"])
{
echo "Correct";
}
else
{
echo "Not Correct";
}
}
?>
Javascript
function ja_k2filter_submit()
{
var captcha = $('captcha');
var code = $('code');
if ($code = '');
{
alert("Güvenlik Kodunu Doğrulayınız!");
}
return false;
if ($code = captcha);
if($('input_searchword'))
{
input = $('input_searchword');
v_label = ($$('label[for=input_searchword]')[0].innerHTML)+'...';
if((input.value !='')&&(input.value!=v_label))
{
$('mod_ja_searchword').value =input.value;
}
}
javascript values ​​but does not

Error deleting image with AJAX and PHP using unlink

I am trying to delete a selected image from a folder with AJAX and PHP. I have not seen any error, could you please tell me your opinion about the code I have?
Thanks in advance
AJAX code:
function createAjax()
{
var objAjax = false;
if (window.XMLHttpRequest)
{
objAjax = new XMLHttpRequest ();
}
else
{
if (window.ActiveXObject)
{
try
{
objAjax = new ActiveXObject ("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
objAjax = new ActiveXObject ("Microsoft.XMLHTTP");
}
catch (e)
{
}
}
}
else
{
objAjax = false;
}
}
return objAjax;
}
function eliminar(id_foto)
{
var ajax = createAjax();
ajax.open("POST", "delete_img.php",true);
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4)
{
//AQUI DEBES DE PONER EL CODIGO RESPECTIVO PARA ELIMINAR DEL NAVEGADOR
// EL DIV EN CUESTION o simplemente hacer su contenido vacio, que es lo que hare
document.getElementById("delete"+id_foto).innerHTML = "";
document.getElementById("div_mensajes").innerHTML
}
else
{
document.getElementById("div_mensajes").innerHTML = "<br><center>Eliminando<img src = 'images/ajax-loader.gif' /></center>";
}
}
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.send("id_foto="+id_foto);
}
HTML and PHP code to display it first:
$handle = opendir(dirname(realpath(__FILE__)).'/uploads/');
while($file = readdir($handle)) {
if($file !== '.' && $file !== '..') {
if(file_exists('uploads/Thumbs.db')){
unlink('uploads/Thumbs.db');
}
echo'<div class="gallery-item" id="delete'.$file.'">
<p class="gallery-clean">
<a class="image" rel="'.$file.'" rev="'.$file.'" href="uploads/'.$file.'" title="">
<img src="uploads/'.$file.'" alt="'.$file.'"></a></p>
<div>
<a class="ico ico-delete" rel="9" rev="2" href="#" onclick = "eliminar_ajax('.$file.');"><span></span></a>
<a class="ico ico-edit" rel="9" href="#"><span></span></a>
<a class="ico ico-resize" rel="9" href="#"><span></span></a>
<a class="ico ico-full" rel="group" href="#"><span></span></a>
</div></div>';
}
}
PHP code to delete the file:
$dir = "uploads/";
$file = $_POST['id_foto'];
$img = $dir.$file;
unlink($img);
Ok! I have solved using this:
script type="text/javascript">
function deleteFile(fname,directory)
{
$.ajax({ url: "delete_img.php",
data: {"file":fname,"directory":directory},
type: 'post',
success: function(output) {
alert(output);
$("#delete"+file).remove();
}
});
}
</script>
How can I remove the div if I call it
#delete.'<?php echo $file?>
And what is the extension of your image? Add it to $file like so $file .= ".whateverextensionithas";
To be more clear
$dir = "uploads/";
$file = $_POST['id_foto'];
$file .= ".whateverextensionithas";
$img = $dir.$file;
unlink($img);
Or to be real clear
$dir = "uploads/";
$ext = ".whateverextensionithas";
$file = $dir.$_POST['id_foto'].$ext;
if(file_exists($file))
unlink($file);
else
echo "file does not exist";
Try this piece of code:
if(isset($_POST['id_foto'])){
$dir = "uploads/";
$file = $_POST['id_foto'];
$img = $dir.$file;
$f = fopen($dir."post.txt", 'w+');
fwrite($f, $img);
fclose($f);
}
and inspect post.txt to see what sort of output you get.

PHP and AJAX onclick redirection

I am using Ajax to populate a drop down menu from the database, my question is how do I onclick redirect it to a page along with the CARD_ID i got back from the database?
right now when I click on it it's displaying the card name in the search bar which is part of what I want but now I need the other half the redirection. How can I achieve this?
<?php
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$str = $_GET['content'];
if(strlen($str))
{
$sel = mysqli_query($mysqli, "select CARD_NAME, CARD_ID,CARD_TYPE from cards where CARD_NAME like '".trim($str)."%'");
if(mysqli_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysqli_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysqli_fetch_array($sel))
{
$card_info = str_ireplace($str,"<b>".$str."</b>",($row['CARD_NAME']));
$card_type = str_ireplace($str,"<b>".$str."</b>",($row['CARD_TYPE']));
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\" onClick=\"display('".$row['CARD_NAME']."');\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
the javascript.
subject_id = '';
function handleHttpResponse() {
if (http.readyState == 4) {
if (subject_id != '') {
document.getElementById(subject_id).innerHTML = http.responseText;
}
}
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
function getScriptPage(div_id,content_id)
{
subject_id = div_id;
content = document.getElementById(content_id).value;
http.open("GET", "script_page.php?content=" + escape(content), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
if(content.length>0)
box('1');
else
box('0');
}
function highlight(action,id)
{
if(action)
document.getElementById('word'+id).bgColor = "#C2B8F5";
else
document.getElementById('word'+id).bgColor = "#F8F8F8";
}
function display(word)
{
document.getElementById('text_content').value = word;
document.getElementById('box').style.display = 'none';
document.getElementById('text_content').focus();
}
function box(act)
{
if(act=='0')
{
document.getElementById('box').style.display = 'none';
}
else
document.getElementById('box').style.display = 'block';
}
the html
<div class="ajax-div">
<div class="searchbar">
<input type="text" onKeyUp="getScriptPage('box','text_content')" id="text_content">
</div>
<div id="box"></div>
</div>
I'm not sure what you are trying to do, but it seems you want something like this:
1- Change the way you display your rows so that the ID gets sent to your function as well:
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\"
onClick=\"display('".$row['CARD_NAME']."', " . $row['CARD_ID'] . ");\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
^^^^^^^^^^^^^^^^^^^^^^^^^
2- Change your display function to redirect
function display(word, id)
{
// document.getElementById('text_content').value = word;
// document.getElementById('box').style.display = 'none';
// document.getElementById('text_content').focus();
window.location.href = "some_page.php?card_id=" + id;
}
I have commented out the original lines because there doesn't seem much point in doing stuff on a page you are leaving anyway. You could also completely remove the word parameter if this is the solution you are looking for.

loading page through AJAX

<form>
<table>
<tr>
<td>
<input type="tex" id="arheading" name="arheading" value="Article Heading" onfocus="if (this.value == 'Article Heading') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Article Heading';}" />
</td>
<td>
<select id="plaetype" name="placetype">
<option selected="Place Type">Place Type</option>
<?php
include 'ini/configs_adm.php';
$result_adm = mysql_query("SELECT * FROM places");
while($row_adm=mysql_fetch_array($result_adm))
{
echo '<option value="'.$row_adm['places'].'">'.$row_adm['places'].'</option>';
}
?>
</select>
</td>
<td>
<select id="country" name="country">
<?php
include 'ini/configs_adm.php';
$result_adm = mysql_query("SELECT * FROM countries");
while($row_adm=mysql_fetch_array($result_adm))
{
echo '<option value="'.$row_adm['country'].'">'.$row_adm['country'].'</option>';
}
?>
</select>
</td>
</tr>
</table>
</form>
Above is the code that i want to load on my index page without refreshing or without navigation through AJAX.
and the ajax code i tried to is.........
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
function ajaxpage(url, containerid) {
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) { // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e) {
try {
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e) {
}
}
}
else
return false
page_request.onreadystatechange = function () {
loadpage(page_request, containerid)
}
page_request.open('GET', url, true)
page_request.send(null)
}
function loadpage(page_request, containerid) {
if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
document.getElementById(containerid).innerHTML = page_request.responseText
}
function loadobjs() {
if (!document.getElementById)
return
for (i = 0; i < arguments.length; i++) {
var file = arguments[i]
var fileref = ""
if (loadedobjects.indexOf(file) == -1) { //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js") != -1) { //If object is a js file
fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css") != -1) { //If object is a css file
fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref != "") {
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects += file + " " //Remember this object as being already added to page
}
}
}
and the code that will call for AJAX function is.....
<ul id="admin_menu">
<?php
include 'ini/configs_adm.php';
$result_adm = mysql_query("SELECT * FROM adm_tools");
while ($row_adm = mysql_fetch_array($result_adm))
{
echo '<li>' . $row_adm['adm_menu'] . '</li>';
}
?>
</ul>
My ajax code have loaded the page but the php script is not retrieving data from db
It looks like you might be missing the extract($row) function.
That would look like:
while($row_adm=mysql_fetch_array($result_adm))
{
extract($row_adm);
echo '<option value="'.$row_adm['places'].'">'.$row_adm['places'].'</option>';
}

Categories