Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 950
  • Last Modified:

auto submit a form using jquery and php issue

Hello,

I'm unable to get the jquery .submit() to work the same as the html submit input.  
When I replace:
<button type="button" id="upload">Upload</button>
with:
<input type="submit" name="submit" value="Upload" id="submit"/>

the containing form with an id of uploadFrm is submitted to itself and then redirects to another page.  When I use a html button and attach a click event to it, the event gets called but the $("#uploadFrm").submit(); in the dialog save function never submits the form.  Any ideas?

<?php
	$folder = 'images/';
	$orig_w = 500;
	$caption = $_POST[caption]; 
	$albumCoverImage = $_POST[albumCoverImage]; 
	if( isset($_POST['submit']) )
	{
		$imageFile = $_FILES['image']['tmp_name'];
		$filename = basename( $_FILES['image']['name']);
		$info = pathinfo($folder.$filename);
		$fileext = $info['extension'];
		list($width, $height) = getimagesize($imageFile);		
		$src ='';
		if (strtolower($fileext) == 'png') {
			$src = imagecreatefrompng($imageFile);
		}
		else if(strtolower($fileext) == 'gif'){
			$src = imagecreatefromgif($imageFile);
		}
		else if(strtolower($fileext) == 'jpg'){
			$src = imagecreatefromjpeg($imageFile);
		}
		else{
			echo "File type not supported, .gif, .jpg or .png required!";
		}			
		$orig_h = ($height/$width)* $orig_w;
		$tmp = imagecreatetruecolor($orig_w, $orig_h);
		imagecopyresampled($tmp, $src, 0,0,0,0,$orig_w,$orig_h,$width,$height);	
		if (strtolower($fileext) == 'png') {
			imagepng($tmp, $folder.$filename,100);
		}
		else if(strtolower($fileext) == 'gif'){
			imagegif($tmp, $folder.$filename,100);
		}
		else if(strtolower($fileext) == 'jpg'){
			imagejpeg($tmp, $folder.$filename,100);
		}
		else{
			echo "File type not supported, .gif, .jpg or .png required!";
		}
		
		imagedestroy($tmp);
		imagedestroy($src);
		$filename = urlencode($filename);
		header("Location: crop.php?filename=$filename&height=$orig_h");
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
		<title>Opus1 Image Upload</title>
		<link type="text/css" href="../jqueryui/css/ui.all.css" rel="stylesheet" />
		<script type="text/javascript" src="../js/jquery-1.3.2.js"></script>
		<script type="text/javascript" src="../jqueryui/ui/ui.core.js"></script>
		<script type="text/javascript" src="../jqueryui/ui/ui.resizable.js"></script>
		<script type="text/javascript" src="../jqueryui/ui/ui.dialog.js"></script>            
		<script type="text/javascript" src="../jqueryui/ui/effects.core.js"></script>
		<script type="text/javascript" src="../js/jquery.opacityrollover.js"></script>			
		<link type="text/css" href="../jqueryui/css/demos.css" rel="stylesheet" />
		<link type="text/css" href="../jqueryui/css/ui.theme.css" rel="stylesheet" />
		<link rel="stylesheet" href="../css/basic.css" type="text/css" />
		<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
		<script type="text/javascript">
		$(document).ready(function() {
			$("#submit").click(function() {
				alert('Handler for .submit() called.');
				$('#addAlbumDialog').dialog('open');							
			});
			$("#addAlbumDialog").dialog({
                  bgiframe: true,
                  autoOpen: false,
                  height: 400,
                  width: 400,
                  modal: true,
                  buttons: {
                        'Save': function() {
							var caption=$("#captionAlbum");
							var albumCoverImage=$("#albumCoverImage"); 
							var albumCover=$("#albumCover"); 
							//alert(albumCover.val());
							//$.post("../addAlbumdb.php", {caption:caption.val(),albumCoverImage:albumCoverImage.val()});
							$(this).dialog('close');
							alert("about to post");
							$("#uploadFrm").submit();	
                        },
                        Cancel: function() {
                              $(this).dialog('close');
                        }
                  },
                  close: function() {
                        //allFields.val('').removeClass('ui-state-error');
					  }
				});
			});
			function createNewAlbum(albumSelected)
			{
				if(albumSelected == 1){
					$('#addAlbumDialog').dialog('open');
				}	
			}
		</script>
    </head>
    <body>
		<h1>Opus1 Gallery - Image Upload</h1>
		<form id="uploadFrm" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
			<p>
				<input type="file" name="image" id="image" size="50"/>
				<button type="button" id="submit">Upload</button>
			</p>			
		</form>	
		<div id="addAlbumDialog" title="Add Album" style="display:none">			
				<fieldset>
				<label for="selectAlbum">Upload to Album:</label>
				<SELECT name="selectAlbum" id="selectAlbum" onchange="createNewAlbum(this.value);"> 
					<OPTION VALUE=1>Create New Album</option>
					<option disabled="disabled">-------------------------------</option>
					<?=$options?> 
				</SELECT> 
				<br />
				<label for="captionAlbum">Caption:</label>
				<input id="captionAlbum" type="text" name="captionAlbum"/> 
				<br />
				<label for="albumCover">Album Cover:</label>
				<input TYPE="checkbox" name="albumCover" id="albumCover">
				<input id="albumCoverImage" type="hidden" name="albumCoverImage" value="default"/> 
				</fieldset>       
		</div>		
    </body>
</html>

Open in new window




0
cgray1223
Asked:
cgray1223
  • 4
  • 3
1 Solution
 
cgray1223Author Commented:
Main lines of code of interest here are:

line 6 - runs the post logic and then redirects, not getting executing when using jquery submit()
line 66 - .click event attached to html button with id of "submit"
line 85 - jquery.submit() called for form id of "uploadFrm"
line 106 thru 111 - form that I'm trying to submit


0
 
shaziashaikhCommented:
Do not give 'submit' id to any other HTML element as it's a default used for form submit.

just change the button id name as below:
<button type="button" id="showDialog">Upload</button>

Also change the name in the jquery's click function as below:
$("#showDialog").click(function() {
    //alert('Handler for .submit() called.');
   $('#addAlbumDialog').dialog('open');                              
});
0
 
hexer4uCommented:
Change
<button type="button" id="submit">Upload</button>
to
<input type="submit" name="submit" value="Upload" />

Just clicking on it will submit the form.
If you want to submit the form by clicking something else, add this to it's onclick event:
$('#uploadFrm').submit();

A form with only 1 element will not be submitted unless you have a submit button, so you have to replace your button with <input type="submit" name="submit" value="Upload" />

Also to optimize, you should do something like

function afterOKsubmit(){
            global $tmp;
            global $src;
            global $filename;
            global $orig_h;
            imagedestroy($tmp);
            imagedestroy($src);
            $filename = urlencode($filename);
            header("Location: crop.php?filename=$filename&height=$orig_h");

}

and do afterOKsubmit(); at lines 30, 33 and 36, not after all ot if-else statements (the last else would display, but the page would be redirected)
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
cgray1223Author Commented:
Thanks for the responses!

hexer4u, I don't want the  <input type="submit" name="submit" value="Upload" /> to be the button that actually submits the form.  I just want it to call my jquery function and open my dialog where I can gather more form inputs and then have the save button on my dialog actually call the $('#uploadFrm').submit();  

I've modified my code so that the upload button opens the dialog and the save button does have the $('#uploadFrm').submit(); snippet but it doesn't submit.  I think you're saying the form must have a submit button, correct?  If so, can I not accomplish submitting from the dialog which is outside the form?  
0
 
hexer4uCommented:
You can submit the form via 2 methods:
1. use a submit button INSIDE the <form> tags
2. use a javascript .submit() wherever.

I'm saying that in order to work in ALL browsers, you'll have to include an HTML submit button INSIDE the <form> tags, even if you submit it with JS. You can set it's style to style="display: none" to hide it, but it has to be there. You can use a <input type="button" ..../> if you want a button that does not submit the form.
Carefull, as the <button> tag is generally interpreted as a type="submit" button (see IE)

What you want to do is OK, as long as you store the collected data inside iputs/select/textarea INSIDE the <form> tags you are submitting.

This is because when you submit a form, only the content between the <form> tags of the one you submit will actually reach the next page
0
 
cgray1223Author Commented:
Ok, I think I understand what you're saying but I can't get the form to submit.  I added a input button in the form that I attach the jquery .click function to and also kept the input submit button (hidden) in there as well.  Below is my code, can you see anything?


<?php
      $folder = 'images/';
      $orig_w = 500;
      $caption = $_POST[caption];
      $albumCoverImage = $_POST[albumCoverImage];
      $con = mysql_connect('localhost', 'musicopus1', 'octopus1');
      if (!$con){
        die('Could not connect: ' . mysql_error());
      }
      mysql_select_db("musicopus1_com_-_musicopus2009", $con);
      $sql="SELECT * FROM ALBUM_NEW";
      $result=mysql_query($sql);
      $options="";
      while ($row=mysql_fetch_array($result)) {
            $id=$row["ID"];
            $title=$row["TITLE"];
            $options.="<OPTION VALUE=\"$id\">".$title;
      }       
      mysql_close($con);
      if( isset($_POST['submit']) )
      {
            $imageFile = $_FILES['image']['tmp_name'];
            $filename = basename( $_FILES['image']['name']);
            $info = pathinfo($folder.$filename);
            $fileext = $info['extension'];
            list($width, $height) = getimagesize($imageFile);            
            $src ='';
            if (strtolower($fileext) == 'png') {
                  $src = imagecreatefrompng($imageFile);
            }
            else if(strtolower($fileext) == 'gif'){
                  $src = imagecreatefromgif($imageFile);
            }
            else if(strtolower($fileext) == 'jpg'){
                  $src = imagecreatefromjpeg($imageFile);
            }
            else{
                  echo "File type not supported, .gif, .jpg or .png required!";
            }                  
            $orig_h = ($height/$width)* $orig_w;
            $tmp = imagecreatetruecolor($orig_w, $orig_h);
            imagecopyresampled($tmp, $src, 0,0,0,0,$orig_w,$orig_h,$width,$height);      
            if (strtolower($fileext) == 'png') {
                  imagepng($tmp, $folder.$filename,100);
            }
            else if(strtolower($fileext) == 'gif'){
                  imagegif($tmp, $folder.$filename,100);
            }
            else if(strtolower($fileext) == 'jpg'){
                  imagejpeg($tmp, $folder.$filename,100);
            }
            else{
                  echo "File type not supported, .gif, .jpg or .png required!";
            }
            imagedestroy($tmp);
            imagedestroy($src);
            $filename = urlencode($filename);
            header("Location: crop.php?filename=$filename&height=$orig_h");
      }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
            <title>Opus1 Image Upload</title>
            <link type="text/css" href="../jqueryui/css/ui.all.css" rel="stylesheet" />
            <script type="text/javascript" src="../js/jquery-1.3.2.js"></script>
            <script type="text/javascript" src="../jqueryui/ui/ui.core.js"></script>
            <script type="text/javascript" src="../jqueryui/ui/ui.resizable.js"></script>
            <script type="text/javascript" src="../jqueryui/ui/ui.dialog.js"></script>            
            <script type="text/javascript" src="../jqueryui/ui/effects.core.js"></script>
            <script type="text/javascript" src="../js/jquery.opacityrollover.js"></script>                  
            <link type="text/css" href="../jqueryui/css/demos.css" rel="stylesheet" />
            <link type="text/css" href="../jqueryui/css/ui.theme.css" rel="stylesheet" />
            <link rel="stylesheet" href="../css/basic.css" type="text/css" />
            <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
            <script type="text/javascript">
            $(document).ready(function() {
                  $("#upload").click(function() {
                        alert('Handler for .submit() called.');
                        $('#addAlbumDialog').dialog('open');                                          
                  });
                  $("#addAlbumDialog").dialog({
                  bgiframe: true,
                  autoOpen: false,
                  height: 400,
                  width: 400,
                  modal: true,
                  buttons: {
                        'Save': function() {
                                          var caption=$("#captionAlbum");
                                          var albumCoverImage=$("#albumCoverImage");
                                          var albumCover=$("#albumCover");
                                          //alert(albumCover.val());
                                          //$.post("../addAlbumdb.php", {caption:caption.val(),albumCoverImage:albumCoverImage.val()});
                                          $(this).dialog('close');
                                          alert("about to post");
                                          $("#uploadFrm").submit();      
                        },
                        Cancel: function() {
                              $(this).dialog('close');
                        }
                  },
                  close: function() {
                        //allFields.val('').removeClass('ui-state-error');
                                }
                        });
                  });
                  function createNewAlbum(albumSelected)
                  {
                        if(albumSelected == 1){
                              $('#addAlbumDialog').dialog('open');
                        }      
                  }
            </script>
    </head>
    <body>
            <h1>Opus1 Gallery - Image Upload</h1>
            <form id="uploadFrm" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
                  <p>
                        <input type="file" name="image" id="image" size="50"/>
                        <input type="button" id="upload" value="Upload!"/>
                        <input type="submit" name="submit" value="Upload" id="submit" style="display: none"/>
                  </p>                  
            </form>      
            <div id="addAlbumDialog" title="Add Album" style="display:none">                  
                        <fieldset>
                        <label for="selectAlbum">Upload to Album:</label>
                        <SELECT name="selectAlbum" id="selectAlbum" onchange="createNewAlbum(this.value);">
                              <OPTION VALUE=1>Create New Album</option>
                              <option disabled="disabled">-------------------------------</option>
                              <?=$options?>
                        </SELECT>
                        <br />
                        <label for="captionAlbum">Caption:</label>
                        <input id="captionAlbum" type="text" name="captionAlbum"/>
                        <br />
                        <label for="albumCover">Album Cover:</label>
                        <input TYPE="checkbox" name="albumCover" id="albumCover">
                        <input id="albumCoverImage" type="hidden" name="albumCoverImage" value="default"/>
                        </fieldset>      
            </div>            
    </body>
</html>
0
 
hexer4uCommented:
Move the div addAlbumDialog inside the <form> tags.
Data collected by dialog would not be posted otherwise
0
 
hexer4uCommented:
remove the lines
$con = mysql_connect('localhost', 'musicopus1', 'octopus1');
and
mysql_select_db("musicopus1_com_-_musicopus2009", $con);
from cgray1223's post and the question would have no reason to be deleted.
that information (to be removed) will not influence the question or solution to this issue
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now