I have a jQuery textarea from where I am posting form values with a button. I don't want to refresh the page and use AJAX for this purpose so that the page does not get refreshed. I have tried a lot but the solution does not seem to be coming out. Here is my code for the same. Any insight will be really helpful.
Here is my code,
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><span onclick='$(this).parent().hide()'><b>X</b></span><form id = 'contactForm1' action='submit.php' method='post'><textarea required cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' id = 'submitnotes' name= 'submit_notes' type='submit' onclick = 'submitform()' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>
<script type="text/javascript">
function submitform() {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
}
</script>
To achieve this hook to the submit event of the form itself, not the click event of the submit button. Also note that you shouldn't be using on* event attributes. As the HTML content of the form is dynamically appended to the DOM you can use a delegated event handler on both the form and span instead. Try this:
$(document).ready(function() {
$('.click_notes').on('click', function() {
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html('<div class="comment_form"><span><b>X</b></span><form id="contactForm1" action="submit.php" method="post"><textarea required cols="50" class="span10" name="notes" rows="6"></textarea><br><input class="btn btn-primary" id="submitnotes" name="submit_notes" type="submit" value="Add Notes"><input type="hidden" name="submitValue" value="' + tid + '" /></form><br></div>');
});
$(document).on('submit', '#contactForm1', function(e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
},
error: function(xhr) {
console.log('An error occurred.');
console.log(xhr);
},
});
}).on('click', 'span', function() {
$(this).parent().hide()
});
});
Also note that you're including two versions of jQuery, one of which (1.6.1) is getting nearly 8 years out of date. I'd suggest using a single reference to jQuery 3.3.1 instead.
Related
I have 2 buttons "removeD" and "updateRecord"(by id) and I have written same ajax for them as follows:
$.ajax({
url: 'DB/tableDisplay.php',
type: 'POST',
data: 'id='+uid,
dataType: 'html'
})
But in tableDisplay.php I want to have different functionality for both the buttons.How to check the id of the button clicked in php?
I've tried using :
if(isset($_POST['removeD'])){
}else{
}
But this is not working.
Try this:
$(document).ready(function(){
$('button').click(function(){
var id = $(this).attr('id');
$.ajax({
url: 'DB/tableDisplay.php',
type: 'POST',
data: {id: id},
dataType: 'html'
})
});
});
$('body').on('click','#id1',function(){
$.ajax({
url : 'url',
data : {variable:values},
type : 'html',
dataType : 'GET/POST',
success : function(data){
console.log('Message after Success');
},
error : function(){
console.log('Error Message')
}
});
});
In your url page you can find whether ajax request is posted or not
if(isset($_REQUEST['variable'])){
write your php code here........
}
Try the following code to detect the button clicked:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('.click-button').on('click',function () {
var button_id = $(this).attr('id');
if(button_id == 'removeD'){
alert('removeD button clicked');
}else if(button_id == 'updateRecord'){
alert('updateRecord button clicked');
}
});
});
</script>
</head>
<input type="button" class="click-button" id="removeD" value="removeD">
<input type="button" class="click-button" id="updateRecord" value="updateRecord">
You can use target it return which DOM element triggered the event. see below code its too easy and short to get id of clicked element.
$('button').click(function(e){
alert(e.target.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="remove">Remove</button><br>
<button id="update">Update</button><br>
the problem is that i am unable to insert data in my database without reloading
i have tested it without the note_sql.js and my note_sql.php works fine but there seems to be a problem in my js file if some body could point me in the right direction it would be wonderful
Index.php
<form id="noteform" action="note_sql.php" method="POST">
<input type="text" name="note"></input>
<input id="sub" type="submit" value="Save Note" />
</form>
<span id="result_note"><span>
<script type ="text/javascript" src="jquery/note_sql.js"></script>
note_sql.js
$("#sub").click(function(){
var data = $("#noteform: input").serializeArray();
$.post($("#noteform").attr("action"),data,function(info){$("result_note").html(info); });
clearInput();
});
$("#noteform").submit(function(){
return false;
});
function clearInput(){
$("#noteform :input").each(function(){
$(this).val('');
});
}
Use Jquery Ajax the working code is given below :
please add ID to Note Form Element :
<pre>
<script>
$(document).ready(function () {
$("#sub").click(function () {
var name = $("#note").val();
var message = $("#message").val();
$.ajax({
type: "post",
url: "note_sql.php",
data: "name=" + name,
success: function (data) {
alert(data);
}
});
});
});
</script>
</pre>
Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});
I have a page that lists a bunch of items with add to cart buttons, the user clicks the button it fires AJAX which adds the item to the php cart and adds the item to the sidebar for a visual cue of what's in the cart, with a remove button. Problem is, when i click the remove button it refreshes the page even though i have prevent default attached to the function
This works
$(document).ready(function(e) {
$('.additem').click(function(e) {
e.preventDefault();
$(this).html('Added').attr('disabled' , true);
$(this).closest('form.form_add').submit()
});
$('form.form_add').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "buy-page-handler.php",
data: $(this).serialize(),
dataType: "json",
success: function(result) {
var id = result.id;
var name = result.name;
var qty = result.qty;
var price = result.price;
$('#sidebar').append('<div class="cart_cont">'
+'<div class="desc">'+name+' '+price+'</div>'
+'<div class="remove">'
+'<form method="post" class="form_delete">'
+'<button type="submit" class="removeitem">Remove</button>'
+'<input type="hidden" name="id" value="'+id+'">'
+'<input type="hidden" name="item-remove" value="true">'
+'</form>'
+'</div>'
+'</div>');
}
});
});
This doesn't work
$('.removeitem').click(function(e) {
e.preventDefault();
$(this).closest('.form_delete').submit()
});
$('.form_delete').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "buy-page-handler.php",
data: $(this).serialize(),
success: function() {
alert("success")
}
});
});
This is my first attempt at using the jquery/ajax/php combination, so i'm sure its a bit rough.
Any help would be greatly appreciated.
The issue is that your class="removeitem" elements are added dynamically after the DOM is ready, so your new elements are not bound to $('.removeitem').click(). Try binding it by delegating to the parent -
$('#sidebar').on('click', '.removeitem', function(e) {
e.preventDefault();
$(this).closest('.form_delete').submit()
});
Just change:
<button type="submit" class="removeitem">Remove</button>
to:
<button type="button" class="removeitem">Remove</button>
Been asking a lot of jquery questions lately, I'm trying my best to learn a lot about it.
Anyway, I am sending an Ajax HTTP request to a PHP page in order to make a login form without requiring a page refresh. Now since it may take some time to connect the database and get the login information etc..
Now I do have loading as a .html but how can I hide the loading data once data has loaded?
Tried to use a few functions but didn't seem to work.
Thanks so far, this site has helped me a lot through the learning process.
Here's the JavaScript:
$(document).ready(function() {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
user_login: $('#user_login').val(),
pass_login: $('#pass_login').val()
}
}
function loading(e) {
$('#content').html('Loading Data');
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function(e) {
if (e.keyCode == 13) {
var username = $('#user_login').val();
loading(e);
check(e);
}
});
$('#submit').click(function(e) {
if (e.keyCode != 13) {
loading(e);
check(e);
}
});
});
Here is the HTML:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="js/login.js"></script>
<div id="content"> Loading...</div>
<div id="field">
<input type='text' name='user_login' id='user_login' placeholder='eg: Mark#gmail.com'> <br>
<input type='password' name='pass_login' id='pass_login'> <br>
<input type="submit" name="submit" id="submit" value="Login">
</div>
function check(){
$.ajax({
url: 'ajax/check.php',
type: 'post',
error: function(){
alert('An error has occured.');
},
beforeSend: function(){
$('#content').show('slow').html('Loading');
//loading(e);
},
data: {user_login: $('#user_login').val(),pass_login: $('#pass_login').val()}, // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});
}
$('#submit').click(function(){
check();
});
$('#field, #field input').keyup(function(e){
var username = $('#user_login').val();
if (e.keyCode == 13) {
check();
}
});
Markup
<div id="field">
<input type='text' name='user_login' id='user_login' placeholder='eg:Mark#gmail.com'> <br>
<input type='password' name='pass_login' id='pass_login'> <br>
<input type="button" name="submit" id="submit" value="Login">
</div>
Good luck!!!
First of all, i'm not sure if your code will return a success. This code will help you find out if the response is not successfully. If you get a browser alert. It means you have a server side error. Its either the url path is wrong or your server response statuscode is 500 (Internal error).
$.ajax({
url: 'ajax/check.php',
type: 'post',
error: function(){
alert('An error has occured.');
},
beforeSend: function(){
$('#content').show('slow').html('Loading');
//loading(e);
},
data: getData(), // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});
Refactoring your code entirely will look like this. Choose first or second:
$.ajax({
url: 'ajax/check.php',
type: 'post',
error: function(){
alert('An error has occured.');
},
beforeSend: function(){
$('#content').show('slow').html('Loading');
//loading(e);
},
data: {user_login: $('#user_login').val(),pass_login: $('#pass_login').val()}, // get current values
success: function (data) {
$('#content').hide('slow');
alert(9);
}
});