So I have a really simple form on a website that's entirely AJAX based for loading its pages. The only way for this form to work would be for it to do some AJAX magic as well, so I set about doing it. I had the form tested so I knew it all worked.
Here's the javascript for my form.
The variable "fullpath" just tells me what page is loaded at the moment, all of the pages are stored in the local "pages" directory.
It serializes the form and sends it to the server, with some debugging alerts.
$(document).ready(function() {
$("#regForm").submit(function(event) {
alert($(this).serialize());
$.post("pages/" + fullpath, $(this).serialize(), function(data){
alert(data);
});
return false;
});
});
Here's the form itself
<form name="input" id="regForm">
<div class="form-field"><label>Username</label> <input type="text" name="username"/></div>
<div class="form-field"><label>Password</label> <input type="password" name="password"/></div>
<div class="form-field"><label>Confirm Password</label> <input type="password" name="password2"/></div>
<div class="form-field"><label>Screen Name</label> <input type="text" name="screenname"/></div>
<div class="form-field"><label>Email Address</label> <input type="text" name="address"/></div>
<div class="form-field"><label>Group</label> <select name="usergroup">
<option value="0">Superuser</option>
<option value="1">Admin</option>
<option value="2">Moderator</option>
<option value="3">Advmember</option>
<option value="4">Member</option>
<option value="5">Guest</option>
</select> <br />
<label>Submit: </label><input type="submit" value="Submit" />
</div>
</form>
And here's some PHP I put at the beginning of the page
print_r($_POST);
So I fill the form with some bogus info, and I press submit. All of the data is displayed with the
alert($(this).serialize());
And then the call is successful and I see the loaded form with my
alert(data);
But, where I ask to print the $_POST array in PHP, this is all I get
Array ()
So jQuery is sending the data, it's getting the page back, but for some reason the POST variables aren't going through. Anyone care to lend a hand?
This works in a Fiddle.
Are you sure that fullpath is defined globally ? I don't see any other possible source of errors in your code.
Edit: I can see the actual problem from your comments: 301 redirects don't work through POST:
If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
You need remove this redirect thing, so "pages/" + fullpath directly points to the PHP script. This could also be a problem with your server configuration.
In case of Apache, you might also want to have a look at this SO question.
I packed your snippets together in an html-file and it worked for me so the problem has to be somewhere else in your code. (source: http://pastebin.com/y4Dfsepv)
You have not specified method="post" in your form. If you do not specify, it becomes method="get" by default. So there is no values in the $_POST, you can print_R($_GET) and you will see values there.
Change the below line from:
<form name="input" id="regForm">
to:
<form name="input" id="regForm" method="post">
Update:
Updating the answer as per the comment. The "pages/" + fullpath in $.post might be pointing to the wrong page, try alerting it and check server response in firebug. Make sure it is pointing to the page you want else use the full path to the php script like below:
$.post("http://localhost/pages/" + fullpath, $(this).serialize(), function(data)
you need to chance your direct link."pages/" + fullpath. That is a problem, ajax can't recognize your link when you post
** Editing because we've learned that there is a 301 Redirect code being returned by the server **
See this: https://mdk.fr/blog/post-data-lost-on-301-moved-permanently.html
301 Redirects lose contents of the POST. So jQuery is sending it along, but the server redirects it to the right location of the script without the POST data. You need to figure out where the right location of the script is and specify that in your jquery call to avoid the redirect.
You don't have method="POST" in your form.
Related
One can figure out from a webpage the parameters used for a POST request, e.g.
How to view the address of the POST request made when an HTML button is clicked?
Is this possible for POST method to enter the url with parameters in the address bar or maybe from the debugger console?
For get request, one inserts a ? between address and parameters, e.g.
https://www.w3schools.com/action_page.php?fname=Albert&lname=Einstein.
(The analog post form calls the same script.)
Here is my javascript solution.
E.g. the form on http://vizier.u-strasbg.fr/viz-bin/VizieR
requires post.
The following command can be run in the debugger console. It manipulates one input field.
form=document.getElementsByName("form0")[0]; form.isource.value="Gaia";
form.target="_blank"; form.submit()
The url is already inherited from form.action.
Sure it is possible for POST method to pass parameters in the address.
Set up a form to POST with an action /foo?bar=bat and the server will get POST form parameters and the query string parameters.
It would be trivial to create the action dynamically so that the query string in the action contains the form parameters. For example - here the when the form is submitted the POST data is appended to the query string before the form is posted via ajax. So you get the post parameters both in the URL and in the body data.
html
<!DOCTYPE html>
<html>
<body>
<form action="/something">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
js
$("form").submit(function(e) {
e.preventDefault();
let f = $(e.currentTarget);
$.ajax({
type: "POST",
url: `${f.attr("action")}?${f.serialize()}`,
data: f.serialize(),
success: function() {
//success message maybe...
}
});
});
That said this is probably not a good idea at all.
It's not possible.
The POST params can be passed only via the request body.
You can use some kind of API client tool such as Postman, Paw or just use plain curl.
I have a registration form wherein one of the field is username which needs to be unique. So, I am checking it first in my database before insert proceeds. If username exists, I put the below line. My problem is after clicking OK, it refreshes the page and clears all the inputted data of the user. I know I can use return false but how do I put this on my echo?
else if(mysql_num_rows($result)>0)
{
echo '<script>alert("Username is not available")</script>';
}
else
{
insert goes here
<form id="appform" action="register.php" method="post" onsubmit="return validateform('appform');">
<input type="text" class="textarea1" name="stdname" size="30" onkeyup="isallnospace(this)" /> .
}
You are validating in the worst way possible. If you want to validate using both client side and server side script, please use ajax.
Uses of Ajax:
Update a web page without reloading the page
Request data from a server - after the page has loaded
Receive data from a server - after the page has loaded
Send data to a server - in the background
For more details, visit AJAX Tutorial
best way is to check with ajax before submit, but if you want you can add the $_POST values to the form when it returns to it like so
<input type="text" name="username" value="<?php if(isset($_POST['username'])){echo $_POST['username'];}?>" />
I'm not expert in PHP, and I'm trying to create public chatroom for my simple website.
I'm using SQL database to store messages.The file named chat_index.php getting all messages from database and show it to users. Also it has a simple form to send message with PHP GET method. The following is code for my form.
<form method="get" action="sendmessage.php">
<input name="msg" placeholder="Message" data-theme="a" type="text">
<button type="submit" class="ui-btn ui-corner-all">Send</button>
</form>
With above code I'm sending data to sendmessage.php file. In this file adding message to database and user redirect to chat_index.php with this code.
header("Location: chat_index.php");
exit();
After redirect page loading correctly on browser window. But URL end like this
...../sendmessage.php?msg=test_message
So if I reload the page message sending again and url getting correct like this
...../chat_index.php
How can I resolve this problem?
UPDATED
I tried with POST method. but not solved. browser showing content in chat_index.php and url ending with ../sendmessage.php
Why you are recieveing the url variables is because you are using GET. use POST instead and the variables will be gone.
example:
<form method="POST" action="sendmessage.php">
If you don't want to send data to the query string use POST instead of GET.
<form method="POST" action="sendmessage.php">
This should clearly be a POST form. Any form saving or changing anything on the server should be. Otherwise (using get) people could add messages by just following a link, which is not intended. The redirect after save is OK and good practice. Note that such redirects only work before any output is produced.
Cannot say much more by what you have posted. You should also check if your saving and redirect code is triggered correctly when message is posted.
This is what is happening, the form is being submitted from chat_index.php, so the action ends up being chat_index.php/sendmessage.php.
To solve this change the method to post as directed and change your action to /sendmessage.php
your form should look look like this
<form method="POST" action="/sendmessage.php">
....
</form
hope this help
If this is to be a simple forum site, then it would be much less complicated to not redirect at all. Just set your action attribute to "", and when someone submits the form, it will post the data back to the page. So do something like this:
<form method="post" action="">
<input name="msg" placeholder="Message" data-theme="a" type="text">
<input name="function" type="hidden" value="post_message">
<button type="submit" class="ui-btn ui-corner-all">Send</button>
</form>
Then put the php code that was in sendmessage.php into chat_index.php above the starting DOCTYPE and html tags, and delete sendmessage.php. Or alternatively, use include('sendmessage.php') in the same spot. Then when the page loads, check if $_POST['function'] == 'post_message', and if this condition is true, then execute the stuff you had in sendmessage.php. That will be much more compact, and the user will be redirected once instead of twice. Also, I don't know your file structure, but you might want to rename chat_index.php to just index.php to make it intuitive and so that people can't see inside your directory.
I am trying to submit a form using get method but I dont want the form to refresh or rather when it reloads I want to maintain the data. There seems to be lot of questions on similar lines but none that I tried helped. I am posting my code here:
<script type="text/javascript">
function formSubmit()
{
document.getElementById('form1').submit();
return false;
}
</script>
<form id = "form1" method = "GET">
<br> Query: <input name="query" id="query" type="text" size="50" value="">
<input type="button" name="search" value="Get News" onclick = "formSubmit()">
</form>
I am using python on the server side.
Thanks
The statement:
I am trying to submit a form using get method but I dont want the form to
refresh or rather when it reloads I want to maintain the data.
Implies to me that your end goal requires AJAX or at least some passing of data to the server and back. You will not be able to retain scope within Javascript over a page refresh without the use of something like cookies or passing data to/from the server. Having said that these are more akin to secondary storage mechanisms while you want to retain scope (or primary storage). To do this I would recommend AJAX.
I need to change a form so that instead of reloading the page after submitting it, it redirects the user to another page.
This is the form I'm talking about:
<form class="questionform" name="questionform-0" id="questionform-0">
<textarea class="question-box" cols="12" rows="5" id="question-box-' . $questionformid . '" name="title" type="text" maxlength="200" size="28"></textarea>
<input type="text" class="ubicacion" value="" name="question">
<input type="button" name="ask" value="Publicar" onclick="askquestion('questionform-0'); window.location.reload(true);">
I want to remove window.location.reload and change it for something that redirects users to the page their comment will appear.
The problem is that it's not simply a static. So I have no idea how to do it. The URL I want to send users to is:
www.chusmix.com/s?=(content of the second field)
How do I do it? Anyway thanks for any info or whatever that points me on the right direction. Thanks
There is no need to use javascript for this purpose. You only need to set the action attribute of the form tag. It tells where the form information will be sent. So in your case it will be:
<form action="http://www.chusmix.com/s">
Also if you want to send the variables through the URL like: http://www.chusmix.com/s?variable=someValue
You need to set the method attribute as get so it will look like this:
<form action="http://www.chusmix.com/s" method="get">
If you don't want the data sent to be visible set the method to post, note that there are different advantages for each method so i recommend you read more about this if this form is an vital part of your webpage.
The variable names that appear in the url http://domain.com?**variable**= will depend on the inputs name <input type="text" name="**variable**" />
For more information on how forms work you can go to:
http://www.w3schools.com/TAGS/tag_form.asp
http://www.tizag.com/phpT/forms.php
You can ad an action:
<form action="redirection_url.php" method="POST" class="questionform" name="questionform-0" id="questionform-0">
I think you can use both absolute and relative url. Also note that I've added
method="POST" - which defines how the data from the form will be sent, as you already send some data with GET method (that's the stuff after ? in your url) - so this should work pretty well.
If you cannot use the action attribute in the <form> tag, you may redirect the user using window.location (you will probably want to do this inside the askquestion method, not in the onclick attribute).
window.location = "http://www.chusmix.com/s?=" + inputValue;