I have some problems when trying to pass some parameters to PHP via JS.
Here's the situation:
HTML:
<form id="numbtns" method="post" action="imphp.php">
<button id="1" onClick="pass(this.id)">1</button>
<button id="2" onClick="pass(this.id)">2</button>
<button id="3" onClick="pass(this.id)">3</button>
<button id="confirm" onClick="save()">submit</button>
</form>
JS:
pass(clicked_id) {
var btn = document.getElementById(clicked_id);
**// I have no idea what to do next to give the ids to the php file.**
}
save() {
**// I want function save() to collect the parameters from function pass(), and pass them to 'imphp.php' when submit button is clicked. I'm stuck here.**
}
PHP:
// connection part, let's skip it.
...
$num = $_POST['num'];
$query = sprintf("SELECT id, num FROM tb WHERE num = $num");
I know maybe it's a quick and stupid question for u, but I cannot figure it out for hours. So... could anyone help me out, I'd be very appreciate that.
Thx in advance.
I don't think you need Javascript for this. All you want to do is post the form to the PHP page, right?
<form id="numbtns" method="post" action="imphp.php">
<input type="radio" name="num" value="1" /> 1<br />
<input type="radio" name="num" value="2" /> 2<br />
<input type="radio" name="num" value="3" /> 3<br />
<input type="submit" value="Save" />
</form>
Using buttons made no sense to me at all, so I changed them to radio buttons. The user will check one, then click the Save button to submit the form.
You need to use AJAX... i would recommend simplifying the process with a javascript library like jQuery... here is a tutorial using jQuery / AJAX / PHP: http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
This is a very frequently asked question in one of several forms, as you can see by looking under the Related heading to the right on this page.
I see this a lot and there seems to be a fundamental flaw in many people's understanding of how PHP and Javascript work, so I wanted to throw this out there.
PHP runs on the server, executing the code in the .php page and modules there, and produces output which is sent to the browser. PHP is now done. Stopped. Fini. You PHP code is no longer running.
The web browser receives the output, builds the DOM tree, and starts rendering the HTML as a page and executing the Javascript. The Javascript can't pass parameters to the PHP because the PHP is no longer running. It has terminated execution. Kaput. In addition, the Javascript is running in the browser, on the client machine, while the PHP runs on the server.
What you can do is invoke some new PHP (or re-invoke the same PHP code to do something else) and that is usually done be making an AJAX call from Javascript, as #Jeffery A Wooden suggests in his answer.
HTML, though I'd suggest changing the button elements to <input type="button" ...> elements
<form id="numbtns" method="post" action="imphp.php">
<input type="hidden" name="buttonID" value="1" />
<input type="button" onClick="pass(this)" value="1" />
<input type="button" onClick="pass(this)" value="2" />
<input type="button" onClick="pass(this)" value="2" />
<input type="submit" id="confirm" value="Submit" />
</form>
Javascript:
function pass(button) {
document.getElementById("buttonId").value = button.value;
}
Related
How can I differentiate two separate actions for my submit buttons in one form, whereas one SAVES data into database (as is), and other submits form as a valid request, >>but<< according to HTML5 native validation (I use "required" attributes in HTML form)?
My form has 66 fields and I don't want to validate them all in PHP AFTER submission (as it's too cumbersome and time consuming), or validate them all in JS BEFORE submission (as I am not that agile in JS, as in PHP), so I use "required" and "type" attributes in HTML5, which is very convenient and quite versatile way of validation (besides older browsers).
However I cannot find a easy way to bypass the "required" attribute, when using save button, but not using "Send for submission" button. Can you help suggest a solution? I guess the prefered way is some JS/jQuery way, as I cannot determine which button would be used before hitting the button (so that I can make a field required or not).
Sample code:
<form>
A: <input type="text" name="A" required />
B: <input type="text" name="B" required />
C: <input type="text" name="C" />
<input type="submit" name="save" value="Save"> <!--do not require anything-->
<input type="submit" name="send" value="Send for submission"> <!-- require everything-->
</form>
Of course my form is huge, as it has 66 fields, so best solutions here are possibly general and versatile.
Something like this might get you started:
$('#sub1').click(function() {
$('[name=A]').removeAttr('required');
$('[name=B]').removeAttr('required');
$('form').append('<input type="hidden" name="save" />');
$('form').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
A: <input type="text" name="A" required /><br>
B: <input type="text" name="B" required /><br>
C: <input type="text" name="C" /><br>
<input id="sub1" type="button" name="save" value="Save">
<!--do not require anything-->
<input type="submit" name="send" value="Send for submission">
<!-- require everything-->
</form>
I've eventually come up with something like this.
HTML:
<input type="submit" name="save" value="Save" onClick="removeRequired(this.form)">
JS (using jQuery):
function removeRequired(form){
$.each(form, function(key, value) {
if ( value.hasAttribute("required")){
value.removeAttribute("required");
}
});
}
This is tested and working. It has this nice property, that I can keep the function elsewhere in files, to not clutch the php/html that is executing it.
Only improvement I'd like (and probably other would be interested in) would be to eliminate jQuery as it's only used for browsing each input element in form, which seems easy enough for pure JS. However I could not find an easy way, and run out of time and used above with jQuery. Thanks
To remove the required attribute from all tags before submitting, modify the code to:
$('#sub1').click(function() {
$('[required]').removeAttr('required');
$('form').append('<input type="hidden" name="save" />').submit();
});
jsFiddle Demo to show it works
Note this answer also demonstrates chaining the jQuery methods: $(tag).append().submit()
I've currently got the following set up:
I've got a form that submits an image, the action on that form calls to a new page
"test.php"
On test.php a function is called via a server request check
if ($_SERVER['REQUEST_METHOD'] == 'POST')
The problem with this current set up is that I have to load the page test.php. I want the user to stay on the same page after submitting the form.
I'm gessing that to achieve this I have to use some sort of Ajax call. But I'm not quite sure where to start. If I make an ajax call to the page test.php, will it still proces the server request method?
The form sends some coordinates, and the file test.php crops an image via these coordinates, and saves it to the server.
<form action="/test.php" method="post" onsubmit="return checkCoords();">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="submit" value="Crop Image" class="btn btn-large btn-inverse" />
</form>
The coordinates are generated via another javascript function.
Any help or push in the right direction would help me out a lot.
Kind regards,
Use jQuery as it will make your life a lot easier.
Then, you can send a request like this:
$.post('ajax/test.php', function(response) {
$('#result').html(response);
});
This will send a POST request to ajax/test.php, then put the response output in a DIV with ID result.
The XMLHttpRequest object is used to exchange data with a server
But you can use ajax with jQuery to upload your images.
here is nice example :
Ajax Image Upload
Demo :
Ajax Image Upload Demo
For my php file, I need to grab the unique form name.
The php file is executed when a user clicks the submit button. However, there are multiple submit button each with the same id, but they all have unique names. I need the name when they click on the submit button.
you dont want elements in html with the same id - bad practice in general. Your page will likely load normally but an html validator will notice it as an error.
html validator: http://validator.w3.org/
without seeing your code, its difficult to give you a definitive answer. if you have miltuple forms you can use hidden inputs. e.g.
<input type="hidden" name="form_name" />
Otherwise you can use javascript to put data in the form when the button is clicked. example javascript using jquery
html:
<form id="formid" >
<button type="button" id="someid" onclick="submitForm('btn1')" />
<button type="button" id="someid" onclick="submitForm('btn2')" />
<input type="hidden" id="btnsubmitid" value="" />
</form>
js:
function submitForm(btnID){
$("#btnsubmitid").val(btnID);
$("#formid").submit();
}
1 way is to put a hidden input inside of your form.
<input type="hidden" name="formName" value="[name of form]" />
then in your php, you can get it using
$form-name = $_POST['formName'];
pretty sure there are other ways, but this came to mind first.
I don't know if this is possible, what I want is just to get the html or the plain-text from the result of a form sent to a external page.
In this case, I have a form that send the variables to a external server and the result goes to the iframe, how I retrieve the html or text from the iframe? This is the correct way?
I'm trying to do this just to simplify a repetitive process here on my agency...
<form name="form" method="post" action="https://www.externalpage.com" target="iframe">
<input type="hidden" name="a" value="0000"/>
<input type="hidden" name="b" value="0001" />
<input type="hidden" name="c" value="0002" />
<p>
<input type="submit" id="button" value="Submit" />
</p>
</form>
<iframe name="iframe" scrollbars="no"></iframe>
Assuming from the tags you are using jquery
var myresult = $('iframe[name="iframe"]').html();
Should do the work.
//edit: just noticed the iframe is from an external domain, it might be subject to the same origin policy, in this case the above code might not work
I am currently working no a 6-page form using jQuery Mobile and are having some problems handling my form results. What I want to do is get all data sent to a .php script so the .php script can print and/or save to my database.
I've often had problems with everchanging variable names as they seem like a pain to manipulate. Perhaps someone know a better way to do this as I am pretty new to jQuery and Ajax. I have attempted to explain how my thought process is underneath.
Has anyone done anything similar that can show me in the right direction? I am pretty much in the dark here as what to google. Perhaps a link to something relevant? I would post any code if I had some, but I haven't really found anything useful to try yet. My form is generated through a .php function however, but saving the results is sort of the opposite of that.
Demands:
- No page reload
- Having the possibility to use mysql_real_escape_string before saving to db
- Submit method: POST
- Target db table needs question_id, option_id, user_id, date and other (for possible comments)
HTML pseudo code (generated by .PHP) - Without spans/fieldsets/labels etc
<form action="<!-- What to put here?-->" method="POST" id="questions">
<input type="radio" name="1[]" value="1"/>
<input type="radio" name="1[]" value="2"/>
<input type="radio" name="1[]" value="3"/>
<input type="checkbox" name="2[]" value="1"/>
<input type="checkbox" name="2[]" value="2"/>
<input type="checkbox" name="2[]" value="3"/>
<input type="checkbox" name="2[]" value="4"/>
<textarea name="2[]" placeholder="Type here..."></textarea>
<!-- ... -->
<a type="submit" href="#results" onclick="formSubmit()" data-role="button">Submit</a>
</form>
JavaScript Code:
function formSubmit()
{
document.getElementById("questions").submit();
}
Desired output in .php:
$answers = ("questionid" => "answerid", "questionid" => "answerid", "questionid => "answertext") for all checked checkboxes/radiobuttons and textfields != "".
Edit:
I've found out I probably need an id for my form so it shall hereby be named as questions.
The best way to do it would perhaps be by calling the .php script with an onclick on the submit button.
It sounds like you need help doing a simple AJAX submission but maybe there's some hidden question in here I've missed but I'll answer anyway.
So what you want is to look at this tutorial here http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
You set your URL to AJAX submit to a handler PHP script which will then do what you want with the data and return a status, success/failed etc.
Hope that helps.