So I have an array of default values in a php array the file (backend.php) has multiple functions and acts. I want to target just the array with the act="default". I need to take the the encoded json php array and populate and html form with it.
html page - frontend.html
<html>
<head>
</head>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name:
<input id="name" type ="text" name="name"></input>
<br><br>
Postal Code:
<input id="postal" type ="text" name="postal"></input>
<br><br>
Phone Number:
<input id="phone" type ="text" name="phone"></input>
<br><br>
Address:
<input id="address" type ="text" name="address"></input>
<br><br>
<input type="submit"></input>
</form>
<div id= "content"></div>
Refresh
<a id="InsertDefault" href="#">Insert Default Data</a>
<br><br>
<ul id="errors"></ul>
<p id="success"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
php page - backend.php
<?php
if ($_REQUEST['act'] == 'default'){
$defaultData = array(
'name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street"
);
echo json_encode($defaultData);
}
else if...
?>
main.js page (errors here)
$(document).ready(function()
{
$("#InsertDefault").click(function()
{
// make an AJAX call here, and place results into the form
$(document).ready(function(){
$('#content').load('backend.php', {'default':'defaultData'}, //this format
function (){ $('#content').html('these are the default values')}
);
// prevents link click default behaviour
defaultData.preventDefault();
return false;
});
$("#PersonForm").submit(function()
{
// Clear any success or error messages
$("#success").html("");
$("#errors").empty();
// make an AJAX call here, and set error or success accordingly
// prevents submit button default behaviour
return false;
});
});
Instead of using .load it would be better to use $.ajax or $.post since $.load will set the content of the selected returned data (which should be either text or HTML). In your case you want to return json so that you can set the form element values.
$(document).ready(function()
{
$("#InsertDefault").click(function(e)
{
// prevents link click default behaviour
e.preventDefault();
// make an AJAX call here, and place results into the form
$.ajax({
url: 'backend.php',
type: 'post',
data: {
act:'default'
},
dataType: 'json',
success: function(data) {
// set the form values
$('[name=name]').val(data.name);
$('[name=postal]').val(data.postal);
$('[name=phone]').val(data.phone);
$('[name=address]').val(data.address);
// display message
$('#content').html('Fields filled in with default values');
},
error: function() {
// handle your error
console.log('error');
}
});
return false;
});
$("#PersonForm").submit(function()
{
// Clear any success or error messages
$("#success").html("");
$("#errors").empty();
// make an AJAX call here, and set error or success accordingly
// prevents submit button default behaviour
return false;
});
});
Since your AJAX call is expecting json return you need to use header('Content-Type: application/json'); in your php script to set the data type.
It's also a good idea to use output buffering (see ob_start() and ob_clean() below) so that any notices outputted by php do not dirty the json your AJAX call is expecting.
ob_start();
if (isset($_POST['act']))
{
if ($_POST['act'] == 'default')
{
ob_clean();
header('Content-Type: application/json');
$defaultData = array(
'name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street"
);
echo json_encode($defaultData);
exit();
}
}
Related
I have an html form and some php and a little bit of javascript. The form has two input tags. Both input tags have class attributes. I would like to 'store' the class value inside a PHP variable so I can echo after clicking submit.
I've tried integrating javascript with the first php variable ($firstclass) and failed to get it working even as an alert(). I really don't want to alert the class value but figured this would help find the solution.
<form action="" method="post">
<input type="text" name="input1" class="hidden_class_1">
<input type="text" name="input2" class="hidden_class_2">
<input type="submit" name="submit">
</form>
<?php
$firstclass = ""; //hidden_class_1
$secondclass = ""; //hidden_class_2
$firstclass = "<script type=\"application/javascript\">alert(('this.className').attr('class'))</script>";
$secondclass = ""; //ideally hidden_class_2
if(isset($_POST['submit'])){
echo "<h2>First Input Class Value: ".$firstclass."</h2>";
echo "<h2>Second Input Class Value: ".$secondclass."</h2>";
}
I expect the output to be as follows;
First Input Class Value: hidden_class_1
Second Input Class Value: hidden_class_2
The "easiest" way would be to use AJAX/XHR and send the classes to the PHP script.
<form id="ajaxform" action="path/to/script.php" method="post">
<input type="text" name="input1" class="hidden_class_1">
<input type="text" name="input2" class="hidden_class_2">
<input type="submit" name="submit">
</form>
For example, using jQuery:
const $form = $('#ajaxform');
function onSuccess (response) {
console.log('Successfully submitted the form');
console.log('Server responded with', response);
}
function onFailure (jqXhr, status) {
console.log('Ooops, something went wrong!');
console.log('Server sent status code', status);
}
$form.on('submit', event => {
event.preventDefault(); // suppress the reload
const $input1 = $form.find('[name=input1]');
const $input2 = $form.find('[name=input2]');
$.ajax({
method: $form.prop('method').toUpperCase(),
url: $form.prop('action'),
data: {
input1Value: $input1.val(),
input2Value: $input2.val(),
input1Class: $input1.prop('className'),
input2Class: $input2.prop('className')
}
}).
done(onSuccess).
fail(onFailure);
});
Inside you PHP, you'd use $_POST (or $_REQUEST) to grab the values which have been sent:
$input1_value = $_POST['input1Value'];
$input2_value = $_POST['input2Value'];
$input1_class = $_POST['input1Class'];
$input2_class = $_POST['input2Class'];
# do what you want with the variables
Note that you have to handle the server's response inside the onSuccess function. Usually, people use JSON to model a response from the server. You can use PHP's build-in json_encode and json_decode functions for it. For example, your PHP script could answer with:
$input1_value = $_POST['input1Value'];
$input2_value = $_POST['input2Value'];
$input1_class = $_POST['input1Class'];
$input2_class = $_POST['input2Class'];
# do what you want to do with the variables, then
$response = array(
'ok' => true,
'message' => 'PHP says "Thanks" for the information'
);
header('Content-Type: application/json');
echo json_encode($response);
die;
Inside the onSuccess function, you'd then for example:
function onSuccess (response) {
if (response.ok) {
console.log('Submitted, and all values where OK');
console.log(response.message);
return; // opt-out early, no need for "else" keyword
}
console.log('Submitted, but something went wrong');
console.log(response.message);
}
I'm test using ajax submit form (submit to myself page "new1.php")
The thing that I want is, after click submit button, it will echo firstname and lastname. But I don't know why I do not see the firstname and lastname after submit.
here is new1.php page
<?php
echo $_POST['firstname']."<br>";
echo $_POST['lastname']."<br>";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myform" action="new1.php" method="post">
Firstname : <input type="text" name="firstname"> <br>
Lastname : <input type="text" name="lastname"> <br>
<input type="submit" value="Submit">
</form>
<script>
// this is the id of the form
$("#myform").submit(function(e) {
$.ajax({
type: "POST",
url: 'new1.php',
data: $("#myform").serialize(), // serializes the form's elements.
success: function(data)
{
alert('yeah'); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
</body>
</html>
In your case the best option to retrieve values as JSON format using json_encode in your PHP code and then accessing these values through data object.
Example:
PHP code:
if($_POST)
{
$result['firstname'] = $_POST['firstname'];
$result['lastname'] = $_POST['lastname'];
echo json_encode($result);
die(); // Use die here to stop processing the code further
}
JS code:
$("#myform").submit(function (e) {
$.ajax({
type : "POST",
url : 'new1.php',
dataType : 'json', // Notice json here
data : $("#myform").serialize(), // serializes the form's elements.
success : function (data) {
alert('yeah'); // show response from the php script.
// make changed here
$('input[name="firstname"]').text(data.firstname);
$('input[name="lastname"]').text(data.lastname);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
When you use form as a serialize you have to retrieve like this.
Edit your ajax like this :
data: { formData: $("#myform").serialize()},
Then you can retrieve like this in your controller:
parse_str($_POST['formData'], $var);
echo "<pre>";
print_r($var);
exit;
Make some changes in javascript here:
success: function(data)
{
$('#response').html(data); // show response from the php script.
}
And in html code make a div with id response
<div id="response"></div>
Change from
alert('yeah'); // show response from the php script.
to
alert(data); // show response from the php script.
the value firstname, lastname will not display because you called the new1.php via ajax and the data (firstname, lastname and the page code) is returned to java script variable (data) you need to inject the data to your document
Try this
$.ajax({
type: "POST",
url: 'new1.php',
data: $("#myform").serialize(), // serializes the form's elements.
success: function(data) {
document.documentElement.innerHTML = data;
}
});
I am using codeigniter 3.1
Ajax post not working and i am getting 403 (Forbidden) in console.
[POST http://localhost/test/post 403 (Forbidden)]
HTML
<div class="post">
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
</div>
<button id="post">Submit</button>
JAVASCRIPT
$('#post').on('click', function () {
var value1=$("#data1").val();
var value2=$("#data2").val();
$.ajax({
url: window.location.href+'/post',
type: "POST",
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
});
CONTROLLERS
public function post()
{
$data1 = $this->common->nohtml($this->input->post("data1", true));
$data2 = $this->common->nohtml($this->input->post("data2", true));
$this->data_models->update($this->data->INFO, array(
"data1" => $data1,
"data2" => $data2,
)
);
}
If you want CSRF protection on (a good idea) then you must pass the CSRF token when posting form data - via AJAX or not. Consider this approach.
The easiest way to put the token in your form is to use Codeigniter's "Form Helper" (Documented here) You can load the function your controller or use autoloading. This view code assumes you have the helper loaded.
HTML
<div class="post">
<?= form_open('controller_name/post'); //makes form opening HTML tag ?>
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
<?php
echo form_submit('submit','Submit', ['id'=>'post']); //makes standard "submit" button html
echo form_close(); // outputs </form>
?>
</div>
The form_open() function also automatically adds a hidden field containing the CSRF token to the HTML.
Javascript
$('#post').submit(function( event ) {
//the next line will capture your form's fields to a format
//perfect for posting to the server
var postingData = $( this ).serializeArray();
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
data: postingData,
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
controller
By the time $_POST gets to your controller the CSRF token has been striped away so you don't have to worry about it "polluting" your incoming data.
public function post()
{
//get all the posted data in one gulp and NO, you do not want to use xss_clean
$posted = $this->input->post();
//With the above the var $posted has this value (showing made up values)
// array("data1" => "whatever was in the field", "data2" => "whatever was in the field");
//sanitize the field data (?)
//just stick the clean data back where it came from
$posted['data1'] = $this->common->nohtml($posted["data1"]);
$posted['data2'] = $this->common->nohtml($posted["data2"]);
$this->data_models->update($this->data->INFO, $posted);
//you must respond to the ajax in some fashion
//this could be one way to indicate success
$response['status'] = 'success';
echo json_encode($response);
}
You could also send back some other status if, for instance, the model function reported a problem. You then need to react to that status in you javascript. But if you don't respond it will likely result in problems down the road.
Wording might be a bit off. I'm trying to use the Battle.NET API to retrieve some information regarding characters. I have a 'server' field, and a 'char name' field.
I've reviewed a few of the similar questions, like this one, and maybe it's just my PHP new-ness but I'm getting confused on how to properly do it. I'm still not sure at all how to troubleshoot PHP errors.
What I did was design the HTML + PHP embedded into one 'php' file. It Worked. I then separated them into index.html + test.php it worked
The main issue with that was a few things - I wasn't rendering the response, I JUST had it 'echo' the response. Which appears to have been in JSON
{"lastModified":1477156067000,"name":"Thischaracter","realm":"Thisrealm","battlegroup":"Thisbattlegroup","class":1,"race":6,"gender":0,"level":110,"achievementPoints":20805,"thumbnail":"thrall/50/129432626-avatar.jpg","calcClass":"Z","faction":1,"totalHonorableKills":8657}
So the flow needs to be HTML Form - Submit -> AJAX -> PHP form (This is far as my "experience" goes, because I've never done anything with the response) -> MAYBE a getJSON from the PHP data? -> HTML output. I mention AJAX because I don't want the page to update. Just a 'div' or LI to be updated.
index.html -- I modified this form a bit before posting here to remove extra non-sense.
<form action="testingApiForBnet.php" method="post" id="myForm">
<p class="inp-wrap search-wrap">
<label for="search-field" class="search-label grid-25">Find</label>
<input type="search" name="search-term" id="charSearch" class="grid-75"/></p>
<p class="inp-wrap cat-wrap">
<label for="categories" class="grid-20">on</label>
<select name="search categories" id="servers" class="grid-80">
</select>
</p>
<submit name="SubmitButton">
</form>
testAPI.php
<?php
if(isset($_POST['SubmitButton']))
{
$charName = $_POST['charName'];
##$_POST['charName'];
$server = $_POST['servers'];
##$_POST['server'];
$bnetAPI = "https://us.api.battle.net/wow/character/";
$apiKey = "apiKeyWouldGoHere";
// Example https://us.api.battle.net/wow/character/$Server/$CharName?locale=en_US&apikey=$apiKey//
$request = $bnetAPI . urlencode($server) .'/'.$charName .'?locale=en_US&apikey=' . $apiKey ;
$response = file_get_contents($request);
$jsonobj = json_decode($response);
}
?>
The 'json_decode' and 'file_get_contents' I got from another thread, because I was getting non object responses. With those $jsonobj is putting out the object I linked above.
test.js
$(document).ready(function () {
$('#myForm').on('submit', function(e) {
e.preventDefault();
$.post('testAPI.php', $(this).serialize(), function (data) {
alert(data);
console.log(data)
return false;
})
});
});
Up until the "function (data)" this script is actually taken from another form I have that works successfully. Currently nothing is happening when I hit submit - No redirect, no response, no console.log - I feel like it's because I'm POSTing, and it needs to GET but then I'd still get 'something' from data?
Would appreciate any input. Also still unable to troubleshoot PHP, unless I run the PHP script directly. I feel this much just be functionality within the language.
Thanks!
UPDATE Placeholder.php
<?php
if (!empty($_POST)) {
$charName = $_POST['charName'];
##$_POST['charName'];
$server = $_POST['servers'];
##$_POST['server'];
$bnetAPI = "https://us.api.battle.net/wow/character/";
$apiKey = "key";
// Example https://us.api.battle.net/wow/character/Thrall/Teodoro?locale=en_US&apikey=$apiKey//
$request = $bnetAPI . $server .'/'.$charName .'?locale=en_US&apikey=' . $apiKey ;
$response = file_get_contents($request);
$jsonobj = json_decode($response);
header('Content-Type: application/json');
echo $response;
exit();
}
?>
UPDATE index.html (just JS portion)
$(document).ready(function () {
$('#myForm').submit(function (e) {
e.preventDefault();
$.post('test2.php', $(this).serialize(), function (data) {
console.log(typeof(data));
if (typeof data === 'string')
data = JSON.parse(data);
if (typeof data !== 'object') {
console.log("failed to parse data");
return;
}
data = JSON.parse(data);
console.log(data);
});
/*
*/
console.log('Data is not returning.');
return false;
});
});
Your jQuery code refers to a form with myForm ID, but you haven't assigned the ID to the form. So you should add the id attribute as follows
<form id="myForm">
Next, you have to fix the URL you post to. It should be testAPI.php, but not text.php:
$('#myForm').submit(function (e) {
e.preventDefault();
$.post('testAPI.php', function (data) {
// ...
});
})
Since you are binding the onsubmit, and handling the post request yourself, you probably don't need the action and method attributes in your form. Since the testAPI.php returns JSON content, you need to decode it in the request handler. Also, with the $.post() call you don't send any data to the server. It is just an empty POST request. You have to pass the serialized form as the second argument:
test.js
$('#myForm').submit(function (e) {
// note, `this` variable refers to the form node.
e.preventDefault();
$.post('testAPI.php', $(this).serialize(), function (data) {
if (typeof data === 'string')
data = JSON.parse(data);
console.log(data);
});
return false;
})
The code parses data, if it is a string. The jQuery handler may pass data as Object in case if the response returned Content-Type: application/json (in fact, is the right MIME type for JSON data). So you I'd recommend fixing the MIME type in testAPI.php, and, yes, you should print the response instead of decoding (unless you need to modify it):
header('Content-Type: application/json');
echo $response; // supposed to be a JSON string
exit();
If, however, you need a modified response, then decode it, modify, and encode, again:
header('Content-Type: application/json');
$response = json_decode($response, true);
$response['something'] = 'somevalue';
// unset($response['redundant_field']);
header('Content-Type: application/json');
echo json_encode($response); // supposed to be a JSON string
exit();
Example
test.php
<?php
if (!empty($_POST)) {
$search_term = $_POST['search-term'];
$category = $_POST['category'];
$fake_response = [
'term' => $search_term,
'cat' => $category,
'somethingelse' => date('r'),
];
header('Content-Type: application/json');
echo json_encode($fake_response);
exit();
}
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Test</title>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm">
<input type="search" name="search-term" id="charSearch"/>
<select name="category" id="servers">
<option value="optA" selected>optA<option>
<option value="optB">optB</option>
</select>
<input type="submit" name="SubmitButton"/>
</form>
<script>
$(document).ready(function () {
$('#myForm').submit(function (e) {
e.preventDefault();
$.post('test.php', $(this).serialize(), function (data) {
if (typeof data === 'string')
data = JSON.parse(data);
if (typeof data !== 'object') {
console.log("failed to parse data");
return;
}
console.log(data);
});
return false;
});
});
</script>
</body>
</html>
Sample output (in the browser's console)
Object { term: "rr", cat: "optA", somethingelse: "Sun, 23 Oct 2016 05:10:50 +0000" }
I would like to build a newsletter subscription function to my website. and I want to get all the input save into a txt file in the host folder. However, I don't want to switch page after people submit it. Just show a popup message saying "Thank You for Subscribing" will be perfect. I know how to do it with PHP to show a message in a separate page, but not sure how to do it in a popup box. Here is my html and PHP code. Please help, thanks a lot.
<html>
<head>
<title></title>
</head>
<body>
<form>
<form action="myprocessingscript.php" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Text file</a>
</body>
PHP function is
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
Once you have included jQuery to your page, something like following should work:
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'field1' : $('input[name=field1]').val(),
'field2' : $('input[name=field2]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myprocessingscript.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// data is the output from your php, check it and display alert appropriately
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Take a look at source article