Solved

auto submit a form using jquery and php issue

Posted on 2010-08-23
8
886 Views
Last Modified: 2012-05-10
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
Comment
Question by:cgray1223
  • 4
  • 3
8 Comments
 

Author Comment

by:cgray1223
ID: 33498909
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
 
LVL 1

Expert Comment

by:shaziashaikh
ID: 33499109
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
 
LVL 6

Expert Comment

by:hexer4u
ID: 33499368
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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:cgray1223
ID: 33502569
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
 
LVL 6

Expert Comment

by:hexer4u
ID: 33504580
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
 

Author Comment

by:cgray1223
ID: 33507215
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
 
LVL 6

Accepted Solution

by:
hexer4u earned 500 total points
ID: 33508505
Move the div addAlbumDialog inside the <form> tags.
Data collected by dialog would not be posted otherwise
0
 
LVL 6

Expert Comment

by:hexer4u
ID: 33508514
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question