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
});
Related
I want to create an ajax post request that gets the value of the radio button then use it in a PHP conditional statement.
So far i have tried this code (all code is from one php file):
$(document).ready(function () {
$('.radio-buttons input[type="radio"]').click(function(){
var subject= $(this).val();
$.ajax({
url: 'home.php',
type: 'POST',
data: {
'subject': subject
},
success: function(response) {
alert(response);
}
});
});
});
<form id="form1" method="POST" class="radio-buttons ">
<input class="radio-filter" type="radio" name="subject" value="A">A</input>
<input class="radio-filter" type="radio" name="subject" value="B">B</input>
</form>
if (isset($_POST['subject'])) {
echo "Showing!";
}
the alert message shows the value of the radio button when I clicked them but the echo in PHP condition is not showing.
You are using alert(subject); which will just alert the value of the radio button as you've mentioned.
Change that line to alert(response); to alert the response on success.
The alert(subject) needs to be alert(response).
Change alert(subject) to alert(response)
because 'subject' is what you have been sent! so after it 'subject' will receipt by your PHP process and returned as response(echo "Showing") on value of the function an object success: function(response)
and alert the response to see data/text "Showing"
$(document).ready(function () {
$('.radio-buttons input[type="radio"]').click(function(){
var subject= $(this).val();
$.ajax({
url: 'home.php',
type: 'POST',
data: {
'subject': subject
},
success: function(response) {
alert(response);
}
});
});
});
How can I send input values through AJAX on button click? My code is below. Thanks in advance.
while
{
<form class="commentform">
<input type="hidden" class="proid" name="proid" value="<?=$rr['id']?>">
<input type="text" class="form-control" name="comval" placeholder="Write a comment.." autocomplete="off">
<button class="btn btn-post" type="button">Post</button>
</div>
</form>
}
$(document).ready(function() {
$(document).on('click', '.btn-post', function(){
var thePostID = $(this).val;
$.ajax({
url: 'fetch_comments.php',
data: { postID: thePostID },
type: 'POST',
success: function() {
alert(data);
}
});
Firstly, the correct method is $(this).val(), not just $(this).val.
Secondly, you can simplify your code by getting the data from the closest form element using serialize(). Try this:
$(document).on('click', '.btn-post', function() {
var $form = $(this).closest('form');
$.ajax({
url: 'fetch_comments.php',
data: $form.serialize(),
type: 'POST',
success: function() {
alert(data);
}
});
});
$("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.
I am working on a login form that gets loaded inside a div (parent of .messageboxcontent) with .load on a button press. It all works till the 3rd time I press submit where the div disappears again (I guess by reload of the page and the div CSS is hidden). The URL has the $_POST data added after the 3rd submit (?username=<whatever_I_Fill_In_As_3rd>).
<div class="messageboxcontent">
<form id="ajaxform">
<table>
<tr>
<td>Gebruikersnaam: </td><td><input type="text" name="username" /></td><td>
</tr>
</table>
<input type="submit" value="Registreer" id="submit" />
</form>
</div>
<script>
$('form').on('submit', function( event )
{
var dataString = $(this).serialize();
event.stopPropagation();
//event.preventDefault();
$.ajax(
{
type: "POST",
url: "register.php",
data: dataString,
success: function(response)
{
$('.messageboxcontent').html(response);//FIXED by changing .messageboxcontent to parent.
}
});
return false;
});
</script>
I tried different kind of approaches like:
$('form').submit(function(event) {
//..
}
//
$('#ajaxform').submit(function(event) {
//..
}
//
$(document).ready(function()
{
$("#ajaxform").on("submit", function( event )
{
var dataString = $(this).serialize();
//event.stopPropagation();
event.preventDefault();
$.ajax(
{
type: "POST",
url: "register.php",
data: dataString,
success: function(response)
{
$("div.messageboxcontent").html(response);
}
});
return false; //with and without this.
});
});
Be consistent with quotes. Also close your div (<div class="messageboxcontent"></div>)
Try this:
$(document).ready(function(){
$("#ajaxform").on("submit", function( event ){
var dataString = $(this).serialize();
event.preventDefault();
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
success: function(response)
{
$("div.messageboxcontent").html(response);
}
});
return false;
});
});
Hope that helps.
return false; or event.preventDefault(); inside your ajax function would stop the page from reloading.
Secondly, jQuery works with selector methods via class or id - so, in your case, you will want to use $('#ajaxform').
Lastly, the possible reason why you are facing with unexpected result like after 3rd time is because your form is wrapped inside a div that you want to manipulate the result. So, try rewrapping your DIV element to this: <div class="messageboxcontent"></div> and have your <form> stand on its own separately from messageboxcontent div.
I'm trying to get data via ajax then send it through a form. However it doesn't seem to be working. Any ideas what im doing wrong?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<form method="get" action="test.php">
<input id="myvar" type="hidden" name="albumid" />
<button type="submit" id="btnsubmit">Submit</button>
</form>
<script type="text/javascript">
$('form').submit(function() {
$.ajax({
url: "newAlbum.php",
success: function(data){
var album = data;
$('#myvar').val(album);
}
});
});
</script>
newAlbum.php
<?PHP echo '11'; ?>
test.php
<?php echo $_GET["albumid"]; ?>
Okay try adding as follows:
$('form').submit(function() {
$.ajax({
url: "newAlbum.php",
async:false,
success: function(data){
var album = data;
$('#myvar').val(album);
}
});
});
As someone else pointed out - you need to add the data parameter. But I would also use $(this).serialize(), since that will fetch all form input elements.
<script type="text/javascript">
$('form').submit(function() {
$.ajax({
url: "newAlbum.php",
data: $(this).serialize(),
success: function(data){
var album = data;
$('#myvar').val(album);
},
error : function(data) {
console.log(data);
}
});
});
</script>
Try receiving the data as JSON
$.getJSON()
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);
}
});