I have an AJAX function that loads data from the database using a simple select * ... to a div. the function works fine without submit, but when I use a form, it doesn't work and the #itemContainer is empty, Am I missing something? I even tried :
$(document).ready(function() {
$("#myForm").submit(function() {
but didn't work also
My code :
<script id="source" language="javascript" type="text/javascript">
$("#myForm").submit(function() {
$.ajax({
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
});
</script>
You didn't cancel form submission event.
Add preventDefault() in your submit
Like this
$("#myForm").submit(function(event) {
$.ajax({
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
event.preventDefault();
});
Update:
event.preventDefault() is depricated.
try to use return false;
Like this
$("#myForm").submit(function(event) {
$.ajax({
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
return false;
});
It's because page will be reloaded on form submission.
Handle the submit event and add return false.
<script id="source" language="javascript" type="text/javascript">
$("#myForm").submit(function() {
submitForm();
return false;
});
function submitForm() {
$.ajax({
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
};
</script>
Related
I have a function where the user inputs are stored in a variable in javascript.
$('#btnsubmit').click(function() {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
var bookseats = seat;
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats},
});
});
When the user clicks on the #btnsubmit button, I want to send this variable(actually an array) to a PHP file named confirm.php.
<form method="POST" action="confirm.php">
<div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div>
</form>
In my PHP file, I've written the code to get the sent variable as follows.
$bookseats = "";
if(isset($_POST['bookseats']))
{
$bookseats = $_POST["bookseats"];
print_r($bookseats);
}
When executed, nothing happens in the PHP file(doesn't print the bookseats).Is there something wrong with this code?
You're not using a "success" callback to get the output of the PHP code. See success callback
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats},
success: function(data) {
console.log(data); // or alert(data);
}
});
Also, I think you should stop the propagation of the default behavior of the button, to prevent the browser to redirect the page to the form's action URL:
$('#btnsubmit').click(function(ev) {
ev.preventDefault();
As #Malovich pointed out, as of jQuery 1.8, you could also use .then():
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats}
}).then(function(data) {
console.log(data); // or alert(data);
}, function(){
console.log("Error");
});
I'm going to forbid a second click on Google +1 button.
<g:plusone callback='click_callback' href="myurl.com"></g:plusone>
My click_callback function is:
function click_callback(b) {
if(b.state == "on") {
$.ajax({
type: "POST",
url: "gp1process.php",
data: "id=" + id,
cache: false,
success: function(a) {
$("#Hint").html(a);
remove(id);
click_refresh()
}
})
}
Can I use one() method of jQuery?
Since I am not actually posting to an ajax request I placed the $(this).attr("disabled", "disabled") before the ajax call but you will want it in your success function.
What this will do is add the disabled="disabled" attribute to your button after you click it. I think that is what you were looking for.
$(document).ready(function() {
$('button').click(click_callback);
});
function click_callback(b) {
id = $(this).attr('id');
if (!$(this).attr("disabled")) {
//the line below should be in your success function
//i placed it here so you can see the feature work
//since i am not really running the ajax
$(this).attr("disabled", "disabled")
$.ajax({
type: "POST",
url: "gp1process.php",
data: "id=" + id,
cache: false,
success: function(a) {
$(this).attr("disabled", "disabled")
$("#Hint").html(a);
remove(id);
click_refresh()
}
})
} else {
//the button is diabled do something else
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<g:plusone callback='click_callback' href="myurl.com"></g:plusone>
<button id="theID">+1</button>
<div id="hint"></div>
I have made a form submit with AJAX, the first time it submits, it has the success function, however the second time it prints the success data in accept_friend.php instead of the #requests_container, like a normal PHP form.
$('.accept_friend').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "../accept_friend.php",
type: "POST",
data: data,
success: function( data )
{
$('#requests_container').html(data);
},
error: function(){
alert('ERROR');
}
});
return false;
});
here is accept_friend.php
<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require "classes/class.requests.php";
require "classes/db_config.php";
$current_user = $_POST['current_user'];
$friend_id = $_POST['friends_id'];
$requests = new Requests($DB_con);
if($_SERVER["REQUEST_METHOD"] == "POST"){
$requests->accept($current_user, $friend_id);
}
?>
It seems that you are replacing the entire html in your $('#requests_container') and I am assuming that the .accept_friend button is also inside the same container.
If this is the case then try replacing your code with
$('#requests_container').on('submit', '.accept_friend', function(){
var data = $(this).serialize();
$.ajax({
url: "../accept_friend.php",
type: "POST",
data: data,
success: function( data )
{
$('#requests_container').html(data);
},
error: function(){
alert('ERROR');
}
});
return false;
});
This will keep your event alive even after the form button is removed and put back in the DOM
I've tested this and it does work for me (Firefox)
after you've clobbered your form, rebind the submit event to the submitter function
$('.accept_friend').submit(function submitter() {
var data = $(this).serialize();
$.ajax({
url: "../accept_friend.php",
type: "POST",
data: data,
success: function(data) {
$('#requests_container').html(data);
setTimeout(function() { // may not be needed
$('.accept_friend').submit(submitter); // rebind submit
}, 0);
},
error: function(){
alert('ERROR');
}
});
return false;
});
I m trying to create a link that when clicked won't redirect but will perform an action and then refresh the page using jquery.
Click Me
<Span id="updateMe">1</span>
Jquery
$('#btnClick').click(function(e){
url = $(this).attr('href');
$.ajax({
url: url,
success: function(){
alert("succes alert 1 worked");
}
});
$.ajax({
url: "another_url.php",
success: function(data){
$("#updateMe").html(data);
}
});
javascript:window.location.reload();
});
Do these:
Add e.preventDefault(); to stop reload.
Move reload() to the success callback.
Get rid of javascript:. You are already inside it.
Corrected Code:
$('#btnClick').click(function(e) {
e.preventDefault();
url = $(this).attr('href');
$.ajax({
url: url,
success: function() {
alert("succes alert 1 worked");
window.location.reload();
}
});
$.ajax({
url: "another_url.php",
success: function(data) {
$("#updateMe").html(data);
window.location.reload();
}
});
});
I am working on a dynamic page with multiple forms that can be added and removed by the user. My jquery script goes and finds all 'form' elements and submits them with jquerys ajax method. Here is the script
$(document).ready(function () {
(function (){
var id = $(document).data('campaign_id');
$(document).on('click', '#save-button', function () {
$('form').each(function (){
var data = new FormData(this);
var form = $(this);
if(!form.parent().hasClass('hideme'))
{
$.ajax({
url: form.attr('action'),
type: 'POST',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
console.log('form submitted '+count);
}
});
}
});
window.location.replace('/campaign');
});
})(); //end SIAF
});//end document.ready
The problem occurs that only sometimes the form submits, I can get it to if I click the save button a few times or if I remove the window.location.redirect that runs at the end, I suspect it is something to do with the redirect occurring before the submit, but I am not sure of a solution after going through some of the documentation
You are being caught out by the asynchronous nature of Ajax. Ajax does not work in a procedural manner, unfortunately. Your success method is called as and when the Ajax request has completed, which depends on your internet connection speed and how busy the server is.
It is entirely possible, the javascript completes its each loop and the first ajax request is still sending or waiting for a response. By when the javascript is ready to do a window.location call.
Edit:
Added code to check the number of forms, and the number of ajax requests, once they have all run, it will redirect
$(document).ready(function () {
(function (){
var id = $(document).data('campaign_id');
var numForms = $('form').length;
var numAjaxRequests= 0;
$(document).on('click', '#save-button', function () {
$('form').each(function (){
var data = new FormData(this);
var form = $(this);
if(!form.parent().hasClass('hideme'))
{
$.ajax({
url: form.attr('action'),
type: 'POST',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
console.log('form submitted '+count);
numAjaxRequests++;
if(numAjaxRequests == numForms) {
window.location.replace('/campaign');
}
}
});
}
});
});
})(); //end SIAF
});//end document.ready