Hey all, using this method jQuery append() and remove() element i'm adding text inputs to a document. i'm using this php
if($_POST['cp_slider'])
{
$array=$_POST['cp_slider'];
foreach($array as $cp_slider)
{
if(strlen($cp_slider)>0)
{
echo '<li><input type="text" name="cp_slider[]" value="'.$this->options["theme_slider"].'" /><img src="images/delete.gif" /></li>';
}
}
}
The value was created like this:
if ($_POST['to_action'] == 'save') {
$this->options["theme_slider"] = $_POST['cp_slider'];
update_option('artTheme', $this->options);
}
But what i see in the value of every input after submitting the form is: Array as a word.
UPDATE
I figured it out and it's working fine. The value gets it's real value, i've just changed the foreach line
from this
foreach($array as $cp_slider)
to this
foreach($array as $this->options["theme_slider"])
But there is still one problem there. After i submit the form, the data from inputs submits very well. But when i go to another page with in the application and then i'm comming back to the page with this inputs, they are simply not there, they just disappear from the page.
this question seems to vague there are many ways to submit form data so I guess start with a form then choose ajax or maybe you want to look at jquery validation
HTH
If you are trying to save the data, your jQuery will have to send the request to a PHP script that will take the input and put it into the database somehow.
User Makes Edits
Presses 'Save'
The Save button fires off a jQuery
AJAX request that sends the
appropriate data to a PHP script that
processes/sanitizes it and then puts
it into the database
If you don't make a call to another script, jQuery will just be updating the HTML seen in the browser and your PHP scripts won't know anything about it.
Related
I've Googled and searched on SO quite a bit for this unique problem, but not really finding my exact solution.
I have a basic form with X number of inputs. At some point in the form, the user as the freedom to add inputs via button click if needed. When they submit the form, it goes to another page to collect the posted form data, but I want the ability for the user to click "Back" (or send them back programmatically) if the submit fails.
I have error checking setup prior to submit via javascript, but there are other things (such as a PHP mailer) that could fail and I want them to be able to resubmit their data.
The issue of course is when the browser clicks back, it - at best - refreshes the initial form that was in the DOM with input data, but I lose all of the dynamically added inputs.
I want to capture the form/data in a session and have it repopulate the DOM with the submitted version created by the user on click back.
The closest I've come is doing something like this on SUBMIT:
var theForm = $('#myForm');
sessionStorage.setItem('formData', JSON.stringify(theForm.clone(true).html().toString());
And this on postback/click back:
$('#myForm').replaceWith(JSON.parse(sessionStorage.getItem("formData")));
The problem here is I get my form, but not the data! Do I need to iterate over each input to get my data put back in the recreated form?? Why doesn't it grab the data when .clone(true)ed?
Here's the answer I ultimately got to work.
Upon form validation, I set the session to hold the form data like so:
var theForm = $('#MyForm');
sessionStorage.setItem('formHTML', JSON.stringify(theForm.clone(true).html()));
theForm.find('input,select,textarea').each(function(){
sessionStorage.setItem(this.name,this.value);
});
Then, when the DOM loads again, I have this that checks for the session and populates the form with data if it exists:
$(document).ready(function(){
if (sessionStorage.getItem("formHTML")) {
$('#MyForm').html($.parseJSON(sessionStorage.getItem("formHTML")));
}
$('#MyForm').find('input,select,textarea').each(function(i,elem){
var sessItem = elem.name, sessValue = '';
if (sessValue = sessionStorage.getItem(sessItem)) {
if(elem.type=='radio' && elem.value==sessValue){
alert(elem[i].type+' has value of "'+elem[i].value+'"');
$('[name='+sessItem+']')[i].prop('checked',true);
}
else if(elem.type=='textarea'){
alert(elem.type);
$('[name='+sessItem+']').val(sessValue);
}
else
{
$('[name='+sessItem+']').val(sessValue);
}
}
});
});
I have a page for asking queries to an SQL database. Its only purpose is to allow students to exercise. Depending on the students activity the page rewrites itself with new content so that the student may enter a query, have the resulting table shown or get an error message.
All is working through forms that post data to the same page.
However, if a student uses the back button or the forward button (after hitting the back button) data gets lost as I cleanse the $_POST variable content to get ready for new action.
There is, however, a "go back" button that assembles data to restore the previous page by POSTing the required data. Is it possible to use some kind of technique, javascript, html5, PHP or whatever to actually submit the form that posts the assembled data when hitting the browser back button?
I am using HTML 5, PHP 5 and some JavaScript (not JQuery but if it gives me an option ...)
you can use the html5 storage since if user not fill the full form or close the browser the data will lost on close browser and not submit it form not fill
to check html5 storage
function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
use onkeyup to store like
$("#title").keyup(function(){
var articel_title = $("#title").val();
localStorage.setItem("articel_title",articel_title);
localStorage.getItem("articel_title");
});
and next time when user open the form just show the content stored
to clear use
localStorage.removeItem("articel_title");
As suggested in the comments you could store the post data in the session, for example every time a new query is posted you could add it:
$_SESSION['queries'][] = $_POST;
Then you could allow the users to go back / forward through this with some form of loop:
<ul>
<?php foreach($_SESSION['queries'] as $k => $v) : ?>
<li>Some link structure</li>
<?php endforeach; ?>
</ul>
I've got a bit of a weird problem.
I'm creating a location based web app that is using a javascript function to get a user's GPS coordinates. I have a form with a submit button, and when that submit button is clicked, the function is called (onclick='getCoords()"). The javascript then sets that values of two hidden fields (latitude and longitude) to the GPS coords.
My issue is this: PHP is 'beating' the javascript in the sense that the field values aren't being set in time, so that each value becomes a 0. I've done a bunch of testing, and this is definitely the issue. If I do something like set a seperate button to run the javascript function, the run the form everything works fine.
Any ideas on how to solve this problem?
Gists:
https://gist.github.com/2425419
https://gist.github.com/2425394
https://gist.github.com/2425391
Along the lines of what Volkner said, block submit using a submit handler (call preventDefault), then submit at the end of itsWorking. You can either call .submit() to do the submission, or use AJAX.
I think the crux of your problem is that an <input type="image"> will submit a form just as sure as <input type="submit"> will.
However, to fix this as is, add event as a parameter to both the call and declaration of getUserLocation(event).
Then edit your JavaScript as follows:
function getUserLocation(event) {
event.preventDefault(); // prevents form from submitting
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(itsWorking, notWorking);
}
else {
alert("Dang! Your browser doesn't support finding your location, use the zipcode method below.");
}
};
function itsWorking(position) {
var lat = position.coords.latitude;
var longi = position.coords.longitude;
var finalLat = Math.round(lat*1000000)/1000000
var finalLong = Math.round(longi*1000000)/1000000
$("#longi").val(finalLong);
$("#lati").val(finalLat);
document.getElementById('findoneform').submit(); // submits form since we were successful
};
But like I originally stated, it seems if you used an img tag instead of <input type="image">, that would prevent the form from sending in the first place (and maybe you did this on purpose, because you wanted to have two ways to submit the form?).
This issue happens because the page unloads (submits the form) before the geolocator's done doing its thing, but this way, we stop the form from submitting, and itsWorking() only gets called AFTER the geolocator has done its thing, so we don't submit the form until the end of itsWorking() when we've done everything we wanted to do.
I need to dynamically add form elements to an HTML form as soon as the Submit button is clicked but before the POST data is sent to a server. The new elements must be "read" from a PHP file on my server.
HISTORY:
Currently my HTML form has "hidden" fields that are submitted to another server for processing. I have no control over the other server. My problem is that anyone can edit these hidden fields.
How can I dynamically add form elements to the POST data as soon as the form is submitted?
You can try it this way:
First disable the submit by changing the submit button type from 'submit' to 'button' (or whatever)
Put in onclick on that button to a javascript routine (here i use submit_form()).
Create an empty div within your form. (here i call it with id = 'dynamic')
Using jquery, this is the submit_form().
I think you will need to give it some time for these elements to bind properly before submitting. Maybe a short time delay before $("#myForm").submit();
Here is the code for the submit_form() function:
function submit_form()
{
$("#dynamic").append("<input type='hidden' name='input1' value='whatever'>");
$("#dynamic").append("<input type='hidden' name='input2' value='whatever'>");
$("#myForm").submit();
}
You can post the data to your server and after it post again to the external server with the new elements attached.
Your job is done on server side.
See also:
php server-to-server post?
If you need any control over what is submitted to the other server, you have to do that yourself. Make the form submit to your own server, then validate it, add your data and re-submit it to the other server.
You can use the CURL extension in PHP to post data from your server.
Im looking for a way to have a form in cakephp that the user can add and remove form fields before submitting, After having a look around and asking on the cake IRC the answer seems to be to use Jquery but after hours of looking around i cannot work out how to do it.
The one example i have of this in cake i found at - http://www.mail-archive.com/cake-php#googlegroups.com/msg61061.html but after my best efforts i cannot get this code to work correctly ( i think its calling controllers / models that the doesn't list in the example)
I also found a straight jquery example (http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/) which does what i would like my form to do but i cannot work out how to use the cakephp form helper with it to get it working correctly and to get the naming correct. (obviously the $form helper is php so i cant generate anything with that after the browser has loaded).
I an new to cake and have never used jQuery and i am absolutely stumped with how to do this so if anyone has a cakephp example they have working or can point me in the right direction of what i need to complete this it would be very much appreciated.
Thanks in advance
I would take the straight jquery route, personally. I suppose you could have PHP generate the code for jquery to insert (that way you could use the form helper), but it adds complexity without gaining anything.
Since the form helper just generates html, take a look at the html you want generated. Suppose you want something to "add another field", that when clicked, will add another field in the html. Your html to be added will be something like:
<input type="text" name="data[User][field][0]" />
Now, to use jquery to insert it, I'd do something like binding the function add_field to the click event on the link.
$(document).ready( function() {
$("#link_id").click( 'add_field' );
var field_count = 1;
} );
function add_field()
{
var f = $("#div_addfield");
f.append( '<input type="text" name="data[User][field][' + field_count + ']" />' );
field_count++;
}
Of course, if a user leaves this page w/o submitting and returns, they lose their progress, but I think this is about the basics of what you're trying to accomplish.
This was my approach to remove elements:
In the view, I had this:
echo $form->input('extrapicture1uploaddeleted', array('value' => 0));
The logic I followed was that value 0 meant, not deleted yet, and value 1 meant deleted, following a boolean logic.
That was a regular input element but with CSS I used the 'display: none' property because I did not want users to see that in the form. Then what I did was that then users clicked the "Delete" button to remove an input element to upload a picture, there was a confirmation message, and when confirming, the value of the input element hidden with CSS would change from 0 to 1:
$("#deleteextrapicture1").click(
function() {
if (confirm('Do you want to delete this picture?')) {
$('#extrapicture1upload').hide();
// This is for an input element that contains a boolean value where 0 means not deleted, and 1 means deleted.
$('#DealExtrapicture1uploaddeleted').attr('value', '1');
}
// This is used so that the link does not attempt to take users to another URL when clicked.
return false;
}
);
In the controller, the condition $this->data['Deal']['extrapicture1uploaddeleted']!='1' means that extra picture 1 has not been deleted (deleting the upload button with JavaScript). $this->data['Deal']['extrapicture1uploaddeleted']=='1' means that the picture was deleted.
I tried to use an input hidden element and change its value with JavaScript the way I explained above, but I was getting a blackhole error from CakePHP Security. Apparently it was not allowing me to change the value of input elements with JavaScript and then submit the form. But when I used regular input elements (not hidden), I could change their values with JavaScript and submit the form without problems. My approach was to use regular input elements and hide them with CSS, since using input hidden elements was throwing the blackhole error when changing their values with JavaScript and then submitting the form.
Hopefully the way I did it could give some light as a possible approach to remove form fields in CakePHP using JavaScript.