Submit PHP form without reloading or AJAX - javascript

I know this question must've been asked various times here but I have not found a solution from all links I could search for. I don't understand how to do this.
I have a form, with 2 textboxes and 1 submit button. The form name is 'form1'
here is what I was using till now:
<script type="text/javascript">
$("#form1").submit(function() {
$.ajax({
type: 'GET',
url: 'response.php',
data: {1: $("#txt1").val(), 2: $("#txt2").val()},
success: function (data) {
$("#update").prepend(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
</script>
'update' is a table.
I am adding a new row to it after the data is parsed in response.php.
Now, the problem is, using AJAX for this is not at all secure. Users can use plugins such as 'Tamper Data' for firefox to mess with these and send any data they want regardless of what they entered. Thus, making me vulnerable to XSS and CSRF attacks.
So I tried a different approach, I set the form's action to response.php.
Now, there are 2 problems in doing that:
The page refreshes.
How can I make the table row prepend via PHP that too in another document? Earlier I was just echoing it and then AJAX prepended the data for me.

To make things clear: There is no other way than "refreshing" or AJAX.
You should stick to AJAX. To amend your security concerns, you can add a token to the form, which is only valid for this user (saved in his session on login). Therefore noone else can send data in his name and thus eliminiating the risk for XSS and CSRF.
You need to transmit that token in your AJAX request and check it in response.php.
Validation in response.php:
Escape everything which goes into your database. mysql_real_escape_string or PDO will help you with that.
When you output userdata somewhere in your page use htmlspecialchars().
You might also consider strip_tags() before saving or printing any values.

Since you're submitting a form request, you should be using POST instead.
Secondly, ajax post is no less secure than a regular post so you should not be worried.
Third, if you're worrying about someone sniffing your network. Have your website use HTTPs instead.
To prevent XSS attacks, you should be modifying your data before printing it to the end user using something like htmlentities.
To prevent sql injections, I would suggest using PDO or atleast escape your userinput before.

Removing AJAX isn't the solution to solve XSRF and XSS vulnerabilities. Instead you should use form tokens, two step forms, etc to prevent this.
Using session tokens isn't very hard - you just have to generate a token for each form, save them on the server and compare the send token with them on the server. To be really secure, you should generate a token for each form, but you could also use a token for each session.
Btw. XSS isn't a problem of ajax or some form posts - it's a problem of not escaping malificious output. htmlentities and stuff like this, should help you.

Related

pass data using value of div (security)

is it safe to send the data(text) of div to the server via ajax? or get the url of an <a> tag and use it?
ex.
<div id="get-value">Some Value</div>
<button id="send" data-url="process.php"></button>
javascipt
$('#send').click(function() {
$.ajax({
url: this.dataset.url,
dataType: 'json',
type: 'post',
data: {
value: $('#get-value').text(),
}
});
});
What if I edit the text in the div and the data-url of button in the developer tools and click the button after?
It is safe to do this.
When working with Javascript and AJAX, you are subject to this inherent problem: it can always be modified. The best way to minimize the issue is to make sure that no secure operations occur on the client, and instead let the Javascript do the display and submit.
In this case, you can leave it as it is. As long as you are sanitizing the user input on the server side then you are doing most all you can (aside from obfuscation, which is rarely a good idea in Javascript).
In my opinion, and I'm no security expert but this is how I deal with things, you should always validate and sanitise user input on the server side. If a user can submit data, they can tamper with it, so it is not safe until you have cleaned it up and made sure it is safe on the server.
I don't know what you are using for your server side, but most frameworks these days have built in ways of sanitising user input before committing it to, say, a database. I would look into the documentation of your server side language/framework to find out the best way to handle incoming user input safely.
is it safe to send the data(text) of div to the server via ajax? or get the url of an tag and use it?
Yes.
Note, however, that since it is coming from the browser, it is user input and should be treated as such. You can't assume that data you gave to the browser with the expectation that it would be sent back to the server isn't going to be tampered with.
Don't use such for things like authorisation. You can't trust the browser to tell you if the user is an admin or not. You need to have proper authentication and then do the authorization for the user on the server.
Don't use it without suitable escaping for the purpose. e.g. Don't stick it into SQL without using a bound argument. Don't stick it in HTML without converting special characters to entities (or using a HTML parser with a white list filter to clean out XSS risks).

Can I validate only with jQuery or do I need PHP? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I understand the difference between the two languages, but when it comes to form validation. Is jQuery enough?
Can I validate my form in jQuery/JavaScript and then do an AJAX call to send the completed form to an email address? Is it even possible to send form data to an email address using JavaScript?
Or is it somewhat safer to do everything in PHP?
I ask this because using PHP is what I'm used to, however, I've recently started working with more advanced JavaScript and jQuery.
you should do both of these validations
- jQuery for user friendly response to what the user is missing or entered wrong
- asap feedback from the client side.
you can't trust the client, so you always have to do server-side data checks
to make sure everything is correctly entered.
It is best to pass the data over and check it again on the server-side then complete your action (email, database inserts, outputs)
You can make a more user friendly UI in JQuery. However, you should also do the validations in PHP (server-side) because if you do not someone could bypass the validations by turning off JavaScript. There are also other ways to get around this, but as a general rule never trust a client to do validation.
In other words client-side validation (JQuery/JavaScript) cannot replace server-side validations. JQuery is used more for user-experience.
Since you are worried about AJAX here is a code example:
PHP
//if there is an error:
header('HTTP/1.1 500 Internal Server Error');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
//if there is not an error:
header('Content-Type: application/json');
echo json_encode(array("message"=>"All good here!"));
JQuery
//this is on submit, but you could do other events
$(document).ready(function(){
$("form").submit(function(e)
{
e.preventDefault();
$.ajax({
type: "post",
url: "path/to/your.php",
data: $('form').serialize(),
success: function(data)
{
alert(data.message);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
dataType: "json"});
}});
});
Note: I did not test the code above, but it may give you an idea of what to do.
Regardless of if you decide to do any client-side validation, you'll always want to do server-side (PHP) validation as well because you should never ever trust user supplied input.
As for including jQuery/JavaScript validation as well: that's more of a stylistic or user experience question. If want your users to have instant feedback for certain types of errors (such as missing or invalid data) then you should absolutely include some client-side validation.
It's best if you use both: Use jQuery to test the input while the user is filling out the form or when the user presses the submit-button. That's enough in most cases, but since the user could have JavaScript turned off in their browser, you should check the sent in data with PHP as well. This is especially important if the data can mess something up on your side, for example if the data is saved into a database or something, then SQL injections could potentially make a huge mess and put your security at risk...
If you check the data with PHP, then the first jQuery part isn't absolutely necessary, but it's nice if the user gets a feedback about whether they filled the form out correctly without having to reload the page first...
And no, I don't think it's possible to send the form data to an email address using only JavaScript.
It is vital that you let the server do any validation as, at the end of the day, IT is the mechanism that communicates with your database, file storage area, email process and executing any commands - I.e. anything of any consequence!
JavaScript validation is quick and useful but, as others have said, it's easily bypassed by simply turning it off! Or what if your visitor uses a browser that doesn't have JavaScript?
jQuery/JavaScript are client side scripting languages, it is very easy to bypass you should use combination of both client side and server side validation for reliable inputs. In the we need SMTP server in order to send an email that will be our server side so you have to use PHP for email your form information to an desired email destination.
I hope it's enough for your understanding :)
well.. Starting, aren't languages ​​that can opt for one or the other.
Javascript / jquery is a client-side language and PHP is a server-side language. What is this? Javascript runs on the client browser, is subject to its limitations and can be changed easily by the end user and have behaviors we did not want. Have PHP runs on the server side, where the user has no control. It is safer and, by rule, one should not ignore the PHP (or other server-side language) to validate forms. Thus, we are sure that our code does not have security flaws.
However, it is very good to use both ... jquery / JS allow you to check in real time, saving the user from submitting the form and then receive an error message ... In JS, it saves this work. And if the user "breaks" that protection hardly pass the validation server-side.
In short, PHP always ... To enhance the experience (and highly recommend), also use JS :)

How to authenticate an AJAX request to a PHP file?

On my website I have a registration page which makes an AJAX request to check if a username is available after it has been entered. This file is called check.php and is in the same directory as the registration.php file. When data is posted to check.php it will perform a query at a MySQL database and return how many users it found with that username.
If anybody were to post data to the check.php file they would see the result, too. I need to stop this somehow, I've read on a few answers I need to "authenticate" each request. This is probably a very large topic although I'm not too sure what to search for to find more about it. Is authenticating each request a good way to stop unnecessary username checks? If so I would really appreciate it if anyone could point me in the right direction as to how to do this.
A solution is to generate a unique token in session, and put it in all pages that will contain a form. Post this token on each AJAX request you make.
It is called CSRF protection, Cross-Site Request Forgery.
You can add a protection layer checking the user referer in HTTP headers.
Answer for common case: no - you can't prevent this, since AJAX is just an HTTP-request. It can be sent no matter how you'll protect your server. So if the point is - to protect from 'evil hackers' - there's no way to do this. The correct though is to check/validate anything on server side.
But is it's about only basic check, you can read
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest')
-but be aware - this is also a data, which came from client i.e. it can't be trusted (actually, it's just HTTP-request header, nothing more)
I think you can create a Session variable when the user logs in your aplication and check if this variable has the correct value whe you post something to your 'check.php' file to check if your user is previous authenticate
Missing a lot of info but conceptually I am not sure you are worrying about a real risk. Bottom line is that people can use your form to check if emails exist so it's logical they can use check.php as well. Would be overkill to try and prevent that.
I have one think - you can generate some unique token, store it on SESSION before show the page. Than on each checking you must to add this token to request. check.php must regenerate token and return it new.
But each request can emulate and it not protect you from people, which want to know results of check.php. Nothing protect...
Also you can make mechanism for analyzing ip request for checking

collecting output and form submission on a different page?

I'm looking for a way to gather the output(in text) on a webpage after a form submission.
Is there a way to maybe see the http response of a form submission in Javscript?
Otherwise, I would like to know if there's a nice way to somehow, say parse or collect outputs of multiple webpage(same page) form submissions. I know it's not possible (or too complicated) to save a file with the output in Firefox using Javascript.
So an option for me is to set up another webpage that will accept form submissions and somehow output the http response or webpage after submitting a form on a different page.
I was trying to do all this in Greasemonkey but I can't figure out a way to collect the output of multiple form submissions(of the same page) for analysis after finishing. What I have so far is filling out the right form and submitting(though it seems to keep going in a loop forever because every time you submit the form you land back on the same page and the Greasemonkey script executes the form submission over and over again), but I'm stumped at how to somehow collect the results.
I have not used macros like iMacros before so perhaps that might be a more suitable approach?
Thanks! Open to any suggestions and hope to hear any help! Muchhhh appreciated! :) Thanks again!
I've not any experience with Greasymonkey, but an AJAX call is relatively easy when using jQuery (but I don't know whether jQuery works with Greasemonkey).
http://jsfiddle.net/9peGW/
$.ajax({ url: "/",
type: "GET",
data: $('#theform').serialize(), // returns like '?test=val&test2=val2'
// using the elements of the form
success: function(text, state, xhr) {
alert(text.substring(0, 200));
// alert first 200 response characters
// (so that it fits in the alert box)
alert(xhr.getResponseHeader("Content-Type"));
// alert the Content-Type response header
}
});
Note though that AJAX requests only work for the same domain as it is called from, but perhaps this is not applicable through Greasymonkey (I really don't have experience with that).
İt is too easy at İmacros. You can search for a tag and extract information that you need. Do not try jQuery. It is too complicated for this job, I know :)

What's the best way to submit a form to a form script on another site?

I am working on a basic HTML page that requires the user to send details to a script located on a third-party website. What I require is for the user to fill out a form on my web page, and have that information submitted to another third-party form.
I do not wish to return anything to the user, other than whether the submission was successful or not. I also do not want the user to have to go to this third-party site to submit using their form.
It was suggested by the website itself to use an iframe and hold its form on your page, but I was wondering what other, preferably better methods are available to me. It'd be nice if there were some form of jQuery/js code I could use to do such a thing.
It'd be nice if there were some form
of jQuery/js code I could use to do
such a thing.
One way is to use jQuery's $.ajax or $.post methods like this:
$.ajax({
url: url,
success: function(data) {
alert('succeeded');
}
});
Maybe you could try cURL with CURLOPT_POST and CURLOPT_POSTFIELDS?
well it depends if you have control over the other website as well. as in you are able to access the code.
If you are you can use JSONP to pass the values and get a response, but to do it you will have to assign a callback that is sent and then formatted at the front of a JSON object for it to work (they do this for security).
The other option is to use a php ob_start() function. (Note: this will only work if the form you are trying to submit these values to allow $_GET to be used to proccess the form)
ob_start();
include('http://wwww.anotherwebsite.com?key1=value1&key2=value2&key3=value3');
$returnString = ob_get_contents();
ob_end_clean();
So then from here $returnString is the result, which you can basically search (strpos() to see if true is how I would do it) in php to find key words to see if it was successful or not or what ever you need to check for.
But again, this only works if the form on the remote server uses $_GET and not $_POST (or allows both through globals).
I know this is a php solution, but a warning is that for security purposes, there are serious restrictions on what javascript can do cross server.. the best javascript way to do cross server is JSONP, which jQuery does support so you might want to look into that.. but as I mentioned, for it to work you need to have a callback be able to be sent back with the response, and the response needs to be in a jsonp object format.. (basically you either need to 1. have the other server have a jsonp api for you to use or you have control over the other server's server side files to make the changes needed).
Do you want like that? It's simple form submitting to another website. But, I can't check whether it's successfully submitted or not.
<form action="http://www.another.com">
<input name="myInput" type="text">
<input type="submit" value="Submit">
</form>

Categories