Search code examples
phpajaxajax-request

AJAX data not sent to the PHP file


I have a problem in my AJAX . My javascript file is unable to send data to the PHP file. My javascript file :

function updateTile(tile_no){

    var ajaxRequest;

    var color = document.getElementById("color_"+tile_no).value;
    //alert($color);
    var img_path = document.getElementById("url_"+tile_no).value;
    //alert(url);
    var title = document.getElementById("title_"+tile_no).value;

    try{

    ajaxRequest = new XMLHttpRequest();
    } catch (e){

        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){

                alert("Browser Error !");
                return false;
            }
        }
    }

    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){


            document.getElementById("box_tile"+tile_no).innerHTML = ajaxRequest.responseText;
        }
        else
        {
            document.getElementById("box_tile"+tile_no).innerHTML = '<img src=ajax-loader.gif /> <br /> ';
        }
    }

    var url = "update.php?color="+color+"&url="+img_path+"&img_path="+title;

    alert(url);

    ajaxRequest.open("GET", url, true);
    ajaxRequest.send(null); 
}

The alert(url); shows update.php?color=#444444&url=http://somesite/image.jpg&img_path=Tile 1. My update.php file :

<?php


    $color_code = $_GET['color'];

    $img_url = $_GET['img_path'];

    $title = $_GET['title'];

    echo 'Color Code :'.$color_code;
    echo '<br />Image Path :'.$img_url;
    echo '<br />Title :'.$title;

/*
echo '<div style="background:'.$color_code.';width:100%;height:100%;vertical-align:bottom;color:#f8f8f8;font-family:Trebuchet MS;"><img src="'.$img_url.'" /><span>'.$title.'</span></div>';
*/  
?>

But the response from the PHP shows empty results !

Color Code :
Image Path :
Title :

Solution

  • You should encode the image path as it is a url and the colour as it contains a # (use encodeURIComponent)

    Your query string seems all messed up, you pass color, url and img_path but expect color, img_path and title

    Also

    var url = "update.php?color="+encodeURIComponent(color)+
              "&img_path="+encodeURIComponent(img_path)+"&title="+title;