Multiple forms using same AJAX call with different outcomes? - php

If I have many forms generated by PHP and want a "Reply" button on each of them, where it sends the content of the form via ajax to another php page, then can I use the same javascript snippet for all of these elements?
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Reply" />
</form>
So if I do something like the following, then can I still handle all the responses individually and display the response ONLY on the element that "Reply" was clicked on?
$("#foo").submit(function(event){
$.ajax({
url: "/form.php",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked only in the element it was clicked in!");
});
// prevent default posting of form
event.preventDefault();
});

If you want to handle all forms on the page, your code could work with minor changes.
$("form").submit(function(event){
$.ajax({
url: "/form.php",
type: "post",
// You have to have a way to retrieve the form data
data: getFormData(form),
success: function(response, textStatus, jqXHR){
console.log("Hooray, it worked only in the element it was clicked in!");
});
// prevent default posting of form or just return false
event.preventDefault();
});

No, there are multiple ways on submitting a form. You would want to change your first line to:
$("#replybutton").click(function(event){
Then you have to add that replybutton id to your button, and you'd have to explicitly list out the data elements in your ajax call. Also, the event.preventDefault() would be unnecessary. Come to think about it the whole <form> tags would be unnecessary as well.
There are other ways to do this using the form, but this is the simplest.

Related

Ajax page content is submitting form multiple times as many as page loaded

I have website that every page is being loaded using ajax both back to previous page, but the problem am facing now is submitting a form using ajax post. I try cache a form data with ajax and is working very fine except when i back to index.php and load same page again it will submit multiple time. And the more i back and load same page again it will submit how many time i loaded it.
What i really mean is, when i click on Open Page One from index page, and submit a form it will work at first browser reload. But when i use my ajax back button to navigate to index page and load that same Open Page One without reloading browser, it will submit two times and if i repeat same process again again, it will keep submitting based on how many time i click back and enter the page again.
Please can anyone help me i have also tried making the form id unique but it only work fine for different page ID.
INDEX.PHP
<div id="ShowPageContent">
Open Page One
Open Page Two
Open Page Three
</div>
<script>
$(function(){
"use strict";
$(document).on('click', '.loadwithajax', function(e){
var targetUrl = e.target.href;
var prevUrl = $(this).attr('data-page-link');
$.ajax({
type: "POST",
url: targetUrl,
data: {targetUrl : targetUrl, prevUrl : prevUrl},
async: false,
beforeSend: function(){},
success: function(htmlBlock){
$('#ShowPageContent').html(htmlBlock);
}
});
e.preventDefault();
});
});
</script>
OPENPAGE.PHP
<?php
$validateForm = 'validate-form-'.md5($_GET['targetUrl']);
?>
Back To Main Page
<form action="" method="post" class="<?php echo $validateForm;?>">
<input type="text" value=""/>
<input type="submit" value="Send"/>
</form>
<script>
$(function(){
"use strict";
$(document).on('submit', '.<?php echo $validateForm;?>', function(e){
$.ajax({
type: "POST",
url: ajax_appserver('shop', 'update_product.php'),
data: $(self).serialize(),
beforeSend: function(){},
success: function(data){
console.log(data);
}
});
e.preventDefault();
});
});
</script>
The problem happens because every time you load the page you attach an onsubmit handler to the document. Loading that page multiple times and document will have multiple copies of the same handler attached to it.
Adding $(document).off('submit', '.<?php echo $validateForm;?>') before $(document).on('submit'... will remove the previously attached handlers before adding a new one, and will solve your problem.

Submit form to two places

I have an issue where I need a simple contact form to have an action to post to a data collection service, AND to a thank you page for conversion tracking.
The data collection service page does not allow for any sort of redirection unfortunately, so my best bet is to submit to BOTH a thank you page, and to the data collection service.
I just don't know how to to this though... can someone please steer me in the right direction? I've done a lot of searching, but can't really get anything to work with jquery or javascript.
Any advice / feedback / methods would be greatly appreciated.
Per the reply below, I'm trying to get the AJAX to redirect after it sends data to the collection service like this, but I can't get it to work:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
// Shorthand for $( document ).ready()
$(function() { $("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
window.location.replace("http://example.com");
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}); });
</script>
<form name="ajaxform" id="ajaxform" action="https://secure.velocify.com/Import.aspx?Provider=IdealHomeLoansWebPOST&Client=IdealHomeLoansLLC&CampaignId=46"method="POST">
Using jQuery, you could send everything to your data collection service and wait for an answer. If it was successful, redirect to the thank you page.
Everything you need to know can be found in this article: http://hayageek.com/jquery-ajax-form-submit/
$(function() {
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
});
This replaces the default form-submission with an AJAX-Request.
Then just use the following code to redirect to the thank you page:
window.location.replace("http://example.com");
Submit to the Thank You page and have the Thank You page do a CURL request to the data collection service.
Or, submit to an intermediate page that submits the CURL request and then redirects to the Thank You page.
The most straight forward way I can think of doing this would be to have a onClick handler for your submit button and then using JavaScript fire off some sort of XHR post request to your data collection service containing the form data. You would then return true and the browser would post to the Thank You page.
For example using JQuery (your code will need more check and complexity)
HTML:
<form id="form" action="somewhere.php" method="post">
<!-- form stuff here -->
<input type="submit">
</form>
JS:
$('#form').submit(function() {
$.post('somewhereElse.php', {data: $('#form-element').val()});
return true;
});
JQuery Ajax Post, might have to set it to async.
On the success submit from the first one, you can submit to the second. Then on the success you can redirect to the the thankyou page.

Check if button was clicked in PHP from serialize() jquery

I'm building a form to allow someone to change the color of buttons, to be used on a webpage, via a web GUI. It's set up to submit the changes via ajax, with jquery, for preview prior to the user clicking the save submit button so they can make sure they like the changes before saving them.
I understand that .serialize() will not send the value of a button click or even tell you that a button was clicked. I have googled and searched stackoverflow but I can't make any of the solutions work with my set up.
How can the PHP script tell if the save button was clicked?
HTML:
<div id="preview"></div>
<form id="build_form" class="build_form" action="button_preview.php" method="post">
<input name="color" type="radio" value="red" /> red
<input name="color" type="radio" value="blue" /> blue
<input name="save" type="submit" value="Save" class="button" />
</form>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$(function() {
$(".build_form").change(function() {
$("form").submit();
});
});
$('#build_form').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
$('#preview').html(response);
}
});
return false;
});
});
</script>
PHP:
<?php
print_r($_POST);
?>
Calling .submit() on the form and then handling the submit event to stop the default submit and do an Ajax call seems overly complicated even aside from the fact that it stops your Save button working. Why not do the Ajax preview part directly in the change event and leave the submit to happen naturally via the Save button (which is a submit button already)? Remove the submit handler entirely.
$(function() {
$("#build_form").change(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
$('#preview').html(response);
}
});
});
});
When the Save button is clicked the request will include a parameter save with value Save, so in your PHP you can test for that. When the request is made via Ajax the parameter save will not be submitted.
add a hidden input that gets updated when you change your color value, this will have the effect of being serialize()able
edit
i see i didt address your point, why not add an onclick on your button that calls the function when clicked?

Ajax & Jquery form submission

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.

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