Ajax & Jquery form submission - php

I'm about to pull the hair out of my head with this one.
I'm sure the problem is simple, I'm new to Ajax with Jquery and I'm just overlooking something. But Man this is annoying. Every time the form is submitted, the page refreshes and .ajax throws error:. What could be causing this? I know I'm getting my form values to the Jquery for sure. And newcomment.php is working. I can post regular forms to it, but not with jquery.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
EDIT: Here's my html form:
<form>
<textarea id="comment" placeholder="Post Comment..."></textarea>
<input id="album" type="hidden" value="<?php echo "$a"?>"/>
<input id="photo" type="hidden" value="<?php echo "$p.$ext"?>"/><br/>
<button id="photo-comment-submit" onclick="postPhotoComment()">Post</button>
</form>
I also noticed that if I give the inputs names, Chrome puts them into the url bar like GET variables. And after every page refresh, it adds the ? at the end of the url. So, it seems like its trying to submit the form regularly.

Are you returning false to stop the browsers default action?
$('form').submit(function(){
var dataString = $(this).serialize(); // shortcut
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
});
return false;// cancels the default action
});

If the function where you're calling the AJAX form submission code is the onSubmit method of the form, you'll need to stop the default action from happening -- that is, you want to stop normal submission.
To accomplish this, use the preventDefault method of the event object:
function postPhotoComment(evnt) {
evnt.preventDefault();
// existing code continues...
}
You may also return false from your event, but be aware that doing so has different effects in different browsers, and that it is not as explicit or reliable as calling preventDefault or stopPropagation directly.
Edit
Also, the error handler is probably getting called because your code initiates the XHR request, but when the browser starts the default action (submitting the form), it cancels any pending XHR requests. This is causing the error handler to be triggered.
Edit 2 I have created a jsFiddle with a working demonstration: http://jsfiddle.net/wXrAU/
Documentation
event.preventDefault method on MDN - https://developer.mozilla.org/en/DOM/event.preventDefault

Make sure that you return false; to the form when submitting, otherwise it will still submit as a "normal" form without using Ajax and reload the page.
EDIT: After reading the comments I think that this would be most appropriate for you:
<form action="url.php" onsubmit="return false;"></form>
jsFiddle with appropriate code: http://jsfiddle.net/SO_AMK/ZVgNv/
The PHP messes things up a little, but it works.

I actually fixed this by simply removing the <form> tags. I didn't need them anyways. But everything seems to work now.

Make sure you write a valid, HTTP-accessible url instead of just a path to a script, e.g.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "http://yoursite.com/whatever/newcomment.php", // here
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
Because JavaScript is a client-side language. It knows nothing about your filesystem structure or anything of that kind. And AJAX request is based on HTTP protocol.

Related

AJAX - PHP how to return a variable to the original AJAX script and alter an input value

I am protecting my forms with a captcha code to prevent using bots submitting loads and loads of forms.
This form works with AJAX and won't refresh the page like it usually does.
I have everything set now and it is working. but..
So this is the form im talking about to help understand.
When you click on request a new password, i need the code to change on the input field.
I do change the code after requesting a password like this in newpass.php
$_SESSION['capcode3'] = $capcode3;
This is my javascript code:
<script>
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
document.getElementById("captcha").value = "<?php echo $_SESSION['capcode3']; ?>";
});
</script>
So by using document.getElementById it would change the input value but, instead of setting the new value, it sets the old value.
So if the code is ABC123 and the new code is DEF456 it wont change to DEF456
Is there a better way to send the new code back to the input field?
Note: I have tested if $_SESSION['capcode3'] will change it's value with a positive result.
You did not specify a success handler in your ajax. Ajax is handled async, thus needs a callback to where the data will be passed when the request is succesfuly handled
$.ajax({
type: "POST",
url : "data/newpass.php/",
success: function(data) {
//change UI here
document.getElementById("captcha").value = data;
},
});
Please add code in success of ajax because may be session value will be changed on ajax success.
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data,
success :function(data){
document.getElementById("captcha").value = data;
}
});
Please try with this.

Do I still need PHP validation while I am using Jquery.validate.Js and ajax?

I know js validation is for client side and php validation is for server side.
User can skip the js validation and submit but is it possible when I am getting the action php file in ajax?
I mean I am using the following code to validate the form. as you see I am calling postProjectAction.php in the ajax..
If an user skip the JS/disable the js and submit the form, form won't be submitted because,
my form has no action
the form data will not be inserted or submitted to the database if the postProjectAction.php is not called. when user disable the js the code won't call the postProjectAction.php
so there is no chance to submit the form.
Is this still insecure?
html:
<form id="form_validation" method="POST">
</form>
js validation:
$(document).ready(function() {
$("#form_validation").submit(function() {
if ($("#form_validation").valid()) {
var data1 = $('#form_validation').serialize();
$.ajax({
type: "POST",
url: "postProjectAction.php",
data: data1,
success: function(msg) {
console.log(msg);
$('.messagebox').hide();
$('#alert-message').html(msg);
$('.messagebox').slideDown('slow');
}
});
}
return false;
});
});
Well PHP validations are at server end while JQuery are at front end.
So its basically depend on need or requirements.
Bots can break front end validations while its bit difficult to break server end validations.
Bottom line, doing server side validation is making more secure :)
Yes, your form is still insecure. A user need not disable JavaScript or even submit your form to bypass the validation implemented.
Your code does validation only when the form is submitted. A user can simply paste the below code to the browser console and run it to post data without doing any validation.
var data1 = $('#form_validation').serialize();
$.ajax({
type: "POST",
url: "postProjectAction.php",
data: data1,
success: function(msg) {
console.log(msg);
$('.messagebox').hide();
$('#alert-message').html(msg);
$('.messagebox').slideDown('slow');
}
});
This is just one of the many ways validation on your form can be bypassed. It is always a good practice to validate all data coming from the client side.
$(document).ready(function() {
$("#form_validation").submit(function() {
if ($("#form_validation").valid()) {
var data1 = $('#form_validation').serialize();
$.ajax({
type: "POST",
url: "postProjectAction.php",
data: {data1:data1},
success: function(msg) {
console.log(msg);
$('.messagebox').hide();
$('#alert-message').html(msg);
$('.messagebox').slideDown('slow');
}
});
}
return false;
});
});
edit postProjectAction.php
if(!$_POST['data1'] OR !$_POST['blalbla']) header("HTTP/1.0 404 Not Found");
else{Your actions}

AJAX Form duplicate entries on submission

I've got a PHP form set up and it works fine on it's own but now that I've hooked it up with AJAX I'm getting duplicate submissions when someone submits the form so even though they've only submitted the form once it's added the details to the database multiple times.
From my testing it seems as though its sending the data twice but looking at the submissions from other people it's possible that it's doing it more than twice under certain circumstances but I haven't been able to replicate that.
Here is the code I was using initially:
$("#email-gather").submit(function(e) {
var url = "https://www.ruroc.com/emailgather.php";
$.ajax({
type: "POST",
url: url,
data: $("#email-gather").serialize(),
complete: function(data) {
$('.email-win input.button').val("submitted").attr('disabled', 'disabled').css({'background-color' : '#b34c4c','text-shadow' : 'none'});
}
});
e.preventDefault();
});
I have had a look around to find a solution and I saw a few people with similar issues saying that .live should be used instead of .submit so I amended my code this this:
$( "#email-gather" ).live( "submit", function() {
event.preventDefault();
var url = "https://www.ruroc.com/emailgather.php";
$.ajax({
type: "POST",
url: url,
data: $("#email-gather").serialize(),
complete: function(data) {
$('.email-win input.button').val("submitted").attr('disabled', 'disabled').css({'background-color' : '#b34c4c','text-shadow' : 'none'});
}
});
});
However this also resulted with the same issue so I'm hoping you might have a solution to this issue. I appreciate any help you can provide on the matter.
In the second part of code (that should work), you have event.preventDefault but event is not defined. try to add function(event) and it must work.
Else in the first one, you can put the prevent default before ajax call and take away the second submit. You need to add a return true in the ajax function to tell you script that the submit was successfull.

AJAX not sending user-input from a form to PHP script

I've been trying to learn basic AJAX and Javascript by following various tutorials and examples online, but I've hit a wall. I'm trying to write a simple script to take user-input from a form using AJAX and submit it to a PHP script, which then just echos the input.
All I can really tell is that whatever is being entered is not going through, but I'm not at the point yet where I can say why. I've tried with both POST and GET, and with various dataTypes, with the same result. I'm certain that I'm doing something wrong or misunderstanding something, but I'm not sure what.
HTML/ AJAX
<form id="my_form">
word <input type ="text" id="word1"/><br/>
<input type="submit">
</form>
<script>
$(document).ready(function(){
$("#my_form").on(function(e){
e.preventDefault();
var verb = $("word1").val();
$.ajax({
url: "testrun.php",
data: "verb",
type: "POST",
});
});
});
</script>
PHP
if (isset($_POST['verb'])){
$x= $_POST['verb'];
echo $x;
}else {
echo "not working";
}
EDIT: I've tried a few of the suggestions thus far, copying and pasting them directly, and none of them have actually done anything that I can see. I think I'm starting to understand a bit more about how AJAX should work, based on the responses, but it's still not reaching the PHP for some reason. I've tried both with the AJAX/HTML in a separate file that calls to the testrun.php script and with putting everything into the testrun.php file and basically having it call itself with the AJAX, but neither approach has achieved anything.
If the AJAX that I've gotten from the responses is fine, then am I misunderstanding something in how the PHP should be set up in order to actually receive the POST data? I'm still rather lost.
Three changes:-
1.var verb = $ ("word1").val(); need to be var verb = $ ("#word1").val();because its id (word1)
2.data: "verb", needs to be data: {"verb":verb},
3.form submission need to be correct so code given below (missing submit):-
Correct code:-
$(document).ready(function(){
$("#my_form").on('submit',function(e){ // check here you have one missing `submit`
e.preventDefault();
var verb = $("#word1").val(); // remove space between `$` and `(`
$.ajax({
url: "testrun.php",
data: {"verb":verb},
type: "POST",
});
});
});
You can not send data as data: "verb", in ajax. you need to send your data in params.
Second, you can not get the value of word1 input as $("word1").val(); you need to use # for get input by IDs.
Example:
$(document).ready(function(){
$( "#my_form" ).submit(function( e ) { //CHANGED using submit event.
e.preventDefault();
var verb = $("#word1").val(); //CHANGED
$.ajax({
url: "testrun.php",
data: "verb="+verb, //CHANGED
type: "POST",
});
});
});
You forgot # foe id selector of word1.
.on() needs event to bind to. In your case of form submit, it's submit
Data should be passed as object. In your case, you will be able to access it with $_POST['verb']
$(document).ready(function ()
{
$("#my_form").on('submit', function (e)
{
e.preventDefault();
var verb = $("#word1").val();
$.ajax({
url: "testrun.php",
data: {verb: verb},
type: "POST"
});
});
});
you miss to give the # sign in var verb = $("word1").val();
and use a variable just as a variable to the data like data: {"your_var_name" : verb}
Try this ...
$.ajax({
type: "POST",
url: "testrun.php",
data: "paramname=value", // access in php $_POST['paramname']
success: function(data){
// if page request is success
},
error: function(data){
// if page request failes
}
});
You have to do this:
var verb = $("#word1").val(); //Don't forget to add #
$.ajax({
url: "testrun.php",
data: {"verb":verb},
type: "POST",
});
verb is a variable, no need to put in between quotation!
The correct answer is
HERE by Anant

ajax jquery search form in PHP

This is my form:
<form id="submitsearch" action="Classes/system/main/searchresult.php" method="POST">
Search by <span style="font-size:15px;">(developer, specialization, profession,major)</span>
<input type="text" name="searchbox" id="searchbox" />
in
<select style="text-align:center;" name="countrysearch" id="countrylist">
<option selected="selected" value="0">None</option>
<option value="1">USA</option>
</select>
<input style="margin-left:25px;" id="submitSearch" type="submit" value="Search"/>
</form>
and this is the Ajax jquery code:
$("#submitSearch").click(function(){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#submitsearch').find('#pagePanel').html(response);
});
Why isn't it working ? The php file is returning the correct result normaly.
But i want it to load inside another div with an id "pagePanel" without reloading, using ajax.
Any help ? I'm new to Ajax.
Edit:
$("#submitbutton").click(function(){
$.ajax({type:'POST', url: 'Classes/system/main/searchresult.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
}})});
This worked out with me.
Thanks for all your help.
If you have a input of type submit, it will, guess what :), submit the form, and therefore reload the page. Turn it into:
<input style="margin-left:25px;" id="submitSearch" type="button" value="Search"/>
Then make sure you actually have a pagePanel element in your html.
And now a couple of suggestions:
don't id your form #submitsearch and the button as #submitSearch... confusion may arise
you can use AJAX's .load() instead of .ajax() to get directly the result in the DIV:
So:
$("#pagePanel").load('Classes/requests/search.php', {$('#submitsearch').serialize()});
If you want to use ajax in the form submition you'll need to cancel it.
$("#submitSearch").click(function(event){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
});
event.preventDefault();//prevents submitting of the form
}
First you need to stop the default form submittal. return false in the submit handler to stop default. Just use the ID of the element without using find() to insert data into. The elemnt you are trying to find doesn't appear in your html though within the form where your code suggests it should be
$("#submitSearch").click(function(){
$.ajax({type:'POST',
url: 'Classes/requests/search.php',
data:$('#submitsearch').serialize(),
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
})
return false;
});
After pushing the submit button, the default behaviour is to submit the form and indeed go to the action URL you provided to your form. Now, you want to prevent that behaviour. This means, you'll have to look at the onsubmit event of the form, and prevent the actual submission. jQuery has a preventDefault() method to do this.
In your case, all you'll have to do is add the following code:
$(document).ready(function() {
$("#submitsearch").on("submit", function (e) {
e.preventDefault();
});
});
And here is a jsFiddle to demonstrate it.
You can obviously do the same thing to your submit button, just add the e variable as the argument to your click event and use e.preventDefault() to cancel the actual submit (but you can still perfectly do the AJAX request).
First of all, you are missing a few closing parenthesis and curly brackets. Be sure to run your dev tools in your browser to check console for errors like that. I normally don't use $.ajax...I usually use $.post, but using what you have so far, I would rewrite to something closer to:
$("#submitsearch").submit(function(){
var submitData = $(this).serialize();
$.ajax(
{
type:'POST',
url: 'Classes/requests/search.php',
data: submitData,
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
}
);
return false;
});​
Instead of sending back loads of HTML to the page, you could just send results in form of a set of JSON objects and then dynamically create the HTML based on the results, this means a lot less data being sent back to the browser which is quicker and more efficient.

Categories