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

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?

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.

Form submit data to SQL DB without page reload (jQuery / PHP?) then change div content

Currently have this form
<div id="subfooter">
<form name="subscribe" method="post">
<input type="email" placeholder="e-mail address">
<input type="submit" value="Subscribe">
</form>
</div>
I also have another page called "_add_subscriber.php" which has the correct information to take the $_POST Data and push it into SQL.
Also I currently have 2 forms on my page. (each with different identifiers).
Now my question is...
When the submit button of form:subscribe is hit I want to post the data hidden to that _add_subscriber.php page thus enter the data to the database. (Not refreshing page!)
I also on click want to replace the contents of the 'subfooter' Div with something like...
<span>thanks for subcribing</span>
Thus hiding the original form.
I hope this makes sense, I have look at other solution but don't totally understand how they collect data from this specific form. Though It does seem to generally be a trait that PHP + jQuery can complete all the above actions for me!
Setting your HTML
<form name="subscribe" method="post" action="_add_subscriber.php">
Simple Ajax function I use for form submissions.
$('#subfooter form').on('submit', function() {
var $form = $(this);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success : function(data) {
// console.log(data);
// $('span').show(); // etc
}
});
return false;
});
Take a look into Jquery Serialize.

Multiple forms using same AJAX call with different outcomes?

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.

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.

Adding items to a table in jquery

I have an input box which i use to add items to a table in the db.
It looks like this:
<td>
<form class="insCat" action="#" name="insertCat">
<input name="categorienaam" type="text">
<input class="insert" type="submit" value="nieuwe categorie">
</form>
</td>
And i handle it like this in jquery
jQuery(".insert").click(function(){
str = jQuery("form.insCat").serialize();
console.log(str);
jQuery.ajax({
type: "POST",
data: str + "&cmd=insert",
url: "ajax_handler.php",
success: function(msg){}
});
jQuery("div.result").empty();
});
But i can't see anything in my log since the page is refreshed after each insert. Which i don't want.
Are there ways around this?
You need to prevent the default event of the submit button:
jQuery(".insert").click(function(e){
e.preventDefault();
...your code...
return false;
});
You are attaching the event handler to the submit button, and not stopping the execution of the default event. So the JS runs and then the form is submitted as normal.
First, set a more sensible action than "#" (a link to the top of the page) if the form gets submitted without JS.
Next, attach the event to the form, not the button. That way if it gets submitted through other means (such as the enter key being pressed on the text input) it will still work.
jQuery("form.insCat").bind("submit", yourFunction);
Then, edit your function so that it stops the default event action.
var yourFunction = function(event){
// do whatever you like then...
event.preventDefault();
};

Categories