Getting value of javascript variable into a database

This is a combination jquery / php question, so I’m not sure I’ve posted in the correct forum.

In a project I am working on, the user uploads an image. A rectangular template image is placed over top of the uploaded image which the user can resize and drag.

I am using the following jquery code to drag and resize the template, then record the position of the top left corner of the template, and the width of the template.


 jQuery(document).ready(function() {
	
	jQuery("#template")
		.draggable({
			drag: function(event, ui) {
				var horizontalPosition = console.log(ui.position.left);
				var verticalPosition = console.log(ui.position.top);
			}
		})
		.resizable({
			handles: 's,n,e,w',
			aspectRatio: 433 / 500,
			stop: function(event, ui) {
				var width = console.log(Math.round(ui.size.width).toFixed(0));
				var height = console.log(Math.round(ui.size.height).toFixed(0));
			}
		});
    [I]...juery code continued below...[/I]

I am able to see the width and position results in the console, so this part is working.
But then I would like to take these values and store them in a database. So I have the following form -


<form action="process.php" method="post" name="image_results" />
	<div>
		<input type="hidden" name="template_width" id="template_width" value="" />
		<input type="hidden" name="template_xpos" id="template_xpos" value="" />
		<input type="hidden" name="template_ypos" id="template_ypos" value="" />
		<input type="submit" name="submit" id="save_image" value="Save Image" />
	</div>
</form>	

and added the following code to the end of my jquery to enter the values into the hidden input boxes.


	$('input#template_width').attr('value', width);
	$('input#template_xpos').attr('value', horizontalPosition);
	$('input#template__ypos').attr('value', verticalPosition);
});	

Then in my process.php I processed the $_POST values in preparation to storing them in the database, but when I tried echoing them, they were empty.
In my jquery, I tried removing the console.log() first but that didn’t help.


if (isset( $_POST['submit'] ) && $_POST['submit'] == 'Save Image') {
		
	if (isset($_POST['template_width'])) {
		$template_width = $_POST['template_width'];
	} else {
		$template_width = '';
	}	
	if (isset($_POST['template_xpos'])) {
		$template_xpos = $_POST['template_xpos'];
	} else {
		$template_xpos = '';
	}	
	if (isset($_POST['template_ypos'])) {
		$template_ypos = $_POST['template_ypos'];
	} else {
		$template_ypos = '';
	}	

	echo "Template Width: " . $template_width . " :: Template x position: " . $template_xpos  . " :: Template y position: " .  $template_ypos;
	

Am I taking the wrong approach? or is there some glaring error in my code that I can’t see?

Hi,

The values of hidden inputs need to be updated whenever the user has resized the template.
Can you use your browser tools (right click > inspect element) to see if this is the case.
Could you also post a link to a page where we can see this in action?

My page is local right now, but I will try to upload a demo of what I am trying to do later today.

In the meantime, after the user has finished dragging and resizing, he hit this “Save Image” button and I want the latest width, x position and y position to be saved in the hidden fields. After that there will be no more changes to the template - so no more updating of the values.

Ah ok, then couldn’t you attach a submit handler to the form, e.g.

$("#myForm").on("submit", function(e){
  //set the values here.
});

If this doesn’t work, you might have to prevent the form’s default action, attach the values, then submit it programmatically.

For me, this worked:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style></style>
  </head>
  <body>
    <form action="process.php" method="post" name="image_results" />
      <div>
        <input type="hidden" name="template_width" id="template_width" value="" />
        <input type="hidden" name="template_xpos" id="template_xpos" value="" />
        <input type="hidden" name="template_ypos" id="template_ypos" value="" />
        <input type="submit" name="submit" id="save_image" value="Save Image" />
      </div>
    </form>

    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script>
      $("form").on("submit", function(){
        var width = 250, 
            horizontalPosition = 100,
            verticalPosition = 500;
        $('input#template_width').attr('value', width);
        $('input#template_xpos').attr('value', horizontalPosition);
        $('input#template_ypos').attr('value', verticalPosition);
      });
    </script>
  </body>
</html>

process.php:

<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";

You also had a small typo.

This:

$('input#template__ypos').attr('value', verticalPosition);

should be:

$('input#template_ypos').attr('value', verticalPosition);

Sorry I took so long to respond. Other work got in the way for a few days, but I’m back at this one now and I’ll try your suggestion.

In the meantime, you mentioned a typo, but I can’t see the difference between the one line and your suggested correction.

You also had a small typo.

This:

Code:

$('input#template__ypos').attr('value', verticalPosition);

should be:

Code:

$('input#template_ypos').attr('value', verticalPosition);

Okay, I see the typo - a double underscore instead of a single underscore (really hard to pick out)

I still can’t get the jquery to populate the hidden form fields. Could it be a scope issue because my variables are set in other functions? I haven’t done much javascript in a number of years.

Here is my new javascript code:


jQuery(document).ready(function() {
	
	jQuery("#pocket_template")
		.draggable({
			drag: function(event, ui) {
				var horizontalPosition = parseInt(ui.position.left);
				var verticalPosition = parseInt(ui.position.top);	
			}
		})
		.resizable({
			handles: 's,n,e,w',
			aspectRatio: 433 / 500,
			stop: function(event, ui) {
				var width = parseInt(Math.round(ui.size.width).toFixed(0));
				var height = parseInt(Math.round(ui.size.height).toFixed(0));
			}
		});
	
	$("form").on("submit", function() {
		$('input#template_width').attr('value', width);
		$('input#template_xpos').attr('value', horizontalPosition);
		$('input#template_ypos').attr('value', verticalPosition);
	});
});	

Sorry to keep answering my own posts, but it was a scope issue. Once I removed the ‘var’ from the variables that I declared, I was able to pass the values of the variables to the hidden fields, and then into my database.

This is great! I am learning a lot from this client project.

Hmm, removing var places them in global scope.
I don’t think this is the best idea.
Ideally there will be something like an onDragStop event to hook into, from which you could update the hidden fields.
This is much safer, especially when your variables have generic names such as width and height.

This is an extra application that I am tacking on to a custom WordPress theme that uses WooCommerce. Is there a security issue between my javascript file and the rest of the website? I am not that well versed with current javascript practices. Will global scope also affect the other javascript that plugins may be using?

What if I just change the variable names by prefixing them with something?

However, I’ll look into the possibility of a built-in event like you suggested.

No. Not because of this.

This is why globals are frowned on.

If you are using jQuery UI draggable, there is a dragstop event available:

$( ".selector" ).on( "dragstop", function( event, ui ) {} );

http://api.jqueryui.com/draggable/#event-stop

Let us know how you get on :slight_smile:

I am using jQuery UI draggable and resizable, the dragging and resizing can be performed in any order by the user. So when the user clicks the “Save” button his last action might have been the resizing. It is the final position and width that I want to record. Can I still use the dragstop event if the resizing is done last?

Can you post (or PM me) a link to a page where I can see this?

It’s on my local development version of a client’s WordPress site. The site is live, but this is an additional feature that I am working on for him. I will upload the site to the back of my own site and PM you. Thank you.

I’ve been trying to upload my test site and get the page in question working so you can take a look, but I’m having to deal with a lot of issues with file permissions and the uploading of images, etc that weren’t a problem on my local development site. It may be a few more days before I can get something there, because I’m not that experienced with this level of php, and I have to keep up with the rest of my work too.

No problem :slight_smile:

Having a couple of global variables in your script isn’t the worst thing in the world, so if this is creating disproportionate amounts of work for you, I’m not sure it’s worth the effort.