How can I get some values created in JavaScript into php, use AJAX?

I have found some Jquery code to outline an object and I need to get the values created into my php code.

I have read some posts about using Ajax and Json to communicate directly with php but I have no idea how to implement this into the JavaScript code.

Please can somebody point me in the right direction.

The way I’ve done it is

  • page has a form that uses the inputs for AJAX with args that goes to a PHP file
  • the PHP file takes the args to make a db query and returns the JSON
  • the AJAX callback function modifies the DOM using the JSON

Something like that what you had in mind?

Yes when the user is happy with the points as they can change them at any time they will press a button and the current array of points will be sent to php. I have not thought the next step though fully and was thinking more of saving them into a text file.
At some stage the points need to be read into a shell script and somebody else is developing that and asked for a text file. I suppose when everything is written and working it will all be in one piece of code: upload form > point picker > php > shellscript. I was using the php code to tie the javascript and shellscript together.

You could save the data in other ways to, text, CSV, XML - I tend to usually use a database so that’s what I used.

Cartesian or Radian you’ll always have 2 and only two points?

i.e.

point 1 - X axis
point 1 - Y axis
point 2 - X axis
point 2 - Y axis

or

point 1 - degrees
point 1 - distance
point 2 - degrees
point 2 - distance

I am looking for pairs of numbers in an x,y x,y format. The demo code I have found outputs the points in the format x,y,x,y
I think I found the function that creates the numbers and can make it display the numbers on the screen but there is always a , between the pairs and I can not find where that is being inserted.


    record = function() {
      $(input).val(points.join(','));
	  // Displays the coordinates on the page - lines up with <p id="demo"></p> on index page
		points.toString();
		document.getElementById("demo").innerHTML = points;
    };

For testing a text file output would be useful and may be what the other developer wants but in the long run a database may be better. I can link the original image to the points and do whatever I want with the data once I have it in the database.

Hi Rubble,

So assuming you have your points in a text area, something like this:

<textarea id="points">
  208,221,208,202,198,199,201,191,218,176,229,155,221,132,196,117,169,131,157,158,163,172,177,164,173,180,190,185,192,199,187,201,185,222
</textarea>

Then what you need is a button on the page, which when clicked fires an AJAX request to your PHP script.
For AJAX stuff I always use jQuery, as the syntax is concise and it does a lot of the heavy lifting for you.

Our button, with an on click event handler:

<button id="createFile">Create text file</button>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$("#createFile").on("click", function(){
  // Code here will be executed when button clicked
});
</script>

Now when clicked we need to grab the contents of the text area and submit this to the PHP script:

$("#createFile").on("click", function(){
  $.ajax({
    type: "POST",
    url: "points.php",
    data: {"points": $("#points").text()},
    success: function(response){
      console.log(response);
    }
  });
});

The success callback will log the server’s response to the console and although not strictly necessary, will give us an indication at o whether this has worked.

This gives us:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <style>
    </style>
  </head>
  <body>
    <textarea id="points">
      208,221,208,202,198,199,201,191,218,176,229,155,221,132,196,117,169,131,157,158,163,172,177,164,173,180,190,185,192,199,187,201,185,222
    </textarea>
    <button id="createFile">Create text file</button>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
      $("#createFile").on("click", function(){
        $.ajax({
          type: "POST",
          url: "points.php",
          data: {"points": $("#points").text()},
          success: function(response){
            console.log(response);
          }
        });
      });
    </script>
  </body>
</html>

points.php

<?php 

$points = $_POST["points"];
print_r($points);

In your example, you will then be able to extract the user generated coordinates from $_POST["points"] and create your text file.

If you have any questions, just let us know.

Thanks for the code and the explanation but nothing happens when I run it and I do not get a server response.

No probs :slight_smile:

Are you seeing anything in the console?

I forgot about the console as I have never used it!

In Firefox I get this:

SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead jquery.min.js:1
Error: http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js is being assigned a //# sourceMappingURL, but already has one
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. jquery.min.js:3
" 208,221,208,202,198,199,201,191,218,176,229,155,221,132,196,117,169,131,157,158,163,172,177,164,173,180,190,185,192,199,187,201,185,222
"

The first two lines are there from the start and the third shows up when the button is pressed. Does this indicate the points are being sent but not received?

That’s cool, then everything is working as expected (regarding the AJAX at least).

This:

208,221,208,202,198,199,201,191,218,176,229,155,221,132,196,117,169,131,157,158,163,172,177,164,173,180,190,185,192,199,187,201,185,222

is the value that the script submitted to points.php.

You can access it from within the PHP script as $_POST[“points”]

In my example I am just extracting whatever value $_POST[“points”] contains and echoing it back to the JavaScript.

In your example you will want to use this value to create the text file, then echo back some indication of whether the operation succeeded or not.

HTH

Now this is interesting as I do not think points are an array but a string?

So I have changed points.php to:

$points = $_POST["points"];
echo 'Points are: '.$_POST['points'];

The console now displays:

SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead jquery.min.js:1
Error: http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js is being assigned a //# sourceMappingURL, but already has one
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. jquery.min.js:3
"Points are: 208,221,208,202,198,199,201,191,218,176,229,155,221,132,196,117,169,131,157,158,163,172,177,164,173,180,190,185,192,199,187,201,185,222
" test.php:22

Notice the Points are: at the start of the line.

EDIT: I was expecting points.php to open and display the points.

Nice one :slight_smile:

Now you should have access to the data in your PHP script as desired, right?

Yes I have just written the points to a text file. I will have a go at including it into the demo file later as I have to TRY and find my camera charger :frowning:

Cool :slight_smile:
Let us know if you get stuck.

Not exactly what you’re after, but I’ve been playing a bit instead of doing the yard work I should be doing :shifty:

I haven’t got to the JSON part, but this is what I banged together so far

<!DOCTYPE HTML>
<html>
<head>
<title>graph point example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- wherever you want to pull jQuery in from -->
<script type="text/javascript" src="../includes/jquery-2.1.1.min.js"></script>
<style type="text/css">
body {
  background-color: #BADBEE;
 }
form {
  width: 25%;
  padding: 15px;
  background-color: #DEDEDE;
 }
#get_json {
  float: right;
 }
#error_meesage {
  color: #F00;
  font-weight: bold;
 }
canvas {
  border: 1px solid #000;
  margin-top: 15px;
  background-color: #FFF;
}
</style>
</head>
<body>
<h1>graph point example</h1>
<p>Just to give you a rough idea.<br />
Uses canvas instead of SVG<br />
*This version of jQuery does not support IE 6, 7, or 8</p>
<form id="input_form" method="post" action="get-points.php">
<fieldset>
<legend>inputs for graph point example</legend>
<label for="x_axis_p_1" />X axis point 1</label>
<input type="text" id="x_axis_p_1" name="x_axis_p_1" value="" /> <br />
<label for="y_axis_p_1" />Y axis point 1</label>
<input type="text" id="y_axis_p_1" name="y_axis_p_1" value="" /> <br />
<label for="x_axis_p_2" />X axis point 2</label>
<input type="text" id="x_axis_p_2" name="x_axis_p_2" value="" /> <br />
<label for="y_axis_p_2" />Y axis point 2</label>
<input type="text" id="y_axis_p_2" name="y_axis_p_2" value="" /> <br />
<input type="button" id="use_inputs" name="use_inputs" value="use input values" />
<input type="submit" id="get_json" name="get_json" value="get JSON values" />
</fieldset>
</form>
<p id="error_meesage"></p>
<canvas id="point_canvas"" width="200" height="200"></canvas>
<script type="text/javascript">
$('document').ready(function() {
  assignListeners();
});
function assignListeners() {
  $('#x_axis_p_1').change(function() {
	if ($(this).val() !== NaN) {
	  x_axis_p_1_value = $(this).val();
	}
});
  $('#y_axis_p_1').change(function() {
	if ($(this).val() !== NaN) {
      y_axis_p_1_value = $(this).val();
	}
});
  $('#x_axis_p_2').change(function() {
	if ($(this).val() !== NaN) {
      x_axis_p_2_value = $(this).val();
	}
});
  $('#y_axis_p_2').change(function() {
	if ($(this).val() !== NaN) {
      y_axis_p_2_value = $(this).val();
	}
});
  $('#use_inputs').click(function(e) {
  var err_msg = document.getElementById('error_meesage');
  if ( (typeof x_axis_p_1_value === 'undefined') || (x_axis_p_1_value == '')
	|| (typeof y_axis_p_1_value === 'undefined') || (y_axis_p_1_value == '')
	|| (typeof x_axis_p_2_value === 'undefined') || (x_axis_p_2_value == '')
	|| (typeof y_axis_p_2_value === 'undefined') || (y_axis_p_2_value == '') ) {
	  err_msg.textContent = "All inputs must contain Integers";
	  clearCanvas();
	}
	else {
	  err_msg.textContent = "";
	  draw(x_axis_p_1_value, y_axis_p_1_value, x_axis_p_2_value , y_axis_p_2_value);
	}
	e.preventDefault();
	e.stopPropagation();
});
  $('#get_json').click(function() {
//    getJSON;
});
}
function clearCanvas() {
  var canvas = document.getElementById('point_canvas');
  var context = canvas.getContext('2d');
  context.clearRect(0, 0, canvas.width, canvas.height);
}
function draw(x_axis_p_1_value, y_axis_p_1_value, x_axis_p_2_value , y_axis_p_2_value) {
  var canvas = document.getElementById('point_canvas');
  var context = canvas.getContext('2d');
  
  context.beginPath();
  context.moveTo(x_axis_p_1_value, y_axis_p_1_value);
  context.lineTo(x_axis_p_2_value, y_axis_p_2_value);
  context.lineWidth = 5;
  context.strokeStyle = "#F00";
  context.stroke();
}
</script>
</body>
</html>

I actually managed to get some yard work, house work, and paper work done today!

  • with coding in between :wink:

It’s not perfect*, I’ll leave the tweaking and enhancement to you. But if you have questions, do ask. Hopefully between this, Pullo’s and your code you’re well on your way.
*most notably graph-points.php could use a mess of PHP code to have it work when JavaScript is disabled and you may have noticed I’m not a Designer.

I put all 4 files in the same folder.

point-values.txt

10, 100, 190, 180
64, 180, 19, 105
70, 53, 110, 48
100, 10, 180, 190
5, 164, 199, 65
24, 180, 176, 14
125, 100, 159, 29
2, 2, 99, 99
20, 30, 160, 170
100, 198, 100, 2

set-points.php

<?php
header('Content-type: application/json');
$new_points = array($_GET[0], $_GET[1], $_GET[2], $_GET[3] );
$encoded_points = json_encode($new_points, JSON_NUMERIC_CHECK);
echo $encoded_points;
$new_points_str = implode(", ", $new_points);
file_put_contents('point-values.txt',  "\\r\
" . $new_points_str, FILE_APPEND );
?>

get-points.php

<?php
header('Content-type: application/json');
$graph_points = array();
// use path to the text file
$lines = file('point-values.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
foreach ($lines as $line_num => $line) {
    $graph_points[] = explode(", ", $line);
}
$graph_points_size = count($graph_points);
$key = rand(0, $graph_points_size - 1);
$encoded_points = json_encode($graph_points[$key], JSON_NUMERIC_CHECK);
echo $encoded_points;
?>

graph-points.php

<!DOCTYPE HTML>
<html>
<head>
<title>graph point example</title>
<meta charset="UTF-8">
<!-- wherever you want to pull jQuery in from -->
<script type="text/javascript" src="../includes/jquery-2.1.1.min.js"></script>
<style type="text/css">
body {
  background-color: #BADBEE;
 }
form {
  width: 25%;
  padding: 15px;
  background-color: #DEDEDE;
 }
#get_json {
  float: right;
 }
#error_message {
  color: #F00;
  font-weight: bold;
 }
canvas {
  border: 1px solid #000;
  margin: 15px 0;
  background-color: #FFF;
}
#success_message {
  width: 25%;
  background-color: #FFF;
  color: #0F0;
  font-weight: bold;
 }
#new_points_form {
  display: none;
 }
</style>
</head>
<body>
<h1>graph point example</h1>
<p>Just to give you a rough idea.<br />
Uses canvas instead of SVG<br />
*This version of jQuery does not support IE 6, 7, or 8</p>
<!-- set action to the PHP file -->
<form id="input_form" method="post" action="get-points.php">
	<fieldset>
		<legend>inputs for graph point example</legend>
		<label for="x_axis_p_1" />X axis point 1</label>
		<input type="text" id="x_axis_p_1" name="x_axis_p_1" value="" /> <br />
		<label for="y_axis_p_1" />Y axis point 1</label>
		<input type="text" id="y_axis_p_1" name="y_axis_p_1" value="" /> <br />
		<label for="x_axis_p_2" />X axis point 2</label>
		<input type="text" id="x_axis_p_2" name="x_axis_p_2" value="" /> <br />
		<label for="y_axis_p_2" />Y axis point 2</label>
		<input type="text" id="y_axis_p_2" name="y_axis_p_2" value="" /> <br />
		<input type="submit" id="use_inputs" name="use_inputs" value="use input values" />
		<input type="submit" id="get_json" name="get_json" value="get random values" />
	</fieldset>
</form>
<p id="error_message"></p>
<canvas id="point_canvas"" width="200" height="200"></canvas>
<p id="success_message"></p>
<!-- set action to the PHP file -->
<form id="new_points_form" method="post" action="get-points.php">
	<fieldset>
		<legend>Save these points?</legend>
		<input type="submit" id="save_new_points" name="save_new_points" value="Yes, save them" />
	</fieldset>
</form>
<script type="text/javascript">
$('document').ready(function() {
  assignListeners();
});
function assignListeners() {
  $('#x_axis_p_1').change(function() {
	if ($(this).val() !== NaN) {
	  x_axis_p_1_value = $(this).val();
	}
});
  $('#y_axis_p_1').change(function() {
	if ($(this).val() !== NaN) {
      y_axis_p_1_value = $(this).val();
	}
});
  $('#x_axis_p_2').change(function() {
	if ($(this).val() !== NaN) {
      x_axis_p_2_value = $(this).val();
	}
});
  $('#y_axis_p_2').change(function() {
	if ($(this).val() !== NaN) {
      y_axis_p_2_value = $(this).val();
	}
});
  $('#use_inputs').click(function(e) {
  var err_msg = document.getElementById('error_message');
  $save_new_points = document.getElementById('new_points_form');
  if ( (typeof x_axis_p_1_value === 'undefined') || (x_axis_p_1_value == '')
	|| (typeof y_axis_p_1_value === 'undefined') || (y_axis_p_1_value == '')
	|| (typeof x_axis_p_2_value === 'undefined') || (x_axis_p_2_value == '')
	|| (typeof y_axis_p_2_value === 'undefined') || (y_axis_p_2_value == '') ) {
	  err_msg.textContent = "All inputs must contain Integers";
	  $save_new_points.style.display = "none";
	  clearCanvas();
	}
	else {
	  err_msg.textContent = "";
	  $save_new_points.style.display = "block";
	  clearCanvas();
	  draw(x_axis_p_1_value, y_axis_p_1_value, x_axis_p_2_value , y_axis_p_2_value);
	}
	e.preventDefault();
	e.stopPropagation();
});
  $('#get_json').click(function(e) {
    $save_new_points = document.getElementById('new_points_form');
	$save_new_points.style.display = "none";
    getJsonPoints();
	e.preventDefault();
	e.stopPropagation();
});
  $('#save_new_points').click(function(e) {
    setNewPoints();
	e.preventDefault();
	e.stopPropagation();
});
}
function getJsonPoints() {
  var err_msg = document.getElementById('error_message');
  var suc_msg = document.getElementById('success_message');
  suc_msg.textContent = "";
// use path to the PHP file
  var jqXHR = $.getJSON('get-points.php',
    function(result) {
	  var data_points = [];
	  for (var prop in result) {
	    data_points.push(result[prop]);
	  }
	  err_msg.textContent = "";
	  clearCanvas();
	  draw(data_points[0], data_points[1], data_points[2], data_points[3]);
	})
	.fail(function(jqXHR, textStatus, errorThrown) {
	  err_msg.textContent = "error " + textStatus + " error text " + errorThrown;
	  clearCanvas();
	 });
}
function setNewPoints() {
  var err_msg = document.getElementById('error_message');
  var suc_msg = document.getElementById('success_message');
  suc_msg.textContent = "";
// use path to the PHP file
   $.post('set-points.php?0=' + x_axis_p_1_value + '&1=' + y_axis_p_1_value + '&2=' + x_axis_p_2_value + '&3=' + y_axis_p_2_value,
	{dataType: 'json'},
   function(result) {
	  var data_points = [];
	  $.each(result, function(key, value) {
	    data_points.push(value);
	  });
	  err_msg.textContent = "";
      suc_msg.textContent = "New points have been Saved";
	  clearCanvas();
	  draw(data_points[0], data_points[1], data_points[2], data_points[3]);
	});
}
function clearCanvas() {
  var canvas = document.getElementById('point_canvas');
  var context = canvas.getContext('2d');
  context.clearRect(0, 0, canvas.width, canvas.height);
}
function draw(x_axis_p_1_value, y_axis_p_1_value, x_axis_p_2_value , y_axis_p_2_value) {
  var canvas = document.getElementById('point_canvas');
  var context = canvas.getContext('2d');

  context.beginPath();
  context.moveTo(x_axis_p_1_value, y_axis_p_1_value);
  context.lineTo(x_axis_p_2_value, y_axis_p_2_value);
  context.lineWidth = 5;
  context.strokeStyle = "#F00";
  context.stroke();
}
</script>
</body>
</html>

Thanks for the code @Mittineague I think I will stick with @Pullo’s code at the moment as I have it working and I do not want to confuse myself to much.

This brings me onto another question. In the original demo I linked to there are two images and you can create points for both and I would like to do that.
I tried different things last night without success by having the two text areas with different names and tried different variations of data: settings e.g.


data: {"points": $("#points1"), $("#points2").text()},
data: {"points": $("#points1")+ $("#points2").text()},

But this did not work - form memory I usually had nothing but also had ( I forget now but it was something like ) [original, Original] or in one case I just had a,

The reason for this is we can have two images the same ( with perspective errors for instance ) except the right hand image will have a grid overlaid.
The user clicks the point on the LH image and the new point on the RH image ( could be the same point ) then clicks the next point on the LH image and the new point on the RH image which will be a coordinate that will remove the distortion on processing. This will be done all around the image for as many points as required. The points will be sent to some Imagemagick code which will create an undistorted image.

Hi Rubble,

So, I understand your question as asking how to send multiple sets of points to the PHP script via AJAX.
I hope I got that right :slight_smile:

Basically, the data attribute accepts an object:

$.ajax({
  type: "POST",
  url: "points.php",
  data: { },   [COLOR="#FF0000"][B]<---- the curly braces denote an object[/B][/COLOR]
  success: function(response){
    // code here will be executed if request was successful
  }
});

So one possible solution here would be to add the sets of points to this object:

data: { 
  "points1": $("#points1").text(),
  "points2": $("#points2").text()
}

Then you would have access to $_POST[“points1”] and $_POST[“points2”] on the server.

If you have to do this for more than two images, it is better to create a generic function to grab the information for you and package it up in an object.
You could also create a nested array to send to the server, so in your PHP script you access $_POST[“points”][0], $_POST[“points”][1] etc

HTH

Thanks for the info Pullo

So I was sort of on the right track :slight_smile: I have a small problem which I thought would happen and that is the points from the second image are over writing the first.

Again I have tried a couple of things:

jquery.canvasAreaDraw.js


    record = function() {
      $(input).val(points.join(','));
		points.toString();
		document.getElementById("points1").innerHTML = points; 
    };
  };

transform.php


    <script>
      $("#createFile").on("click", function(){
        $.ajax({
          type: "POST",
          url: "pointsT.php",
          data: { 
  "points1": $("#points1").text(),
  "points2": $("#points2").text()},

          success: function(response){
            console.log(response);
          }
        });
      });
    </script>

Console output
"Array
(
[points1] => 77,129,79,270,259,271,276,154
[points2] =>
)
"

jquery.canvasAreaDraw.js


    record = function() {
      $(input).val(points.join(','));
		points.toString();
		document.getElementById("points1").innerHTML = points; 
		document.getElementById("points2").innerHTML = points; 
    };
  };

transform.php


    <script>
      $("#createFile").on("click", function(){
        $.ajax({
          type: "POST",
          url: "pointsT.php",
          data: { 
  "points1": $("#points1").text(),
  "points2": $("#points2").text()},

          success: function(response){
            console.log(response);
          }
        });
      });
    </script>

Console output
"Array
(
[points1] => 147,135,147,254,330,258,330,125
[points2] => 147,135,147,254,330,258,330,125
)
"

jquery.canvasAreaDraw.js


    record = function() {
      $(input).val(points.join(','));
		points.toString();
		document.getElementById("points1").innerHTML = points1; 
		document.getElementById("points2").innerHTML = points2; 
    };

transform.php


    <script>
      $("#createFile").on("click", function(){
        $.ajax({
          type: "POST",
          url: "pointsT.php",
          data: { 
  "points1": $("#points1").text(),
  "points2": $("#points2").text()},

          success: function(response){
            console.log(response);
          }
        });
      });
    </script>

Console output
"Array
(
[points1] => [object HTMLTextAreaElement]
[points2] => [object HTMLTextAreaElement]
)
"

I thought I could use a different jquery.canvasAreaDraw.js for each set of points but that gave a javascript error.

Out of interest this was the original function before I altered it for the first modified program that is working. I wonder did I need to convert the points to a string in the first place?


    record = function() {
      $(input).val(points.join(','));
    };

Hi Rubble,

Let’s see if we can get a reference to the points in question then.

I assume you have this (two text areas containing the points, each of which have unique ids):

<textarea id="points1">1,2,3,4,5</textarea>
<textarea id="points2">6,7,8,9,0</textarea>

What happens if you add a button to your page:

<button id="log">Log points</button>

Then the following JavaScript at the foot of the page:

<script>
  $("#log").on("click", function(){
    console.log("Points 1 contains: " + $("#points1").text());
    console.log("Points 2 contains: " + $("#points2").text());
    return false;
  });
</script>

What do you see logged to the console?