Refreshing div without reloading not working - php

I'm "fighting" with this for hours now, I hope you could help me with the solution. So I've got a basic form with an empty div that will be then filled:
<form method='post' action='/shoutek.php'>
<input type='text' id='shout_tresc' name='shout_tresc' class='shout_tresc' />
<input type='submit' id='dodaj' value='Dodaj' />
</form>
<div class='shoutboxtresc' id='shout'></div>
<span class='loader'>Please wait...</span>
The shoutek.php contains the queries to do after submission of the form and functions to populate the div.
Here goes my jquery:
$(function() {
$(\"#dodaj\").click(function() {
// getting the values that user typed
var shout_tresc = $(\"#shout_tresc\").val();
// forming the queryString
var data = 'shout_tresc='+ shout_tresc;
// ajax call
$.ajax({
type: \"POST\",
url: \"shoutek.php\",
data: data,
success: function(html){ // this happen after we get result
$(\"#shout\").toggle(500, function(){
$('.loader').show();
$(this).html(html).toggle(500);
$(\"#shout_tresc\").val(\"\");
$('.loader').hide();
});
return false;
}
});
});
});
The problem in that is that it directs me to shoutek.php, so it does not refresh the div in ajax.
As you can see, I used return false; - i also tried the event.preventDefault(); function - it did not help. What is the problem and how to get rid of it? Will be glad if you could provide me with some solutions.
EDIT
Guys, what I came up with actually worked, but let me know if that's a correct solution and will not cause problems in the future. From the previous code (see Luceous' answer) i deleted
$(function() {
(and of course it's closing tags) and I completely got rid of the:
<form method='post' action='/shoutek.php'>
Leaving the input "formless". Please let me know if it is a good solution - it works after all.

$(function() {
$("#dodaj").click(function(e) {
// prevents form submission
e.preventDefault();
// getting the values that user typed
var shout_tresc = $("#shout_tresc").val();
// forming the queryString
var data = 'shout_tresc='+ shout_tresc;
// ajax call
$.ajax({
type: "POST",
url: "shoutek.php",
data: data,
success: function(html){ // this happen after we get result
$("#shout").toggle(500, function(){
$('.loader').show();
$(this).html(html).toggle(500);
$("#shout_tresc").val("");
$('.loader').hide();
});
return false;
}
});
});
});
For readability I removed your escapes. You've missed the preventDefault which prevents the form from being submitted.

You need to prevent the default action on submit button click:
$("#dodaj").click(function(event) {
event.preventDefault();
// your code
}

Related

Send selectbox value to php variables without page reloading

I'm learning AJAX by reading some online tutorials, so please understand I am very new to AJAX and programming in general. I have managed to do the following with 3 selectboxes:
populates selectbox 2 based on selection from selectbox 1
populates selectbox 3 based on selection from selectbox 2
Everything is working perfectly
Here is my code:
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
Here is an Example
What I want to do
I would like to send the value of the 3 selectboxes to 3 php variables without the form reloading.
My Problem
When the user clicks submit:
The form reloads (which I dont want)
The selectbox values does not get send to my php variables
my code to get the values after submit is clicked is as follows:
if(isset($_POST['submit'])){
$a = $_POST['sport'];
$b = $_POST['tournament'];
:
}
However my code is flawed as I mentioned above.
If any one can help me to explain how to send my form data to the 3 php variables without the form reloading it will be greatly appreciated
If you don't want to submit your form when you click the button, you need to set that input as button and not submit. You can, also, attach the submit event handler to the form and prevent it to submit:
$("form").on("submit", function(e){
e.preventDefault(); //This is one option
return false; //This is another option (and return true if you want to submit it).
});
So, being said this, you could probably do something like:
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'yoururl',
data: formData,
type: 'post', //Based on what you have in your backend side
success: function(data) {
//Whatever you want to do once the server returns a success response
}
});
});
In your backend:
if (isset($_POST["sport"])) {
//Do something with sport
}
if (isset($_POST["tournament"])) {
//Do something with torunament
}
echo "Successfull response!"; //You have to "write" something in your response and that is what the frontend is going to receive.
Hope this helps!
Try using the javascript function preventDefault().
See this SO question.
Use a <button>Submit</button> element instead of <input type="submit"/> since the submit automatically submits the form.
Edit: And you would have to use on.('click') instead of looking for submit event in your jQuery.

My textarea sends empty values with ajax for my PHP codes

i have created a textarea & i wanna send the values of my textarea with ajax to the database, but it sends it to database without any value and with reloading, where is my problem ?
html codes :
<form>
<textarea></textarea>
<button type="submit">ارسال</button>
</form>
ajax codes :
$(document).ready(function(e){
var text=$('textarea').val();
$('button').click(function(e){
$('.loading').css('display','block');
$.ajax({
url:'insertText.php',
type:'POST',
data:{'text':text},
beforeSend : function(){
$('.loading').html('فرستادن ...');
},
error : function(request) {
alert(request);
},
success:function(data){
alert(data);
}
});
});
});
and this is my pdo and mvc for informations , i put last layer :
$obj=new Get;
$obj->InsertText($_POST['text']);
Place the line var text=$('textarea').val(); inside click event of the button, Otherwise it will take only the initial value at the time of dom ready.
$(document).ready(function(e) {
$('button').click(function(e) {
var text = $('textarea').val();
$('.loading').css('display', 'block');
$.ajax({
url: 'insertText.php',
type: 'POST',
data: {
'text': text
},
beforeSend: function() {
$('.loading').html('فرستادن ...');
},
error: function(request) {
alert(request);
},
success: function(data) {
alert(data);
}
});
});
});
You have two problems:
You are getting the value from the textarea at the wrong time
You are submitting the form
Your line of code:
var text=$('textarea').val();
Is inside the ready handler but outside the click hander. This means you get the value at the time the DOM becomes ready and not at the time the button is clicked.
Move it inside the click handler.
To stop the form submitting, you need to tell the browser not to perform the default action for clicking a submit button:
$('button').click(function(e){
e.preventDefault();
Note that, in general, it is better to react for the form being submitted rather than a specific submit button being clicked:
$('form').submit(function(e){
e.preventDefault();
It is also preferred that the form should still work when the JavaScript fails (for whatever reason):
<form action="insertText.php" method="POST">
and
<textarea name="text">

Trouble POSTing form with AJAX

edit - the info appears to be posting, but on form_data.php it doesn't seem to be retrieving the posted values
Here's the AJAX
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#submit_boxes").submit(function() { return false; });
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: function(data) {
$('#view_inputs').html(data); //view_inputs contains a PHP generated table with data that is processed from the post. Is this doable or does it have to be javascript?
});
return false;
});
};
</script>
</head>
Here is the form I'm trying to submit
<form action="#" id = "submit_boxes">
<input type= "submit" name="submit_value"/>
<input type="textbox" name="new_input">
</form>
Here is the form_data page that gets the info posted to
<?php
if($_POST['new_input']){
echo "submitted";
$value = $_POST['new_input'];
$add_to_box = new dynamic_box();
array_push($add_to_box->box_values,$value);
print_r($add_to_box->box_values);
}
?>
Your form is submitting because you have errors which prevents the code that stops the form from submiting from running. Specifically dataType: dataType and this.html(data) . Firstly dataType is undefined, if you don't know what to set the data type to then leave it out. Secondly this refers to the form element which has no html method, you probably meant $(this).html(data) although this is unlikely what you wanted, most likely its $(this).serialize() you want. So your code should look like
$('form#submit_boxes').submit(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: success
})
return false;
});
Additionally if you have to debug ajax in a form submit handler the first thing you do is prevent the form from submitting(returning false can only be done at the end) so you can see what errors occurred.
$('form#submit_boxes').submit(function(event) {
event.preventDefault();
...
});
You can use jQuery's .serialize() method to send form data
Some nice links below for you to understand that
jquery form.serialize and other parameters
http://www.tutorialspoint.com/jquery/ajax-serialize.htm
http://api.jquery.com/serialize/
One way to handle it...
Cancel the usual form submit:
$("#submit_boxes").submit(function() { return false; });
Then assign a click handler to your button:
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: this.html(data),
success: success,
dataType: dataType
})
return false;
});

Jquery Ajax Request and PHP

New to Jquery, even newer to Jquery Ajax calls - here is my problem:
I have a small form - email address submit - that fires to a PHP file which inserts the email into a table.
I want to do the following:
Handle the form submission through Ajax so there is no refresh
After successfully writing to the table I want to change the submit button's text to "Success!" for 3 seconds and then back to
"Sign Up" with fadeIn and fadeOut effects.
Here is my code for the form:
<form action="" id="registerform" name="registerform" method="post" >
<input type="text" id="email" name="email" value="Email Address" onClick="empty()" onBlur="determine()" />
<button id="join" type="submit" name="join" onClick="validate()">Sign Up</button>
</form>
Here is my terrible attempt at handling the POST request through Jquery:
$('form').on('submit', function(e) {
$.post('register.php', function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
Can anyone comment on how to make the Ajax request work (doesn't seem to be)?
Thanks in advance!
Update
Alright, the following block of Jquery adds the data to the table, however, my button text does not change:
$('form').on('submit', function(e) {
$.post('register.php', $("#registerform").serialize(), function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
Any ideas now?
Here is an example of one of my ajax calls
details = "sendEmail=true&" + $("form").serialise();
$.ajax({
url: "yourphppage.php",
type: "post",
data: details,
success: function (data, textStatus, jqXHR) {
if (data == "false") {
console.log("There is a problem on the server, please try again later");
} else {
//Do something with what is returned
}
}
})
And on the server side
if (isset($_POST['sendEmail'])) {
//Do something with the data
}
Of course this is only an example, and you may need to alter this to suit your needs :)
One thing to note is what if (data == "false") does. Well on the server side i can echo "false" to tell the ajax call it was not successful.
You're not actually sending any data to the server. You need to use the 'data' parameter of $.post to send your data.
$('form').on('submit', function(e) {
$.post('register.php', $(this).serialize(), function() {
$('#join').html('Success!');
});
//disable default action
e.preventDefault();
});
Not sure, but does the POST request send anything at all? Try adding the data in the POST request.
$('form#registerform').submit(function() {
var email = $(this).find('input[name=email]').val();
$.post('register.php', {email: email}, function() {
$('#join').html('Success!');
});
return false;
});
Where you're pushing your form data to server in ajax call? change code to this.
var data = {$("#email").val()};
$('form').submit(data ,function(e) {
$.post('register.php', function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});

Posting a sub-form with jQuery

I'll start off by saying I'm new to jQuery but I am really enjoying it. I'm also new to stackoverflow and really loving it!!
The problem:
I've created a sub-form with jQuery so that a user may add, then select this information from a dropdown list if it is not already available. I'm unable to POST this data with .ajax(), so that the user can continue to fill out other information on the main form without having to start over.
Sub-Form:
$(function() {
$("#add").live('click', function(event) {
$(this).addClass("selected").parent().append('<div class="messagepop"><p id="close"><img src="img/close.png"></p></img><form id="addgroup" method="POST" action="add_group.php"><p><label for="group">New Group Description:</label><input type="text" size="30" name="grouping" id="grouping" /></p><p><label for="asset_type">Asset Type:</label><select name="asset" id="asset" ><option>Building</option><option>Equipment</option></select></p><p><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></form><div id="result"></div></div>');
$(".messagepop").show()
$("#group").focus();
return false;
});
$("#close").live('click', function() {
$(".messagepop").hide();
$("#add").removeClass("selected");
return false;
});
});
And here is where I'm attempting to process it:
$(function () {
$('#addgroup').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
I've even attempted to create a simple alert instead of processing the information and this also does not work. Instead the form sumbits and refreshes the page as normal. Can anyone help me understand what I am missing or doing wrong? Thank you!
New attempt:
$("#add").live('click', function(event) {
var form = $("<form>").html("<input type='submit' value='Submit'/>").submit(function(){
$.post("add_group.php", {grouping: "Building, asset: "STUFF"});
$(".newgroup").append(form);
return false;
});
Final code
$(function() {
var id = 1
$("#add").live('click', function(event){
if($(".addgroup,").length == 0){
$("#test").append('<div class="addgroup"><label for="newGroup">New Group:</label><input type="text" class="newgroup" id="' + ++id + '" /><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></div>');
$("#add").attr("src","img/add_close.png");
}else{
$("#add").attr("src","img/add.png");
$(".addgroup").remove();}
return false;
});
});
$(function(){
$(".group_submit").live('click',function(event){
$.ajax({
type: "POST",
url: "add_group.php",
data: {new_group: $(".newgroup").val(), asset: $("#group option:selected").text()},
success: function(){}
});
$(".addgroup").remove();
$('#subgroup').load('group.php', {'asset': $("#group option:selected").text()});
return false;
});
});
If the form is submitting and refreshing as normal, the jquery isn't kicking in (the refresh means it's posting the form normally).
I for some reason (maybe others haven't) found that $(document).ready(function() { works much better than $(function() { ...
Also, the groups that you're adding should have a definitive id:
on #add click, count up a counter (form++) and add that to the id (#addGroup_+form) and then target that straight away in the function that added it:
$("#group").focus();
$("#addGroup_"+form).submit(function() {
try using .live()
$(function () {
$('#addgroup').live('submit',function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
and make sure addgroup has no duplicate id... you may use it as class if it has to be duplicated...

Categories