i am using the following jquery to post comments to user_submit.php
var submit = document.getElementById("submit_js");
var comment = document.getElementById("comment");
$("#submit").bind('click', function(){
$.post("user_submit.php", {
comment: $("#comment").text()
});
});
the user_submit.php listens like:
$comment = htmlspecialchars($_POST["comment"]);
i can see in the Firebug console that there is no POST happening. only a single GET that i use for a different function (can this be the culprit?)
Assuming:
<input type="text" id="comment">
<input type="button" id="submit_js">
you want:
$(function() {
$("#submit_js").click(function() {
$.post("user_submit.php", {
comment: $("#comment").val()
});
});
});
PHP:
<?php
$comment = $_POST['comment'];
//...
echo htmlspecialchars($comment); // nothing catches this currently
?>
You also seem to be confusing "submit" and "submit_js" in your code. I'd advise against mixing Javascript and jQuery code unnecessarily too (the "getElementById()" business). You should familiarize yourself with jQuery selectors. For example:
$("#submit_js")
will create a jQuery object with all the elements (which should only be zero or one elements) with the ID of submit_js.
Remember that you're posting via AJAX, so even if you're echoing back the field value, it won't show on your screen unless you're listening for it in the $.post callback.
To check what the problem may be, submit the form normally without jQuery. If your PHP script is echoing back the field value, then the PHP script is working - check your JavaScript. If the you're getting blank, or empty array when using print_r(), then make sure the field name in your form is the same as what you're using in the PHP script.
Don't want you to have to rewrite your code, but here's what I recommend to do.
<form class="comments" method="post" action="user_submit.php">
<input type="text" name="comment" />
<input type="submit" value="Submit" />
</form>
JavaScript:
$('.comments').submit(function() {
var $form = $(this);
$.post(
$form.attr('action'),
$form.serialize(),
function(data, status) {
console.log(data);
}
);
return false;
}
This will submit your form to the PHP script. In the callback function, "data" is the returned data from the PHP script. So if you echo the field value back, the Firebug console will display the value.
In the event the user's browser has JavaScript disabled, the form will still submit properly. Of course your PHP script would have to check if the form was submitted via AJAX so that it can process properly depending on the request method. An easy way to test is to check for the X-Requested-With header. If it was sent via AJAX, the value would be XMLHttpRequest.
Related
Ok, this is less of a question than it is just for my information (because I can think of about 4 different work arounds that will make it work. But I have a form (nothing too special) but the submit button has a specific value associated with it.
<input type='submit' name='submitDocUpdate' value='Save'/>
And when the form gets submitted I check for that name.
if(isset($_POST['submitDocUpdate'])){ //do stuff
However, there is one time when I'm trying to submit the form via Javascript, rather than the submit button.
document.getElementById("myForm").submit();
Which is working fine, except 1 problem. When I look at the $_POST values that are submitted via the javascript method, it is not including the submitDocUpdate. I get all the other values of the form, but not the submit button value.
Like I said, I can think of a few ways to work around it (using a hidden variable, check isset on another form variable, etc) but I'm just wondering if this is the correct behavior of submit() because it seems less-intuitive to me. Thanks in advance.
Yes, that is the correct behavior of HTMLFormElement.submit()
The reason your submit button value isn't sent is because HTML forms are designed so that they send the value of the submit button that was clicked (or otherwise activated). This allows for multiple submit buttons per form, such as a scenario where you'd want both "Preview" and a "Save" action.
Since you are programmatically submitting the form, there is no explicit user action on an individual submit button so nothing is sent.
Using a version of jQuery 1.0 or greater:
$('input[type="submit"]').click();
I actually was working through the same problem when I stumbled upon this post. click() without any arguments fires a click event on whatever elements you select: http://api.jquery.com/click/
Why not use the following instead?
<input type="hidden" name="submitDocUpdate" value="Save" />
Understanding the behavior is good, but here's an answer with some code that solved my problem in jquery and php, that others could adapt. In reality this is stripped out of a more complex system that shows a bootstrap modal confirm when clicking the delete button.
TL;DR Have an input dressed up like a button. Upon click change it to a hidden input.
html
<input
id="delete"
name="delete"
type="button"
class="btn btn-danger"
data-confirm="Are you sure you want to delete?"
value="Delete"></input>
jquery
$('#delete').click(function(ev) {
button.attr('type', 'hidden');
$('#form1').submit();
return false;
});
php
if(isset($_POST["delete"])){
$result = $foo->Delete();
}
The submit button value is submitted when the user clicks the button. Calling form.submit() is not clicking the button. You may have multiple submit buttons, and the form.submit() function has no way of knowing which one you want to send to the server.
Here is another solution, with swal confirmation. I use data-* attribute to control form should be send after button click:
<button type="submit" id="someActionBtn" name="formAction" data-confirmed="false" value="formActionValue">Some label</button>
$("#someActionBtn").on('click', function(e){
if($("#someActionBtn").data("confirmed") == false){
e.preventDefault();
swal({
title: "Some title",
html: "Wanna do this?",
type: "info",
showCancelButton: true
}).then(function (isConfirm) {
if (isConfirm.value) {
$("#someActionBtn").data("confirmed", true);
$("#someActionBtn").click();
}
});
}
});
i know this question is old but i think i have something to add... i went through the same problem and i think i found a simple, light and fast solution that i want to share with you
<form onsubmit='realSubmit(this);return false;'>
<input name='newName'/>
<button value='newFile'/>
<button value='newDir'/>
</form>
<script>
function getResponse(msg){
alert(msg);
}
function realSubmit(myForm){
var data = new FormData(myForm);
data.append('fsCmd', document.activeElement.value);
var xhr = new XMLHttpRequest();
xhr.onload=function(){getResponse(this.responseText);};
xhr.open('POST', 'create.php');
// maybe send() detects urlencoded strings and setRequestHeader() could be omitted
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(new URLSearchParams(data));
// will send some post like "newName=myFile&fsCmd=newFile"
}
</script>
summarizing...
the functions in onsubmit form event are triggered before the actual form submission, so if your function submits the form early, then next you must return false to avoid the form be submitted again when back
in a form, you can have many <input> or <button> of type="submit" with different name/value pairs (even same name)... which is used to submit the form (i.e. clicked) is which will be included in submission
as forms submitted throught AJAX are actually sent after a function and not after clicking a submit button directly, they are not included in the form because i think if you have many buttons the form doesn't know which to include, and including a not pressed button doesn't make sense... so for ajax you have to include clicked submit button another way
with post method, send() can take a body as urlencoded string, key/value array, FormData or other "BodyInit" instance object, you can copy the actual form data with new FormData(myForm)
FormData objects are manipulable, i used this to include the "submit" button used to send the form (i.e. the last focused element)
send() encodes FormData objects as "multipart/form-data" (chunked), there was nothing i could do to convert to urlencode format... the only way i found without write a function to iterate formdata and fill a string, is to convert again to URLSearchParams with new URLSearchParams(myFormData), they are also "BodyInit" objects but return encoded as "application/x-www-form-urlencoded"
references:
https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
https://developer.mozilla.org/en-US/docs/Web/API/FormData
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit#usage_notes (proves that form.submit() does not emulate a submit button click)
Although the acepted answer is technicaly right. There is a way to carry the value you'd like to assign. In fact when the from is submited to the server the value of the submit button is associated to the name you gave the submit button. That's how Marcin trick is working and there is multiple way you can achive that depending what you use. Ex. in jQuery you could pass
data: {
submitDocUpdate = "MyValue"
}
in MVC I would use:
#using (Html.BeginForm("ExternalLogin", "Account", new { submitDocUpdate = "MyValue" }))
This is actually how I complied with steam requirement of using thier own image as login link using oAuth:
#using (Html.BeginForm("ExternalLogin", "Account", new { provider = "Steam" }, FormMethod.Post, new { id = "steamLogin" }))
{
<a id="loginLink" class="steam-login-button" href="javascript:document.getElementById('steamLogin').submit()"><img alt="Sign in through Steam" src="https://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_01.png"/></a>
}
Here is an idea that works fine in all browsers without any external library.
HTML Code
<form id="form1" method="post" >
...........Form elements...............
<input type='button' value='Save' onclick="manualSubmission('form1', 'name_of_button', 'value_of_button')" />
</form>
Java Script
Put this code just before closing of body tag
<script type="text/javascript">
function manualSubmission(f1, n1, v1){
var form_f = document.getElementById(f1);
var fld_n = document.createElement("input");
fld_n.setAttribute("type", "hidden");
fld_n.setAttribute("name", n1);
fld_n.setAttribute("value", v1);
form_f.appendChild(fld_n);
form_f.submit();
}
</script>
PHP Code
<?php if(isset($_POST['name_of_button'])){
// Do what you want to do.
}
?>
Note: Please do not name the button "submit" as it may cause browser incompatibility.
I need to make a button, and when I click on it I'll do the same if I had such form:
<form action="myscript.php" method="post">
<input type="hidden" name="items[]" value="..." />
<input type="submit">
</form>
and clicked submit. On the PHP side I use proper headers and make the force download.
The reason why I can't use a form here, because I have a lot of parameters, and it's not that easy to use a form tag in my HTML markup. Moreover, these parameters are dynamically made, so...
But if I use just $.ajax of course It won't work, I'll just get php response in this ajax request, but the browser won't start downloading the file
Any suggestions?
Just redirect to the download page, if it has the correct headers on that page, it wont change what page they're on, just download the file with a prompt.
Simple answer: Don't use GET. Use POST instead!
<script>
var info = ""; // Somewhere for the response to go
var obj = $.post(
raw_url,
{ var1:value1, var2:value2 },
function(data) { info = data; } );
</script>
On the PHP side, you'll receive any array based data AS an array (thus if value2 were a javascript array, you'll receive it in PHP as an array as well.)
I use Facebook JavaScript SDK.
I want to know how to post the Javascript variables to another page with GET or POST or any other way.
For example i have:
userInfo = document.getElementById('user-info');
How to post it to new page ?
location.href="http://www.walla.com/?info=" + info.id;
Not working
Better use ajax for this ..
here is an example.
<script type="text/javascript">
$(document).ready(function() {
$('#submit-btn').click(function() {
$.ajax({
type:'POST', //POST or GET depending if you want to use _GET or _POST in php
url:'your-page.php', //Effectively the form action, where it goes to.
data:$('#txtName').val(), //The data to send to the page (Also look up form serialise)
success:function(e) {
// On success this fill fire, depends on the return you will use in your page.
}
});
return false;
});
});
</script>
<form>
<input type="text" id="txtName" />
<input type="submit" id="submit-btn" value="Send" />
</form>
Hope it works for u.
That looks okay. You should be able to obtain info.id via $_GET['info'] from PHP.
However, that's assuming userInfo is a simple string.
If it isn't, you may have to convert it to string first. One way to do that is through JSON as JSON is decodable at PHP's side using json_decode().
I am new to AJAX
I want to do something like
$query="select name from login_master where name=txtName.value();";
//txtName is a name of textbox.
But without submitting the form.
can i do this with ajax?
In AJAX you will make a call to whatever PHP page it is that contains this query. Your php page will carry out the query and echo out the results in a form your Javascript can understand, possibly either HTML or JSON.
In the success handler of your ajax call you can then handle the returned data.
Also on the server side be careful because anything input by the user can be potentially hazardous. Use prepared statements with mysqli or PDO.
Something like this should work:
<script type="text/javascript">
$(document).ready(function() {
$('#submit-btn').click(function() {
$.ajax({
type:'POST', //POST or GET depending if you want to use _GET or _POST in php
url:'your-page.php', //Effectively the form action, where it goes to.
data:$('#txtName').val(), //The data to send to the page (Also look up form serialise)
success:function(e) {
// On success this fill fire, depends on the return you will use in your page.
}
});
return false;
});
});
</script>
<form>
<input type="text" id="txtName" />
<input type="submit" id="submit-btn" value="Send" />
</form>
Then in your your-page.php or whatever you will call it you will pickup the $_POST['txtName'] and query your database.
I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/