Simulate html form POST using ajax/jquery - php

I want to read all the post variables and their content from a form and post them using jquery's "$.post()".
First of all, this won't do the job:
$.post("myServer.com/test2.php", $('#myform').serialize())
because it would only send one variable which I'd have to parse on the php side.
Here is how I'd start:
function doIndirectPost() {
variableWithTheFormPOSTData = {};
$("#IdOfMyForm :input").each(function() {
variableWithTheFormPOSTData[$(this).attr("name")] = $(this).attr("value");
}
document.getElementById("IdOfMyForm").submit();
$.post("myServer.com/test2.php", variableWithTheFormPOSTData);
}
and then I'd like to use $.post() to post the data seperated in multiple variables (just like a normal form submit would do it...
I read somewhere, that you could do that like this:
$.post('myserver.com/test2.php.php',{
var1: content1,
var2: content2
}
But I want it to be dynamic. This part:
var1: content1,
var2: content2
should autmatically contain all variable names and values of the form.
In the end I'd like to be able to get all POST variables like this:
foreach ($_POST as $key => $value)
{
echo $key . "= " . $value;
}

Serialize doesn't send only one variable, it sends name value pairs of all input elements in the form. So
$("#IdOfMyForm").on("submit", function () {
$.post("myServer.com/test2.php", $("#IdOfMyForm").serialize(),
function(dataFromServer){
//server sent a response now do whatever you want to do after form has been submitted
//or submit form regular way $("#IdOfMyForm").submit();
}
);
return false;
});
Should work. Just remember to set name attribute of every input/select element in form.

Have you tried it using JQuery's Ajax instead?
Like this answer here:
jQuery Ajax POST example with PHP

Related

php how to handle hyperlink like a POST instead of GET?

I will have a query that return a set of results, and these results will be in hyperlink form as shown below:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
Now user get to click on this hyperlink and get routed to abc.php?cif=$cif..
My question is, is it possible to only show abc.php to user, just like a POST method, and $cif remains available at abc.php?
As #Flosculus said above, the "best" solution to simulate a post request is doing something like proposed here: JavaScript post request like a form submit
However, despite it's surely a reliable solution, I'm wondering you just don't use sessions instead, something like:
From the page where you set the cif variable:
session_start();
$_SESSION['cif'] = $row['cif'];
In abc.php:
session_start();
if (isset($_SESSION['cif'])) {
// Do what you need
}
EDIT::
Another (possible) solution is setting an hidden input and silently submit a form when you click on an anchor, like this:
From your example, instead of:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
You do this:
When you print all the entries, please add this first (from PHP):
<?php
echo <<<HEADER
<form action="abc.php" method="post" id="submitAble">
<input type="hidden" name="cif" id="cif" value="{$row['cif']}">
<table>
HEADER;
// Get data from your query.. Here is an example:
while ($row = mysli_fetch_assoc($query)) {
echo <<<ENTRY
<tr>
<td>{$row['cif']}</td>
</tr>
ENTRY;
}
echo "</table> <!-- \table collapse --></form> <!-- \form collapse -->";
?>
Then, if you're using jQuery (thing that I'm recommending), simply add an event listener in javascript, like this:
$('.cifSetter').on('click', function(e) {
e.preventDefault();
$('#cif').val($(this).data('cif'));
$('#submitAble').submit();
});
If you don't have jQuery, use this instead:
var cifSetter = document.getElementsByClassName('cifSetter');
for (var i = 0; i < cifSetter.length; i++) {
cifSetter[i].addEventListener('click', function(e) {
e.preventDefault();
var cif = document.getElementById('cif');
cif.value = this.dataset.cif;
document.getElementById('submitAble').submit();
});
}
In both ways, whenever an anchor gets clicked, it will prevent its standard behavior (redirecting) and will instead set the value of an hidden field to the value of the CURRENT "cif" and submit the form with the desired value.
To retrieve the desired value from abc.php, just do this:
$cif = $_POST['cif'];
However, keep in mind that the hidden field is editable by the client (most persons won't be able to edit it, though), therefore you should also sanitize your data when you retrieve it.
Sessions could do it but I'd recommend to just use $_POST. I dont get why you wouldn't want to use POST.

Passing JavaScript array using AJAX

I'm very new to ajax and I'm trying to pass an array that I have created in javascript called markers over to a PHP page when the user clicks the submit button. At the time of submission the array exists and is within scope. The code below is what is trying to do that. When I click the submit button I get sent to the php page and "failed" is printed (part of my code) meaning the array was not passed. I believe the error occurs in the ajax code and I'm not sure where it is coming from, any help is greatly appreciated!
The javascript/ajax stuff:
function submit_tour(){
var input = JSON.stringify(markers);
//var input = $(this).serialize();
var sent = $.ajax({
type: "POST",
data: input,
dataType: 'JSON',
url: "test_portal2.php"
}).done(function() {window.alert("done");})
.fail(function() {window.alert("failed");});
window.alert("" + input);
}
The HTML button that is supposed to send the array:
<form name="toursubmit" action="test_portal2.php" onsubmit="submit_tour()">
<input type="submit" value="Submit">
</form>
The PHP that catches it (in the test_portal.php file):
$ans = json_decode($sent);
echo $ans;
if ($ans != NULL){
echo "works";
echo $ans;
}
else {
echo 'failed';
}
A couple of things to point out.
First, you need to prevent the default POST action within your submit_tour() function, otherwise the synchronous POST will happen.
Second, you need to specify the contentType value in your AJAX call as application/json.
Third, if you are actually POSTing JSON to PHP and using application/json as the ContentType, then you will need to get the JSON data in PHP by accessing the raw input like this:
$json = file_get_contents('php://input');
$obj = json_decode($json);
This is because $_POST is only auto-generated for form-encoded content types.
When you send
var input = JSON.stringify(markers);
And markers has no value
<input type="hidden" id="markers" name="markers"> // No value anywhere
Then it will surely be Null :)
Also do you populate your $sent variable from a value in $_POST ? don't see that happening
You don't need this in a form tag. The code is submitting the form and not running the JS.
Remove the form tag, or put this: submit_tour(); in onsubmit on the form instead, and return false.

Ajax Form submit receiving in PHP

I am experiencing some issues with a form I am making. I have the code to post a form to my PHP script that is meant to handle the data with this code:
<script type="text/javascript">
$(document).ready(function()
{
$("#submit").click(function()
{
var q1 = $("#q1").val();
var q2 = $("#q2").val();
var answers = "page=1&q1="+q1+"&q2="+q2;
$.ajax({
type:'POST',
url:'add.php',
data:answers,
success:function(response)
{
$("#answers").html(response);
}
});
});
});
</script>
This form is then received in my PHP script like this:
$page = $_POST['page'];
$q1 = $_POST['q1'];
$q2 = $_POST['q2'];
echo "Page: " .$page . "<br/>Question 1: " . $q1 . "<br/>Question 2: " . $q2;
The issue of it all is that I want this form to be able to handle X amount of inputs and also handle input I do not know the name of. Like I can get 5 textboxes, or 2 textboxes + a string of radiobuttons and so on. Is there a way to collect ALL $_POST data and then explode it or something similar so I can get it ready for the database? I wish to recover all question id's(values) and all answer values(could be a string or an int representing a radiobutton id).
You can iterate through all POST and GET request parameters by simply treating POST and GET as an array. For an example:
print_r($_POST);
Alternatively:
foreach ($_POST as $key => $value) {
echo $key." = ".$value."<br>";
}
If you want to handle a variating amount of input fields, you can define an incrementing naming convention and use loops to gather them all to an array.
with print_r($_POST); you can look at all values.
or something like this:
foreach ( $_POST AS $key => $value) {
echo $key." => ".$value."<br>";
}
First: Let jQuery build your data string, your current method requires you to know each field in advance and can't handle data with special characters in it.
url:'add.php',
data: $('#myForm').serialize(),
success:function(response)
Second: Name your fields using the PHP multiple fields with the same name convention:
<input type="radio" name="answer[1]" value="foo">
<input type="radio" name="answer[1]" value="bar">
You can then access them as:
$_POST['answer'][]
It is an array, so you can get the '1' and the 'foo' or the 'bar' in a loop.

Get form field names with javascript or php?

Is there a way to return a list / array of all the field names that are contained within a form? I.e if i made a form with 10 fields ('name', 'email' etc...) on submit i can determine what the element names are?
JavaScript
The raw JS way to do that is:
const inputs = document['<your form name>'].getElementsByTagName("input");
for (const input in inputs) {
if (inputs[input] && inputs[input].name) {
console.log(inputs[input].name);
}
}
PHP
Yes. They are all in the superglobals $_GET (for all of the GET variables), $_POST (if your form has method="POST"), and $_REQUEST ($_REQUEST is, by default Environment, Get, Post, Cookie, and Server (in that order) you can read more here).
If you want to just get the names, then you can use array_keys on any of the above.
In JavaScript we can get the name attribute of each form element like this:
$('form').on('submit', function () {
var names = [];
$.each($(this).find('input, textarea'), function () {
names.push(this.name);
});
});
This gathers the name attribute of each input or textarea element in the form and puts them in an array, names.
Note that .on() is new as of jQuery 1.7 and in this case is the same as using .bind(): http://api.jquery.com/on
In PHP you can loop through each of the $_GET or $_POST variables:
<?php
$names = array();
if (isset($_POST) && !empty($_POST)) {
foreach ($_POST as $key => $val) {
//$key is the name you wanted, and $val is the value of that input
$names[] = $key;
}
}
?>
And again, the $names variable is an array of all the names of form elements.
Update
If you want to create an associative array of names : values in JS you can do this:
$('form').on('submit', function () {
var names = {};
$.each($(this).find('input, textarea'), function () {
names[this.name] = this.value;
});
});
Now you can access the names variable like this:
alert(names.email);//this will alert the value of the input who's name is `email`
jQuery serialize:
http://api.jquery.com/serialize/
$('form').submit(function() {
alert($(this).serialize());
return false;
});
the $_POST array contains all the field that have been submitted if the form's method was post. If the method was get then $_GET has the form fields (as well as any other get params that happen to be in the URL)
With JQuery you can know it by selecting the input elements and using attr('name');
With PHP :
you can traverse $_GET, $_POST with foreach
You can also get the list of keys by using array_keys($_POST);
:input selector will find form elements in client
http://api.jquery.com/input-selector/
demo http://jsfiddle.net/JBsbL/
$('form').submit(function() {
var inputList = [];
$(this).find(':input').each(function() {
inputList.push(this.name);
})
alert(inputList.join(', '))
return false;
})​
Yes, they are the keys of your $_POST e.g:
$_POST['name'] = 'whatever name was in the form';
You can do a print_r($_POST) to see all keys.
(or $_GET depending on your forms submit method)
These solutions fully solve your problem, but they wroted as use jQuery. jQuery is not a populer library nowadays. We can solve with pure JavaScript more easily.
[...document.querySelectorAll("form input, form textarea, form select")].map(el => el.name)

Javascript get form value in URL without jQuery

If data is submitted via POST through the classic HTML form method is it possible to access those values using standard Javascript without libraries? How would this be done?
Edit for clarity: The variables have been posted. I am trying to access those values via javascript.
Thinking outside the box: (A hack that should never see the light of day)
For this example the posted variable is "a":
var val=document.URL;
var start;
start = val.search(/a=/);
var end;
end = val.search(/&/);
var thispos = val.substring(start+2,end);
document.URL returns the url of the current site.
val.search returns the position of the first occurrence of the regular expression in
the parameter field.
substring the two and...
thispos now contains the posted variable.
Brutal but functional. Is this too terrible to be an answer?
use:
var myField = document.getElementById('myFieldId');
then myField.value will contain the value.
If you have submitted the page, then you have to get the form data using PHP.
Here is a tutorial that should help: http://www.phpf1.com/tutorial/php-form.html
But if you decide to test jQuery, you can use this:
jQuery('#submit').live('click', function()
{
var form_data = jQuery("#data_form").serialize();
//Save data
jQuery.ajax({
url: siteURL +"/path/to/php/file/jquery.php",
data: {formData : form_data,
success: (function(data) {
//data is whatever you return from jquery.php
//I use json for return data
alert('Data has been saved');
}),
dataType: 'json'
});
After a post, the data is send to the server, javascript cant do anything with that since its client side. What you can do is pre-check with document.getElementById('formid') and use those values in the form. After validating or doing what you want to do, end with form.submit() to really send it to the server.
function getUrlInfo() {
var data = window.location.search.substring(1).split("&");
//returns an array of strings containing the params and their values
// data = [ "param=value","param=value","param=value"]
var params1Array = data[0].substring(0).split("=");
//Splits the first string element at the "=" symbol and
//returns an array with the param and value
//param1Array = ["param","value"]
var param1Value = param1Array[1].replace("+", " ");
//Gets the value from the second element in the param1Array
//Replaces the spaces, if any, in the second element,
//which is the value of the url param
var param2Array = data[1].substring(0).split("=");
//Repeat steps for the second param element,in the url params data array
var param2Value= param2Array[1].replace("+", " ");
return {
param1Value,
param2Value
}
};
The submitted data (either POST or GET) is proccesed on the server side. Javascript runs on the client-side so you can't access the variables from the page receiving the form request.
But you can access them before the post using the input field id (specially to check the input values before sending them).

Categories