/    Sign up×
Community /Pin to ProfileBookmark

Why is my function not working?

I have a function:

[CODE]function deleteimage1(){
var image1Field = document.getElementById(‘image1’);
upload_field.form.action = ‘imagedelete.php’;
upload_field.form.target = ‘upload_iframe’;
upload_field.form.submit();
upload_field.form.action = ”;
upload_field.form.target = ”;
return true;
}[/CODE]

I am trying to get the value of field with ID ‘image1’ and then post the value to the imagedelete.php file so I can delete an image without refresh.

This is not working??? Can anybody please help me?

to post a comment
JavaScript

8 Comments(s)

Copy linkTweet thisAlerts:
@KDLASep 23.2009 — I might be wrong, but javascript and PHP don't work together well -- or pretty much don't work together at all.
Copy linkTweet thisAlerts:
@StefanRSAauthorSep 23.2009 — I am sure I can proof you wrong! I have a php file that uses js to update Iframes with uploaded images (With php) without refreshing the php page....

Now I am just trying to delete the uploaded images without refresh....

Why do you say they don't work together???
Copy linkTweet thisAlerts:
@KDLASep 23.2009 — You're trying to detect a variable with one and pass to the other. My experience has taught me that you can't detect a variable with javascript and try to pass it to a server-side script/action. I could be wrong -- my experience was with .NET, but since they're both server-side languages....
Copy linkTweet thisAlerts:
@StefanRSAauthorSep 23.2009 — Ok, i understand... I need someone that knows php as well then to help me.....

?

I can post examples if you like
Copy linkTweet thisAlerts:
@jamesbcox1980Sep 23.2009 — Well, it looks like you're setting a variable to be the image that's getting deleted. What does this accomplish? Did you mean to send that image's URL to the PHP file? If so, you need to set the value of an existing INPUT tag to the image's "src"

[CODE]
function deleteimage1(){

//set the image's src to the src of the image to be deleted
var image1SRC = document.getElementById('image1').src;

//Create a hidden field to put that URL in
var image1Field=document.createElement('input');
image1Field.type='hidden';
image1Field.name='imagesrc';
image1Field.value=image1SRC;

//Now insert that input into the form
upload_field.form.appendChild(image1Field);

//Submit the form--Why not use AJAX to do this instead of an iFrame?
upload_field.form.action = 'imagedelete.php';
upload_field.form.target = 'upload_iframe';
upload_field.form.submit();
upload_field.form.action = '';
upload_field.form.target = '';
return true;
}[/CODE]


Now, on the PHP side, you'll need to access the variable that you just sent. If your form method is POST (which it should be in this case), then your form variables are accessed in PHP by $_POST['variableName']. It's possible that if the correct PHP extension is turned on, you can simply put $ in front of the variable name and use it without $_POST[]. Anyway, here's the PHP code:

[code=php]<?php
try{
unlink($_POST['imagesrc']);
}catch(Exception $e){
echo '<script type="text/javascript">alert("Caught exception: ', $e->getMessage(), '");</script>'; //or anything you want to happen if the delete is not sucessful
?>
[/code]
Copy linkTweet thisAlerts:
@jamesbcox1980Sep 23.2009 — You're trying to detect a variable with one and pass to the other. My experience has taught me that you can't detect a variable with javascript and try to pass it to a server-side script/action. I could be wrong -- my experience was with .NET, but since they're both server-side languages....[/QUOTE]

Oh and yes, KDLA, you are wrong. You can pass variables to PHP EXTREMELY easily. You send them in a POST or GET form, or even Cookie. PHP is awesome at reading passed variables. In fact, it's even better than javascript. I had to write a function solely dedicated to getting the variables out of the URL from a query in Javascript. In PHP it's as simple as $_GET['variableName'] or even $variableName in some cases (assuming REGISTER GLOBALS is turned on). PHP and JavaScript don't necessarily work together in harmony... they work together in tandem. But they [B]DO[/B] work together.
Copy linkTweet thisAlerts:
@StefanRSAauthorSep 23.2009 — HEY! Thanks James!

I will jump into your solution this moment and try it...

I looks like it is the answer I was looking for... Will keep you guys posted.

Thanks
Copy linkTweet thisAlerts:
@StefanRSAauthorSep 23.2009 — I am still doing something wrong???

(I am working with IFrame as this is the only image upload function that I could get to work in the background up to now... (I am actually VERY new in PhP coding and am a self learner.... Guys like you are my mentors! :o )

I am trying to call the function from a link that is created in the Iframe on upload.... The files I have created thus far is:

  • 1. The "testaup.php" form (This is the main form)
    [CODE]<html>
    <head>
    <title>Image Upload and Preview without Page Refresh TEST</title>
    <script type="text/javascript">
    function deleteimage1(){
    //set the image's src to the src of the image to be deleted
    var image1SRC = document.getElementById('image1').src;

    //Create a hidden field to put that URL in
    var image1Field=document.createElement('input');
    image1Field.type='hidden';
    image1Field.name='imagesrc';
    image1Field.value=image1SRC;

    //Now insert that input into the form
    upload_field.form.appendChild(image1Field);

    //Submit the form--Why not use AJAX to do this instead of an iFrame?
    upload_field.form.action = 'imagedelete.php';
    upload_field.form.target = 'upload_iframe';
    upload_field.form.submit();
    upload_field.form.action = '';
    upload_field.form.target = '';
    return true;
    }
    function ajaxFileUpload(upload_field)
    {
    // Checking file type
    var re_text = /.jpg|.gif|.jpeg/i;
    var filename = upload_field.value;
    if (filename.search(re_text) == -1) {
    alert("File should be either jpg or gif or jpeg");
    upload_field.form.reset();
    return false;
    }
    document.getElementById('picture_preview').innerHTML = '<div><img src="../images/loader_light_blue.gif" border="0" /></div>';
    upload_field.form.action = 'ajaxupload.php';
    upload_field.form.target = 'upload_iframe';
    upload_field.form.submit();
    upload_field.form.action = '';
    upload_field.form.target = '';
    return true;
    }
    </script>
    </head>

    <!-- iframe used for ajax file upload-->
    <iframe name="upload_iframe" id="upload_iframe" style="display:none;"></iframe>
    <!-- iframe used for ajax file upload-->

    <form name="pictureForm" method="post" autocomplete="off" enctype="multipart/form-data">
    <div>
    <span>Upload Picture :</span>

    <span id="picture_error"><input type="file" name="img1" id="picture" onchange="return ajaxFileUpload(this);" /></span><br>
    <span id="picture_preview"></span><br>
    <span id="preview_picture_tag" name="preview_picture_tag"></span>

    </div>
    </form>[/CODE]


  • 2. The "ajaxupload.php" form

    This form does the actual upload of the image and resize it to three new images and place it in 3 different folders. After successfull upload, the Iframes are updated with the uploaded 130px image as well as the link to call the delete function.
    [CODE]<?php
    include $root.'../incl/config.php';
    error_reporting(0);
    $pictot = 4;
    $change="Image Uploaded!";
    $imgNumb=1;
    define ("MAX_SIZE","1500");
    function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return $ext;
    }

    $errors=0;
    do{
    if($_FILES["img$imgNumb"]["tmp_name"]!=''){
    $image =$_FILES["img$imgNumb"]["name"];
    $uploadedfile = $_FILES["img$imgNumb"]['tmp_name'];


    if ($image)
    {

    $filename = stripslashes($_FILES["img$imgNumb"]['name']);

    $extension = getExtension($filename);
    $extension = strtolower($extension);


    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
    {

    $change='<div class="msgdiv">Unknown Image extension </div> ';
    $errors=1;
    }
    else
    {

    $size=filesize($_FILES["img$imgNumb"]['tmp_name']);


    if ($size > MAX_SIZE*1024)
    {
    $change='<div class="msgdiv">You have exceeded the size limit!</div> ';
    $errors=1;
    }


    if($extension=="jpg" || $extension=="jpeg" )
    {
    $uploadedfile = $_FILES["img$imgNumb"]['tmp_name'];
    $src = imagecreatefromjpeg($uploadedfile);

    }
    else if($extension=="png")
    {
    $uploadedfile = $_FILES["img$imgNumb"]['tmp_name'];
    $src = imagecreatefrompng($uploadedfile);

    }
    else
    {
    $src = imagecreatefromgif($uploadedfile);
    }

    echo $scr;

    list($width,$height)=getimagesize($uploadedfile);

    $newwidthX=520;
    $newheightX=($height/$width)*$newwidthX;
    if($newheightX > 520) {
    $newheight=520;
    $newwidth=($newwidthX/$newheightX)*$newheight;
    } else {
    $newheight = $newheightX;
    $newwidth = $newwidthX; }
    $tmp=imagecreatetruecolor($newwidth,$newheight);

    $newwidth1=130;
    $newheight1=($height/$width)*$newwidth1;
    $tmp1=imagecreatetruecolor($newwidth1,$newheight1);

    if ($imgNumb == 1){
    $newwidth2=65;
    $newheight2=($height/$width)*$newwidth2;
    $tmp2=imagecreatetruecolor($newwidth2,$newheight2);
    }

    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
    imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
    if ($imgNumb == 1){
    imagecopyresampled($tmp2,$src,0,0,0,0,$newwidth2,$newheight2,$width,$height);
    }
    /// SET IMAGE NAMES HERE!!!!!!!!!!!!!!!!!!!!!!!!!
    //$image_name=time().'.'.$extension;
    $Unique=microtime(); // We want unique names, right?
    $image_name=md5($Unique).'.'.$extension;
    $dbimgname=$imgNumb.'_'.$image_name;
    $filename = '../ad_images/'.$imgNumb.'_'.$image_name;
    $filename1 = '../ad_images/130/'.$imgNumb.'_'.$image_name;
    if ($imgNumb == 1){
    $filename2 = '../ad_images/65/'.$imgNumb.'_'.$image_name;
    }

    imagejpeg($tmp,$filename,70);
    imagejpeg($tmp1,$filename1,70);
    if ($imgNumb == 1){
    imagejpeg($tmp2,$filename2,70);
    }
    imagedestroy($src);
    imagedestroy($tmp);
    imagedestroy($tmp1);
    if ($imgNumb == 1){
    imagedestroy($tmp2);
    }
    }}
    //mysql update your database fields

    }

    $imgNumb++;
    } while($_FILES["img$imgNumb"][name]);
    ////////////////////////////////////////////////////////////////////////////////////////////////

    // This is a PHP code outputing Javascript code.
    echo '<script language="JavaScript" type="text/javascript">'."n";
    echo 'var parDoc = window.parent.document;';

    $deletebutton = ''; // Was trying to create a delete button??? Or will a link work???
    echo "parDoc.getElementById('picture_error').innerHTML = '<a href="javascript: void(#)" onclick="deleteimage1()">Delete Image</a><input type="hidden" id="image1" value="$dbimgname" name="image1"/>';";
    if($dbimgname != '') {
    echo "parDoc.getElementById('picture_preview').innerHTML = '<img src='../ad_images/130/$dbimgname' id='image1' name='preview_picture_tag' />';";
    echo "parDoc.getElementById('picture_id').innerHTML = '".$dbimgname."';";
    }

    echo "n".'</script>';
    exit(); // do not go futher

    ?>[/CODE]


  • 3. The "imagedelete.php" page - (This does not work)

    To fire of the delete function
    [CODE]<?PHP
    //try{
    // unlink($_POST['imagesrc']);
    //}catch(Exception $e){
    // echo '<script type="text/javascript">alert("Caught exception: ', //$e->getMessage(), '");</script>'; //or anything you want to happen if the //delete is not sucessful

    $deleteimage = $_POST['imagesrc'];
    $filename = "../ad_images/$deleteimage";
    $filename1 = "../ad_images/130/$deleteimage";
    $filename2 = "../ad_images/65/$deleteimage";
    unlink($filename);
    unlink($filename1);
    unlink($filename2);

    // This is a PHP code outputing Javascript code.
    echo '<script language="JavaScript" type="text/javascript">'."n";
    echo 'var parDoc = window.parent.document;';

    // Put the image upload field back
    echo "parDoc.getElementById('picture_error').innerHTML = '<input type="file" name="img1" id="picture" onchange="return ajaxFileUpload(this);" />';";
    if($dbimgname != '') {
    echo "parDoc.getElementById('picture_preview').innerHTML = '';";
    }

    echo "n".'</script>';
    exit(); // do not go futher

    ?>[/CODE]


    Hope you can help me here...



    Thanks
  • ×

    Success!

    Help @StefanRSA spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.19,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...