I am trying to submit data to the db without refreshing the page using jquery and php
But I guess there is something I get wrong in my code , its works nicely if I do not apply Jquery :
Bellow is my code am using .
<!---Insert into database -->
<script type="text/javascript">
$(document).ready(function () {
$('.chatbutton').click(function () {
$.ajax({
type: 'post',
url: "insertchatmessages.php",
success: function () {}
});
});
});
</script>
<!---Insert into database ends here -->
</head>
<body>
<table class="chattable" id="chattable" border="0">
<tr><td><div id="load_tweets">
</div></td></tr>
<form id ="chatform" action="?" method="post"></td></tr>
<tr><td><input class ="chattext" type ="text" name="message"></td></tr>
<tr><td><input class="chatbutton" class="chatbutton" type="submit" value="send" name ="submit">
</div>
</table>
HTML (this is derived from your code but modified to work in jsfiddle):
<table class="chattable" id="chattable" border="0">
<tr>
<td>
<div id="load_tweets"></div>
</td>
</tr>
<tr>
<td>
<form id ="chatform" action="/echo/html/" method="post"> <!-- your action should point to your php (insertchatmessages.php) -->
<input type="hidden" name="html" value="This is sample text to show that this works!"/> <!-- for jsfiddle test only. remove this in your code. -->
<input class ="chattext" type ="text" name="message" />
<input class="chatbutton" class="chatbutton" type="submit" value="send" name ="submit" />
</form>
</td>
</tr>
</table>
jQuery:
$(document).ready(function(){
$('#chatform').submit(function(e){
e.preventDefault();
var $form = $(this),
data = $form.serialize();
$.ajax({
data: data,
type: $form.attr("method"),
url: $form.attr("action"),
success: function(data){
$("#load_tweets").html("<p>"+data+"</p>");
}
});
});
});
Working example: http://jsfiddle.net/darshanags/6vxMs/6/
Notes: I have made slight modifications to your code to make it work on jsfiddle, you will have to change it back to make it work in your setup.
.chatbutton is a submit button. When you click it, the jQuery handler fires, and then the form submits (which is the browser's default behavior). In your jQuery script you must call preventDefault():
$('.chatbutton').click(function(e){
e.preventDefault();
// rest of your code
Better, assign a handler to the form submit function (but still you need to prevent default behavior).
Use submit jquery function.
$('#chatform').submit(function() { });
Complete JS Code
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
$('#chatform').submit(function (e)
{
e.preventDefault();
$.ajax({
type: 'post',
url: "random.php",
success: function (response)
{
//do after response.
}
});
});
});
</script>
jQuery serialize will be helful
<script type="text/javascript">
$(document).ready(function () {
$('.chatbutton').click(function (e) {
e.preventDefault();
$.ajax({
data: $('chatform').serialize(),
type: 'post',
url: "insertchatmessages.php",
success: function () {}
});
});
});
</script>
Simple user e.preventDefault() in start of your onclick call, it is used when you want to stop the default behavior:
<script type="text/javascript">
$(document).ready(function (e) {
$('.chatbutton').click(function () {
e.preventDefault();
$.ajax({
type: 'post',
url: "insertchatmessages.php",
success: function () {}
});
});
});
</script>
Related
i have a form and i wanna use jQuery with it. but when i submit it it just doesnt use the code at all.
<form id="form">
<label>Name</label><br />
<input type="text" name="name"><br /><br />
<label>Message</label><br />
<textarea name="message"></textarea><br /><br />
<button type="submit">Submit form</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous">
//have to use jQuery to get the form data
jQuery(document).ready(function($){
$('#form').submit(function(e){
e.preventDefault();
alert('hello');
var data = $(this).serialize();
$.ajax({
url: 'http://localhost:8888/wp-json/v1/contact_form/submit',
type: 'POST',
data: data,
success: function(response){
console.log(response);
}
});
});
});
</script>
i used a alert to see if it works but it just does nothing.
when i submit i get to a blank page. so the e.preventDefaults also doesnt work.
i tried using copilot but it didnt do anything usefull
You must declare your scripts in different tags.
<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script>
<script>
//have to use jQuery to get the form data
jQuery(document).ready(function($){
$('#form').submit(function(e){
e.preventDefault();
alert('hello');
var data = $(this).serialize();
$.ajax({
url: 'http://localhost:8888/wp-json/v1/contact_form/submit',
type: 'POST',
data: data,
success: function(response){
console.log(response);
}
});
});
});
</script>
I am trying to insert a name into my database. There is a form asking to enter name.There is also a submit button.on clicking the submit button no alert is show.I am new to ajax.
this is index.php.
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").submit(function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: "name=" + name,
success: function() {
alert("sucess");
}
});
});
});
</script>
</head>
<body>
<form action="" method="post">
Name:
<input type="text" name="name" id="name" />
<br />
<input type="submit" name="submit" id="submit" />
</form>
</body>
</html>
This is ajax.php
<html>
<body>
<?php
$query=mysql_connect("localhost","root","root");
mysql_select_db("freeze",$query);
$name='l';//$_POST['name'];
mysql_query("insert into tt values('','$name')");
?>
</body>
</html>
Be careful with url's in ajax. Your url is 'ajax.php', this is a relative url, so, if your page is at url http://localhost.com/index.html (for example), ajax will fire a post to http://localhost.com/index.html/ajax.php (and that's probably wrong). Try use absolute url, for that, add '/' at begin of url, then ajax will be fired against http://localhost.com/ajax.php.
Your ajax code should look like code below:
$(document).ready(function() {
$("#submit").submit(function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "name=" + name,
success: function() {
alert("sucess");
}
});
});
});
The submit event is triggered on the form, not the submit button. So
$("#submit").submit(function() {
will not ever be triggered, because #submit selects the button, not the form. You need to give an ID to the form:
<form id="myform">
then use
$("#myform").submit(function() {
You also need to use event.preventDefault() or return null in the event handler, to prevent the form from being submitted normally when the function returns.
First of all I'm sorry if my English isn't totally correct.
I'm learning to use json and I want to try with this simple code, where I insert name and surname and with Ajax I send them to a json struct for then show them in a table.
ajax.php
<form id="iscrizione">
Nome: <input type="text" id="nome" /><br />
Cognome: <input type="text" id="cognome" /></br >
<input type="submit" id="invia" value="ISCRIVITI" />
</form>
<table>
<tr><td>Nome: </td><td><span id="td_nome"></span></td></tr>
<tr><td>Cognome: </td><td><span id="td_cognome"></span></td></tr>
</table>
<script type="text/javascript">
$("#iscrizione").submit(function(){
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("span#td_nome").html(msg.nome);
$("span#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
});
</script>
json.php
<?php
header("Content-Type: application/json", true);
$dati = array( 'nome'=>$_POST['nome'], 'cognome'=>$_POST['cognome'] );
echo json_encode($dati);
?>
Where are the mistakes? Because the outputs are shown for just a second and then they will disappear.
Thank you to everybody.
When you submit the form it will reload all page again, so assigned html visible for short time only.
Use preventDefault() function to overcome this situation.
<script type="text/javascript">
$("#iscrizione").submit(function(event){
event.preventDefault()
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("span#td_nome").html(msg.nome);
$("span#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
});
On submitting form, it will reload page by default. We can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler. Read more about .submit() event.
1.On using returning false after ajax call.
$("#iscrizione").submit(function(){
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
....
....
});
return false; // add return false here
});
2.By using event.preventDefault()
$("#iscrizione").submit(function(event){
event.preventDefault();// use preventDefault() on event
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
....
....
});
});
Either return false or preventDefault() will work, as the other two answers have described. However, it's important to understand that you don't have to submit the form at all, and indeed it isn't best practice to do so. After all, it doesn't make much sense to use HTML to submit the form and then disable the submit behavior in your code. Especially when you don't have to.
AJAX was invented to overcome the problems (such as yours) that result when you reload the page. The point about AJAX is that it gives you the ability to update your page with new data without reloading it.
So, the cleaner way to do what you want is to make your button simply a button, and call your code from the button's click event. Have a look at this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Test
</title>
<!--jQuery file-->
<script src="includes/jquery/jquery-2.2.3.js"></script>
<script type="text/javascript">
$(document).ready(function () {
function showMyPHP() {
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("#td_nome").html(msg.nome);
$("#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
}
$('#invia').on('click', function(e, ui){
showMyPHP();
});
});
</script>
</head>
<body>
<form id="iscrizione">
Nome: <input type="text" id="nome" /><br />
Cognome: <input type="text" id="cognome" /></br >
<button type="button" id="invia">"ISCRIVITI"</button>
</form>
<table>
<tr><td>Nome: </td><td><span id="td_nome"></span></td></tr>
<tr><td>Cognome: </td><td><span id="td_cognome"></span></td></tr>
</table>
</body>
</html>
You can see that we're not submitting the form at all here. Rather, we're calling the AJAX through the button's click event. You'll see that you get the results you're looking for, without resorting to using HTML to submit the form and then disabling the default submit behavior in code.
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>
I have a drop down form, which has a list of four choices the user can select from. After selecting the choice
and clicking the "Advertise in Public Chat" button the option value (1, 2, 3, 4) needs to be passed to advertise.php?advertise=1 (2, 3, or 4)
without the page refreshing. After clicking Advertise in Public Chat I would like a message that says "Message sent to Chat!" and the user can click OK.
My issue:
Code will not execute on Firefox or Internet Explorer (I have tried on Debian Linux & Windows PCs-- all share the same result). Works perfectly on Chrome\Opera.
<!DOCTYPE html>
<html>
<body>
<form id="myform" action="" method="post">
<select name="Type">
<option value="1">(1 on 1)</option>
<option value="2">(2 on 2)</option>
<option value="3">(3 on 3)</option>
<option value="4">(4 on 4)</option>
</select>
<input type="submit" value="Advertise in Public Chat">
</form>
<div id="message"><h2>This will change when the request is sent</h2></div>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('form').on('submit', function(){
event.preventDefault();
var myVal = $('select[name="Type"]').val();
$.ajax({
type: "GET",
url: "advertise.php",
data: {
advertise: myVal
}
}).done(function( response ) {
// response is equal to what advertise.php will echo/print
$('#message h2').html("Message sent to Chat!");
});
});
});
</script>
</body>
</html>
If you -submit- a form, the page will be refreshed. You have to stop or prevent default action for the submit event of your form. Here is a example using jquery:
$('#myForm').on('submit', function(e){
e.preventDefault();
// your ajax function
});
Instead of using
<input type="submit" value="Advertise in Public Chat">
You can use
<input type="button" id="submit-btn" value="Advertise in Public Chat">
and for the ajax you can do like this:
$("#submit-btn").click(function(){
$.ajax({
type: "POST",
url: "advertise.php",
data: dataString,
success: function() {
$('#message').html("<h2>Message sent to Chat!</h2>")
}
});
});
});
Like that you will be able to access $_GET['advertise'] in advertise.php
UPDATE
I forgot to put the curly braces in the data declaration in the first time, now it will work
<script type="text/javascript">
$('#myForm').on('submit', function(e){
e.preventDefault();
var myVal = $('select[name="Type"]').val();
$.ajax({
type: "GET",
url: "advertise.php",
data: {
advertise: myVal
},
success: function() {
$('#message').html("<h2>Message sent to Chat!</h2>");
}
});
});
</script>
UPDATE 2
I just tested this in local and it works assuming that advertise.php is at the same level as this file.
<!DOCTYPE html>
<html>
<body>
<form id="myform" action="" method="post">
<select name="Type">
<option value="1">(1 on 1)</option>
<option value="2">(2 on 2)</option>
<option value="3">(3 on 3)</option>
<option value="4">(4 on 4)</option>
</select>
<input type="submit" value="Advertise in Public Chat">
</form>
<div id="message"><h2>This will change when the request is sent</h2></div>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$(document).ready(function() {
$('form').on('submit', function(event){
event.preventDefault();
var myVal = $('select[name="Type"]').val();
$.ajax({
type: "GET",
url: "advertise.php",
data: {
advertise: myVal
}
}).done(function( response ) {
// response is equal to what advertise.php will echo/print
$('#message h2').html("Message sent to Chat!");
});
});
});
</script>
</body>
</html>