Full disclaimer, I have a limited knowledge of JavaScrip, JQuery, Ajax and PHP and I have been struggling to fix my issue since mid March. I am trying to format some data into an array, using JavaScript, and then post it to a PHP page (which must open and display some HTML) using Ajax.
I have tried almost every variation I can think of for the following code:
(This code is in a <script>
tag below the Form in the HTML Document and script tags in the header include the Ajax
and JavaScript
src
references)
$("#dataForm").submit(function(event){
console.log("Submit started");
var test = $("#title").val();
var serData = 'test1='+test;
//event.preventDefault();
//POST to PHP
$.ajax({
method: "POST",
url: "summary.php",
data: {serData: serData},
success: function(response){
console.log("Success!");
},
error: function(xhr, ajaxOptions, thrownError){
console.log("Didn't work!");
}
});
//event.preventDefault();
});
But this does not even POST the data and instead shows all of the data in the URL area - nor does it load the PHP page. I cannot find any references to explain how this should be done.
I did find this window.location = "summary.php"
- however, it only loads the PHP page and none of the data is POSTed.
Here is my HTML:
<form id="dataForm">
<strong>Title:</strong>
<input type="text" name="title">
<input type="submit" name="sub_button" value="Submit">
</form>
And PHP (summary.php
):
if (isset($_POST['serData'])){
echo "Data POSTed: ";
echo $_POST["test1"];
$test1 = $_POST["test1"];
}
//assume there is some simple HTML code here
<html>
<p>{$test1}</p>
</html>
The console logs "Success!" each time, but I am having no such success.
So to summarize - for testing purposes I would just like to POST this test1
variable and retrieve it on the PHP side, then display the PHP HTML page.
From there on, I would like to know the best way to POST a JavaScript array to PHP (thinking JSON here) and whether it is best to add this array onto the end of ("#dataForm").serialize()
(eg. ("#dataForm").serialize() +"&array"
) OR to POST it separately (if that is indeed possible).
Happy to provide more code if need be! Cheers
Edit1:
My data
now looks like
data: { serData: true, test1: $('input[name="title"]').val() }
When I hit the submit button the data no longer shows in the URL! This is good! But the PHP page still doesnt open! Am I missing something here?