Posting JSON with http post and other data to php page - php

I have a php page and I want to be able to submit a JSON string, and a few other fields back to itself (http post) so I can do some server-side PHP work. Since I'm new to PHP I see a lot of ways of doing this, but some of them aren't working the way I wanted because I wanted to post to the actual page itself so it can do some backend with a lot of session data, page specific data depending where the page came from, etc before moving on. For this reason AJAX is out of the question.
My JSON string is being created in javascript using JSON.stringify off an object array that I have created. Right now I just output my JSON using..
var output = JSON.stringify(objectTable);
console.log(output);
And the JSON is created perfectly no issues there. I have a few input fields on the page as well that I need to be posted back. Up to this point (before I needed to send the JSON) I just been doing..
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return validateData()" method="post">
<input type="text" id="itemName" value="page1" />
<input type="text" id="itemColor" value="red" />
<input type="submit" value="submit">
</form>
This of course works perfectly fine, but now with the JSON I'm starting to wounder if I should be doing something else? I know I could maybe create an and then when my javascript runs and does the JSON.stringify then just set the input value to the JSON. However these seems kind of "cheap" and doesn't seem to be the best practice to me. I also worry if there are any downfalls to doing this method such as special character issues or anything? Is there a different, more logical, or professional way I should be doing this?

Simple, Works, Totaly okay method
So if the objectTable object needs to be sent to the same PHP script at the same time as the other data in the form, then just create a hidden field in the form and when the user hits submit, set the hidden value to that of the object.
<input id='secretSHhhhhh' type='hidden' value='false'>
Then in JS (I am using some jQuery notation because I am lazy).
$('form').on('submit',function() {
/* ... stuff ... */
$('#secretSHhhhhh').val(JSON.stringify(objectTable));
});
Otherwise if you want to send the json encoded object to a PHP script that is kind of independent of the form, then I recommend using ajax. Once again I am using jQuery because it is easy, especially for ajax. In this case I am using the post subset of ajax, but there are many more options in the jQuery library.
$.post("somePage.php", objectTable,function( stuffThePageReturned ) { // No need to stringify
console.log(stuffThePageReturned);
});
My preferred method
$('form').on('submit',function(e) {
e.preventDefault();
var PostData = {};
PostData.itemName = $('#itemName').val();
PostData.itemColor = $('#itemColor').val();
// === Any extra fills from input elements === //
PostData.objectTable = objectTable;
$.post("somePage.php", PostData,function( stuffThePageReturned ) {
console.log(stuffThePageReturned);
});
});

Related

Submitting multiple HTML forms + other variable data with AJAX .on(click) method

I suppose really this is a continuation of my last question titled "Submit multiple HTML forms with a single submit button via AJAX" which got me started with some very basic AJAX. You really have to read that question to understand this one thoroughly. The key to this question now is other variable data...
So, I have a basic AJAX submit script running with jQuery, it's a duplicate to the answer on my previous question (minus a change from 'button' to 'input#publishimages'), and it works well at iterating through multiple forms and submitting them all:
function post_form_data(data) {
$.ajax({
type: 'POST',
url: 'verify.php',
data: data,
success: function () {},
error: function () {}
});
}
$('input#publishimages').on('click', function () {
$('form').each(function () {
post_form_data($(this).serialize());
});
});
The form which is being submitted (each form is equal to one image, so iterate over as many times as needed to submit each image - see more is my previous question) is also in the previous question, and looks similar to this:
<form id="image<?php echo $i; ?>">
<label>Name</label>
<input name="image[<?php echo $i; ?>][Name]" />
<label>Location</label>
<input name="image[<?php echo $i; ?>][Location]" />
<!-- etc, etc, for description, coordinates, camera etc -->
</form>
Well in retrospect, sadly that was a bit too watered down; and this is where the other variable data bit comes into play. I'm now examining each image's EXIF data for additional information, and removing inputs from the form if I find data which would otherwise have to be filled out by the user on the form, if not, display the input so the user can fill it out themselves. So the PHP script with the form in it looks a bit more like this (pseudcode):
<form id="image<?php echo $i; ?>">
<label>Name</label>
<input name="image[<?php echo $i; ?>][Name]" />
// Examine EXIF Data
if (I find EXIF Location Data) {
$_POST['image'][$i]['location'] = $location;
} else {
<label>Location</label>
<input name="image[<?php echo $i; ?>][Location]" />
}
// etc, etc, similar situation occurs with camera make + model, date taken etc.
</form>
So what you can see I'm doing is selectively removing and adding inputs to a form dynamically if I find/do not find information. If I find it, submit the information to the $_POST superglobal, else just echo out a input in the form for the user to fill out. What's the problem? The Javascript.
This is a problem because...
Now, when I reference $(this) (referring of course to the $('form')), only some variables (depending how much EXIF data I managed to extract) are sent via AJAX to their destination, because they're no longer part of the form and the input doesn't exist - instead I've assigned them to the $_POST superglobal and they've become inaccessible to my jquery script.
So...
I need a way of being able to submit EVERYTHING pertaining to the image via AJAX to my destination, no matter whether it was POSTED or submitted as part of the form. I'm totally at a loss on how to achieve this... any suggestions?
You're 'double submitting'. Inside your AJAX function intercept the click and prevent the default:
$('input#publishimages').on('click', function (e) {
e.preventDefault();
$('form').each(function () {
post_form_data($(this).serialize());
});
});
This will stop the form from submitting. A submitted form is nothing but a POST or GET request anyways.
Other than that I'm confused as to what you're trying to accomplish. It sounds like the data is incomplete because of a validation step? User submits form, some EXIF data is grabbed, and new inputs are returned with the missing data, but then the EXIF data has dissolved in a puff of zeros and ones, right? If that's the case you could use hidden form fields:
if (I find EXIF Location Data) {
$_POST['image'][$i]['location'] = $location;
echo '<input type="hidden" value="$foo" name="$bar" />;
} else {
<label>Location</label>
<input name="image[<?php echo $i; ?>][Location]" />
}
You could just keep inputs for everything. For those that have existing data in EXIF, simply fill it in and hide the inputs from user with CSS. This way, you can handle the forms in a more generic fashion and your problem is gone.

Onblur or onchange check, using a php function in a registration form

I would like to be able to check the text in a text-box after it has changed, and report what is wrong.
It is for a registration form.
This is a part of register.php where
<form action"" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p><input name="username-field" type="text" onblur="someFunction()" /><span id="UsernamehelpText"> </span>
</li>
</ul>
</form>
Then I would have a registerfunctions.php where i would store all the functions for checking lenght,char,maybe regex etc.. Its not really that important what functions i call. I just don't know how to call them.
Form what i have seen the span is where u post the errors, but if there is any other option im open for it, all i want is to be able to post the erorr text in the same line as the text-box
I have checked JavaScript and AJAX, but I am pretty new in this and don't really understand how it works.
After discussion in comments I understand what you want.
First, an explanation. There are two places where validation occurs: In your frontend (your web page) and in your backend (in the PHP script that saves the posted values). Anything that you really don't want to save - for example unescaped SQL strings, too-long fields, and so on - has to be validated in PHP, because it is trivial to get around Javascript validation. For example, nothing is stopping someone from sending a POST to your server containing illegal values without even bothering to visit your webpage.
Even though you need to perform validation in the back-end, it's still user friendly to do the same validation in the front end, so the user doesn't have to wait as long to see an error. This also reduces traffic to your server. Something you probably want to do in a big project is to have some kind of system for writing validation rules centrally, and then using those rules to dynamically generate both PHP and Javascript validation. The advantage of doing that is that you don't duplicate your business rules in two places, but in a smaller project it's probably not worth the hassle.
Validation in the frontend looks about like this: You bind an event handler to an appropriate event or events (you can add onkeydown="validateUserName()" for example, so that the validation reacts a bit quicker), and update your warning text appropriately.
<form action="" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p>
<input id="username" name="username-field" type="text" onblur="validateUserName()" />
<span id="UsernamehelpText"></span>
</li>
</ul>
</form>
<script type="text/javascript">
function validateUserName() {
var userNameElement = document.getElementById('username');
//Do your work: Get the value of the user name field, check
// the values against your validation rules...
var helpText = document.getElementById('UsernamehelpText');
if(isValid)
helpText.innerHTML = "";
else
helpText.innerHTML = "Invalid!";
}
</script>
In the backend, when you process the form, you then have to check the same rules in PHP to prevent illegal values from being posted either maliciously or due to an error in your Javascript. If an error is found, you don't save, instead you can just re-render the form with the submitted values in the input fields and a message indicating what was invalid - this allows the user to change their inputs without losing the values they submitted.
With jQuery it would look something like this:
function someFunction() {
$.ajax({
url: "checkStuff.php",
data: $("input[name='username-field']").serialize,
success: function(data) {
if (data == "correct") {
$("#UsernamehelpText").html("Valid");
} else {
$("#UsernamehelpText").html("Invalid");
}
}
});
}
Your PHP could be something very simple that just checks the validity of the input and then echos "correct" if it is.

Create Php page that redirects to another page transmitting some content

I'm a beginner with PHP and I'd like to do the following but I have not a clue of how to do this :
I have a webpage where I ask a user to submit his postal code. After he/she submits it the page redirects to another PHP page where I search in a datebase the city corresponding to the postal code. Then I write : "You're city is ...".
What I'd like is to have this happen using only one webpage (with no visible redirection for the user). I know we can use header to redirect to the first page but I don't know how to transmit the content (city).
You can pass city name in query parameter like
headers('Location: serachdatabase.php?city='.$cityname);
But that may not be what you are looking for. You can consider using Ajax to do this. Using Ajax the page will not refresh completely but only the portion of page can be refreshed. Ajax, if you dont know about it, is widely used.
It sounds like you're looking for an AJAX post. This might sound like an advanced topic for a beginner, but if you check out a framework like jQuery (http://api.jquery.com/jQuery.post/) you'll see it's quite simple.
Try something like this:
$('#myform').submit(function() {
var url = 'databasequery.php';
var postcode = $('#postcode').val();
$.post( url, { postcode: postcode },
function( data ) {
$( "#result" ).empty().append( data );
}
);
return false;
});
In your HTML you would tag your form as myform and create an empty div with the id "result".
Your 'databasequery.php' file should accept a POST variable called postcode and simply output the response you want to display on your page.
You can redirect using header("Location:...");
or you could simply just post a form
<form method="post" action="yourURL">
Postal code <input type='text' name='postal_code' /> <br/>
<input type="submit" value="submit form" name="submit" />
</form>
and then do in php something like this:
<?php
$postal = $_POST["postal_code"];
// match against databse..
?>
Note that this code isn't "safe" to put it in a mysql query!
If you don't want any page redirect, you'll need to use either an iFrame or some CSS-id'd divs to load your content into using javascript's XMLHttpRequest or jQuery's axaj or similar to load info from another PHP page and insert it inside the current document.
Here is an example use of XmlHttpRequest, and Here is jQuery's API documentation on its ajax method.
The key to your problem's solution are GET and POST parameters. Learn about HTML forms.

grabbing POST values with javascript

Forgive me for asking a seemingly obvious question, but all of my searching is turning up guides on how to create POST values with JS, not how to grab (and utilize) them.
What I want to do:
step1.php -- form POSTing to step2.php
step2.php -- also a form, JS grabs one particular POST value and does some work with it, then updates this new form accordingly
for reasons not worth getting into, the process needs to be a 2 step//2 page process.
The obvious solution is just to do something like:
<script type="text/javascript">
function damn_ugly () {
var shameful = <?php echo $_POST['desiredDatum']; ?>;
do more stuff...
}
</script>
but that seems a bit dirty to me.
Is there a better way? or is that really how I'm supposed to do it?
var postData = <?php echo json_encode($_POST); ?>;
You can obviously change that to include only certain fields from $_POST by passing a custom array to json_encode.
var desiredDatum = <?php echo json_encode($_POST['desiredDatum']); ?>;
There is no nicer way to do it - and using json_encode ensures no matter what's contained in the POST variable nothing will break (at least not during the assignment).
That is how you are supposed to do it, JavaScript cannot access the POST values in another way.
Offcourse you can make it a bit more beautiful: have your php-script put the POST variables in an array, and print the array in JSON format. Now your javascript has the array.
POST values are being sent to the server. Once submitted only the server can work with those values. Your example is pretty much the only option you have to "access" POST values that have been sent to the server in the previous request.
JS has no access to POST values, it can only retrieve GET values. However, since you're using a PHP script and you're able to pass the data to JS - why not give your JS functions data in JSON format? You can use PHP's json_encode function to encode all POST values to JSON that you can use then easily in your JS code.
Try this
On second step Page 2:
Set hidden text box on page:
<input type='hidden' name='text1' id = 'text1' value='<?php echo $_POST['desiredDatum']; ?>' />
Now if you use jQuery the wirite below given code
$(document).ready(function() {
var shameful = $('#text1').val();
});
if not using jQuery Then
var shameful = document.getElementById('text1').value;
I hope this is what you are looking for.

Accessing text in a field placed by JS, via PHP

In PHP, in a particular CMS I am using a custom field, which works like google suggest.
As in, for each letter I type an SQL query is performed and matching records are displayed. When clicking on a record it fills the field with that record.
I am fairly certain this is all done with JavaScript.
I need to know how I can access the resultant content of that field, with the text placed through JS, before it is submitted so I can explode() it.
The CMS I am using is using mootools, so a solution relying on mootools would be ideal.
(This answer assumes that you have control over the markup of your forms (the form that requires a string "explosion" before submit) and/or you feel comfortable tinkering with whatever plugins you're using.)
first, make sure that you aren't submitting your form using an actual submit button (). We'll need to submit the form using javascript after fiddling with the field's contents.
next, make sure that your input box (the one you're grabbing text from) and your hidden inputs have unique ids. This will make it easier to query the DOM for the data we need.
Inside your form, in place of a "real" submit button, create a form button:
<form action="something.php" name="myform">
<input type="hidden" id="hiddenItem">
// SOME STUFF
<input type="text" id="autocomplete_field" value="whatever"/>
// SOME OTHER STUFF
<input type="button" value="Submit" onclick="processForm(this)"/>
</form>
Then, write a javascript function to process the string and submit the form:
processForm = function(el){
text = $('autocomplete_field').get('value');
// Lets assume the strings separates words (what you're exploding apart) using spaces
// something like 'DOGS CATS BIRDS PETS'
var array = text.split(' ');
// returns ['DOGS','CATS','BIRDS','PETS']
$('hiddenItem').set('value',array[0]);
// #hiddenItem now has the value 'dogs'
//SUBMIT THE FORM
el.getParent('form').submit();
};
Hope this helps!
You could try to use JS to send the field on some event (onkeyup?) to your php script. After it does it's part, store the result as a session variable and you can retrieve that later.
Try using jquery's get function.
Was that your question?

Categories