PHP redirect with header - javascript

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.

Related

How to not display URI variable on redirect?

I have the following form which is used to redirect the user to search a particular date.
<form action="/datesearch/" method="get" id="goto_date_form" style="display:none;">
<input name="dt" type="text" />
<input type="hidden" name="csrfmiddlewaretoken" value="[my csrf token value]">
</form>
When this form is called with $('#goto_date_form').submit();, it does redirect the page, but it displays both the value of dt and the value of csrfmiddlewaretoken as URI variables.
i.e. when searching for 2016-07-06 it redirects to
`http://localhost:8000/datesearch/?dt=2016-07-06&csrfmiddlewaretoken=[my csrf token value]`
How can I get it to stop displaying the csrf token?
Simply change method="get" to method="post" (and also back end too)
When you use GET in a form, all the data in the form is placed in the URI. If you change your form to use POST instead, the data will be put in the request body - not visible in the URI (but still visible to the user if the user decides to view the Request details).
NOTE if you change from GET to POST, you might have to make some changes in your server side code as well, depending on the method you are using to fetch the data.
Use method="post" in form tag to prevent data passing in url

How to prevent the page from refreshing after validation?

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'];}?>" />

How to change iFrame results to JavaScript alert box?

I have access to a url runs a script to clear a users state.
Id like to produce a script that will run on a webpage, to do this.
The following script works but in Firefox its annoying for people to have to disable mixed content each time they come to the page:
<SCRIPT LANGUAGE="JavaScript">
function go(loc,loc2){
document.getElementById('userstate').src = loc +
document.getElementById('username').value + loc2;
}
</script>
<form onSubmit="go('http://mysiteurlomitted.com/userstate/?userId=','&app=cc'); return false;"/>
Username: <input type="text" id="username">
<input type="submit" value="Clear User State">
</form>
<iframe id="userstate" src="about:blank" width="470" height="30" frameborder="1" scrolling="no"></iframe>
The resulting URL produces a simple text string, and has no HTML on the results page, so I feel it should be pretty easy to read this URL as a file, and load the results into an alert box. This would avoid the iframe method, and get out of the mixed content situation. It would run without anyone needing to change anything. But I cannot figure out how to get this to work. I feel like FileReader() should be a good way to do it, but the URL has parameters... so the reader doesn't know what file type it is. Its just failing. There has to be an easier way to do this.
You shouldn't need any javascript for this kind of thing. Just add a name attribute to the username input, and that value will get passed along in the query string as "&username=Name". so:
<form action="/userstate?app=cc">
Username: <input type="text" id="username" name="username" />
<input type="submit" value="Clear User State" />
</form>
That would submit the form to "http://samedomain.wut/userstate?app=cc&username=", which would be available on the server side in the usual post data source.
There are other, better ways of doing this, but I don't know your setup. You should look into server-side management of cookies/session; the user shouldn't have to input anything except to log in initially.
Edit:
If you want to use this as an administration tool, you can do two things: use ajax (XMLHttpRequest or $.ajax from Jquery), or make your endpoint redirect back to (or serve) the form. You could have the form submit to its own url and in your server side scripting process the data, then output the html for the form again. Not a great pattern for actual applications, but it should work in this situation.

jQuery not sending POST data

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.

Make form redirect users after posting

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;

Categories