Adding items to a table in jquery - php

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();
};

Related

Stop form from refreshing on submit

I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});

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.

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 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.

jQuery validate does not return submit button name

I need help here.
My jQuery code does not return the submit button name in the $_POST Array...
This is my code:
<script type="text/javascript">
$(document).ready(function(){
$('#submForm').validate({
submitHandler: function(form) {
// Do cleanup first
form.submit();
}
})
});
</script>
<input type="submit" class="paypal_bttn" value="premium" name="bttn">
In the $_POST array I can see everything except the button name, that I am really in need to know...
Please help.
Thanks
That's normal. No button was clicked by the user. You forced the submission of the form using javascript. Why do you expect that a button name would be sent when no button was clicked at all. What if you had multiple submit buttons? Which one would you like to send in this case? If your server side script expects some button name you could inject a hidden field into the form with the same name and set its value just before forcing its submission:
$(form).append(
$('<input/>', {
type: 'hidden',
name: 'bttn',
value: 'premium' // TODO: you might want to adjust the value
})
);
form.submit();
you are not submitting or validating the form on button click, since you have wrapped your code inside the ready handler as soon as the DOM is ready you form is validated and then submitted
<input type="submit" class="paypal_bttn" value="premium" name="bttn">
what you can do is
$(document).ready(function(){
$("input[name='bttn']").click(function(e){
e.preventDefault(); //your button type is submit so prevent the default form submission
$('#submForm').validate({
submitHandler: function(form) {
// Do cleanup first
form.submit();
}
})
});
});
The jQuery is not running when you are clicking the button. What you need to do is add the "click(function()" instead. You can then use attr() or other items to select what you want to from there.
You should also use return false; if you don't want the page to submit and you want to use AJAX.
$(".paypal_bttn").click(function(){
// add stuff to do here.
});
You might want to capture the click of the button and do your validation/submit from there.
$('.paypal_bttn').click( function() {
// Do cleanup first
// validate form and submit
}

Categories