I have a form: <form id="form" action="updatescore.php" method="post"> and a php file:updatescore.php which contains the code to update the database using the input values from the form. This all works when using a submit button.
Now I want to remove the submit button and submit the form if a javascript statement is true.
The js code part is:
if (document.getElementById('uhs').innerHTML > 0) { //this is true because the div gone is hidden
$('#gone').hide();
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "updatescore.php",
success: function () { //if submit to db is done
getUsers(1); //a function to reload a page overview
}
});
}
But nothing happens if the statement is true and the database is not updated. Any ideas on this one?
Kind regards,
are you sure the condition is TRUE?
if (document.getElementById('uhs').innerHTML > 0) { //this is true because the div gone is hidden
alert('its true');
also that is not right:
if (document.getElementById('uhs').innerHTML > 0)
perhaps:
if (document.getElementById('uhs').innerHTML.length > 0)
or:
if ($('#gone')[0].style.display=="none") {
The submit button is what triggers the event that runs the code:
$('#gone').hide();
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "updatescore.php",
success: function () { //if submit to db is done
getUsers(1); //a function to reload a page overview
}
});
The document.getElementById('uhs').innerHTML > 0 is not a event so there is not way to run your code .
Try this.....
document.addEventListener('keyup', function (e) {
//
if (document.getElementById('uhs').innerHTML > 0) {
$('#gone').hide();
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "updatescore.php",
success: function () { //if submit to db is done
getUsers(1); //a function to reload a page overview
}
});
}
});
Thanks for the replies. The code worked, but it seemed that a bug in another part of the code was messing with the AJAX call. So in the end there was nothing wrong with the code at all.
Again, thanks for the replies and suggestions!
Related
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.
I am using an inline jquery ajax to delete a list one by one. When giving an action to delete a list, the ajax will send some post data and the response is json encoded. Upon successful response, a pop up box will open in the first ajax success field asking for the username and password. Then an inline ajax will execute there, sending the pop up box's values along with the response from first ajax. I have given a condition in the inline ajax success field to validate the response for the second posted values. The response is coming true but the condition fails, i don't know why. Please refer the code...
$('.deleteButton').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: 'phpPage.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize() + "&del=del",
success: function (d) {
$(".popupContainer").show();
var text = "Do you really want to delete the report dated:";
$('#info').text(text);
$('#delForm').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: 'delRept.php',
type: 'POST',
data: $(this).serialize() + "&vtime=" + d.vtime + "&vdate=" + d.vdate + "&delbox=delbox",
success: function (data) {
if (data == 'string') {
$('#rrr').append("True : Delete it");
} else {
$('#rrr').append(data);
}
}
});
});
return false;
}
});
});
Here it will execute the else condition even if the response is true. Please help me to find the mistake in the coding...
Thanks
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;
});
I want to enhance my tool's page where as soon use click a button. Request goes to server and depending upon return type (fail/pass) i change color of button. No Refresh/page reload
Page has multiple buttons : some what like below.
Name 9-11 - 11-2 2-5
Resource1 - Button - Button - Button
Resource2 - Button - Button - Button
Resource1 - Button - Button - Button
I am a c++ programmer so you might feel i asked a simple question
Here's a sample of jQuery Ajax posting a Form. Personally, I'm unfamiliar with PHP but Ajax is the same no matter what. You just need to post to something that can return Success = true or false. This POST happens asynchronously so you don't get a page refresh unless you do something specific in the success: section.
$("document").ready(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: yourUrlHere,
dataType: "json",
cache: false,
type: 'POST',
data: $(this).serialize(),
success: function (result) {
if(result.Success) {
// do nothing
}
}
});
}
return false;
});
});
Of course you don't have to be doing a POST either, it could be a GET
type: 'GET',
And if you don't need to pass any data just leave data: section out. But if you want to specify the data you can with data: { paramName: yourValue },
The cache: false, line can be left out if you want to cache the page. Seeing as how you aren't going to show any changes you can remove that line. jQuery appends a unique value to the Url so as to keep it from caching. Specifying type: "json", or whatever your specific type is, is always a good idea but not necessary.
Try using the $.post or $.get functions in jquery
$.post("url",$("#myform").serialize());
Adding a callback function as Fabrício Matté suggested
$.post("url",$("#myform").serialize(),function(data){alert(data);$("#myform").hide()//?Do something with the returned data here});
Here you go. You will find an example of a form, a button a the necessary ajax processing php page. Try it out and let us know how it goes:
<form action="" method="post" name="my_form" id="my_form">
<input type="submit" name="my_button" id="my_button" value="Submit">
</form>
<script type="text/javascript">
$("document").ready(function () {
$('#my_form').submit(function () {
$.ajax({
url: "ajaxpage.php",
dataType: "json",
type: "POST",
data: $(this).serialize(),
success: function (result)
{
//THere was an error
if(result.error)
{
//So apply 'red' color to button
$("#my_button").addClass('red');
}
else
{
//there was no error. So apply 'green' color
$("#my_button").addClass('green');
}
}
});
return false;
});
});
</script>
<?php
//ajaxpage.php
//Do your processing here
if ( $processed )
{
$error = false;
}
else
{
$error = true;
}
print json_encode(array('error' => $error));
die();
?>
I'm currently learning PHP. I've made a simple script # http://hash.techho.me, only thing is, I want the form to submit then load the results via AJAX, without the user leaving the page. Possible?
post the form using ajax
$.ajax({
url:'yoururl',
data:$("form").serialize(),
type:'POST',
success:function(data){
alert("success");
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
jQuery.ajax() – jQuery API
Posting to the same page should do the trick. No need to use ajax for that
> <?php
>
> //do stuff with $_POST
> ?>
>
> <html> <body> <form method="post">
>
> <?php echo $result ?>
>
> </form>
> </body>
Fike
use ajax for this, lets suppose try this one for your practice
var string = $("#string").val();
var dataString = 'string=' + string ;
if(string==''){
alert('enter any string');
}
else{
$.ajax({
type: "POST",
url: "path of php file",
data: dataString,
suceess: function(){
//do something
},
error: function(){
//do something
}
});
}
You can use jQuery or Prototype JS libraries to make an easy AJAX call. Example using jQuery would be:
$.ajax({
url:'hashed.php',
data:$("form").serialize(),
type:'POST',
success: function(data){
$('hashmd5').html(data.md5);
$('hashsha1').html(data.sha1);
},
error: function(jxhr){
alert(jxhr.responseText);
}
});
Don't use the same id value in HTML, never ever. They must be unique to correct perform JavaScript functions on elements.
yes it is possible. Write a javascript function that would trigger on submit, disable the submit button so user couldn't press it again, and finally request the server via ajax. on successful response update the content. Something like following in Jquery
$('.form-submit').click(function(event)) {
event.preventDefault();
if(form is valid and not empty) {
$.ajax({
type: "POST",
url: "path to script that will handle insetion",
data: "data from form", //like ({username : $('#username').val()}),
suceess: function(data){
//update the content or what. data is the response got from server. you can also do like this to show feedback etc...
$('.feedback').html("Data has been saved successfully");
},
error: function(){
$('.feedback').html("Data couldn't be saved");
}
});
}
}