jquery is resetting my div content - php

I'm trying to change the content of div using jquery. but the content flashes and resets the div. i cannot use return false; because there is another button for post text field value. i want to keep the changes of div. here is my code:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div>
<form id="form" method="POST">
<input type="text" name="gname" id="gname"/></br>
<button id="btn">Set</button>
<button id="nbtn">View</button>
</form>
</div>
<div id="outp">
</div>
</body>
<script>
$("#btn").click(function(event) {
$.post("send.php", {
named: $("#gname").val()}, function(data) {
alert(data);
});
});
</script>
<script>
$("#nbtn").click(function(e) {
$("#outp").html("<?php include './view.php'; ?>");
});
</script>

It's not jQuery; it's that your form is being posted. So your change is made, but then the form is posted and the page is refreshed from the server.
The default type of button elements is "submit". To make one or both of those buttons just a button, use type="button".
Alternately, if you want to allow the form to be used when JavaScript is disabled (e.g., allow it to be posted normally), leave the buttons as submit buttons but prevent form submission using JavaScript. E.g.:
$("#form").submit(false); // Prevents the form being submitted in the normal way.

Any buttons inside a form are considered submit buttons.
So you need to add event.preventDefault() to your .click code.
Also, why are your scripts outside body section?

You can try with ajax and catch success and error:
$("#btn").click(function() {
var named: $("#gname").val();
$.ajax({
url: 'send.php',
type: 'POST',
data: {param1: 'value1'},
})
.done(function(data) {
console.log("Post success"+data);
})
.fail(function() {
console.log("Post error"+data);
});
});

Related

Problems in submitting form data using ajax

i am new in ajax. i am aware to html,php. i want to do the CRUD operation in ajax. i have created a two file
index.php
insert.php as below.
when i click on submit button it submit data and inserted in database. But it resfresh the page. please suggest me that where i made mistake.
my code as below:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</head>
<body>
<form id="contactForm1" action="insert.php" method="post">
<label>Name</label><input type="text" name="user_name"><br>
<label>Age</label><input type="number" name="user_age"><br>
<label>Course</label><input type="text" name="user_course">
<br>
<input type="submit" name="sumit" value="submit">
</form>
</body>
</html>
insert.php
<?php
$conn = mysqli_connect("localhost", "root", "" ,"aj");
$name = $_POST['user_name'];
$age = $_POST['user_age'];
$course = $_POST['user_course'];
$insertdata=" INSERT INTO test3 (name,age,course) VALUES( '$name','$age','$course' ) ";
mysqli_query($conn,$insertdata);
?>
Close the script tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Use when document is ready
$( document ).ready(function() {
var frm = $('#contactForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
frm[0].reset();
alert('ok');
}
});
ev.preventDefault();
});
});
The ready event occurs when the DOM (document object model) has been
loaded. Because this event occurs after the document is ready, it is a
good place to have all other jQuery events and functions. Like in the
example above. The ready() method specifies what happens when a ready
event occurs.
The JavaScript code, binding the event handler, is executed too early. The DOM is not fully loaded yet so the form can't be found. jQuery doesn't warn about this.
Either wrap your code in jQuery's on doc loaded method $(function(){ /* code here */ } ).
Or/and move your JavaScript to the bottom of your HTML. This is a preferred method. See Benefits of loading JS at the bottom as opposed to the top of the document for more details
There is no mistake. Technically, its correct. It's just not fitting in your use-case.
It's default behaviour that page refreshes when user submits form.
You have two options:
Stop further execution when your ajax call is completed. You can do this by javascript by using preventDefault method. Then, use return false.
Change the submit button to normal button. In other words, don't submit form normal way. Give an id to normal button and call javascript function upon its click.

Form submit supposed to refresh only Div, but instead refreshes Page

I have a PHP page included called 'leaguestatus.php'. This page allows the user to post a message/status update and the intent is to have only this part of the div refreshed; however, on submit, the entire page is reloaded.
In the current implementation I'm simply printing all the $_POST variables to the div so I can see what's coming through. The MsgText textarea DOES get posted, however, it's only after the whole page loads. I'm trying to get just the div and that included file to reload.
div id="statusupdates"><? include 'leaguestatus.php'; ?></div>
leaguestatus.php
<form id="statusform" method="POST">
<textarea name=MsgText rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
<? print "<pre>POST Variables:<BR>";
print_r ($_POST);
print "</pre>";
$MsgText = $_POST["MsgText"];
?>
</div>
The jQuery I'm running in the header is:
$(document).ready(function() {
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl) {
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response) {
$("#formbox").html(response);
}
}).success(function(){
});
}
});
Here are my includes:
html header
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
Edit: updated code to reflect use of #sazedul's response. Only issue now is on first click page acts as expected (no page refresh). On second click the entire page reloads. On third click we're back to normal.
Use this following code for ajax submit hope it will work.
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl)
{
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response)
{
$("#formbox").html(response);
}
});
}
Made the following changes in your leaguestatus.php remembar to put double quote in the name="MsgText" in text area.
<form id="statusform" method="POST">
<textarea name="MsgText" rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
</div>
<?php
if(isset($_POST['MsgText'])){
$message=$_POST['MsgText'];
echo $message;
}
?>
check for .load() like the code below....
$(document).ready(function() {
$("#statusform").submit(function() {
$("div").load();
});
});
You have to preventDefault of submit then other thing
so,you have to use e.preventDefault() to prevent submit.then do what ever you want
$("#statusform").submit(function(e) {
e.preventDefault();
......

Cant .ajax() submit a php form that has been loaded onto main page with jQuery .load()

I'm having the following problem. Below is an explanation of what my PHP pages are and how they work. When I access form.php directly and try to submit it via AJAX, it works perfectly.
Problem - When I .load() form.php into main.php, none of the jQuery code within form.php fires. (verified through firebug) No submits, no alerts, nothing. How can I get the jQuery code within form.php to work when its loaded into main.php?
main.php -> This is the main PHP page which has a link on it. Once this link is clicked, the following jQuery code fires to load "form.php" within a div called #formcontainer. This is the code within main.php that loads form.php.
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php");
});
});
</script>
form.php -> this is a form that gets loaded above. It submits data to MySQL through an jQuery .ajax() POST. Here is the jquery code which submits the form, which has an ID called #homeprofile.
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$(document).ready(function() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
});
Use on() for this like,
$(document).on('submit','#homeprofile',function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
return false;
});
You should be using the .on() syntax for targeting dynamically created elements (elements loaded into the DOM by JS or jQuery after the initial rendering)
Good
// in english this syntax says "Within the document, listen for an element with id=homeprofile to get submitted"
$(document).on('submit','#homeprofile',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Not as good
// in english this syntax says "RIGHT NOW attach a submit listener to the element with id=homeprofile
// if id=homeprofile does not exist when this is executed then the event listener is never attached
$('#homeprofile').on('submit',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Hopefully this helps!
Small issue is that you reference formcontaineropen in the jquery call (this is probably a typo?). The cause is that that a JS code loaded via AJAX will get interpreted (therefore eval() is not needed) but the document ready event will get triggered immediately (which may be before the AJAX loaded content is actually inserted and ready in the document - therefore the submit event may not bind correctly). Instead you need to bind your code to success of the AJAX request, something like this:
main.php:
<html>
Foobar
<div class="formcontainer"></div>
<script src='jquery.js'></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontainer").load("form.php", '',
function(responseText, textStatus, XMLHttpRequest) {
onLoaded();
});
});
});
</script>
form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type="text/javascript">
function onLoaded() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
};
</script>
My solution is somewhat peculiar but anyhow here it is.
This would be your main.php:
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php", '', function(response){
var res = $(response);
eval($('script', res).html());
});
});
});
</script>
And this is your form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
</script>

JQuery and AJAX post to php without reloading page in Wordpress

I'm developing a plugin in Wordpress and am having difficulty trying to post data to a separate PHP file using Ajax without reloading the page. On the backend, the PHP file is relying on if( isset() ) to execute an SQL query. On the client side, the user should see individual records fadeOut and a message that records were successfully deleted.
UPDATE: The javascript is working so far, once the form button is clicked, the correct div-s fade in and fade out. However, the PHP file is not getting any value posted to it, as tested with a var_dump.
HTML Code:
<!-- problem: when setting "action" to a url, that page is automatically loaded. I want to stay on the existing page. -->
<form action='' id='form-delete-assoc' method='post'>
<input name='remove_all' type='submit' id='remove-all' value='Remove All'></input>
</form>
JQUERY: (updated with some fixes suggested by answerers)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('tr.assoc_row').show();
$('#settings-removed-msg').hide();
$('#new-assoc-msg').hide();
$('#formdeleteassoc').submit(function(e){
e.preventDefault();
$.ajax ({
type: 'POST',
url: '<?php echo $cb_t2c_remove_all_url; ?>',
data: {removeall: 'yes'
},
success: function() {
$('#settings-removed-msg').fadeIn('fast');
$('tr.assoc_row').fadeOut('fast');
}
});
});
$('#formsavesettings').submit(function(){
$('#new-assoc-msg').fadeIn('fast');
});
});
</script>
remove_all.php:
<?php
//remove_all.php
global $wpdb;
$prefix = $wpdb->prefix;
$remove_var_dump = $_POST['removeall']; //returning NULL
var_dump($remove_var_dump);
if ( isset( $_POST['removeall'] ) ){
$wpdb->query("DELETE FROM ".$prefix."cb_tags2cats");
}
?>
Like the others said, you need to either return false or use preventDefault(). You should also move your calls to fadeOut and fadeIn into the success callback. If you don't and the request is unsuccessful for some reason, the user may be misled into thinking it was successful.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('tr.assoc_row').show();
$('#settings-removed-msg').hide();
$('#form-delete-assoc').submit(function(e){
// prevent the form from submitting normally
e.preventDefault();
$.ajax ({
type: 'POST',
url: '/delete-assoc.php', // Relative paths work fine
data: { removeall: 'delete-all' },
success: function(){
$('tr.assoc_row').fadeOut('slow');
$('#settings-removed-msg').fadeIn('slow');
}
});
});
});
</script>
Your form submit event needs to return false, to stop the form from actually submitting.
$('#form-delete-assoc').submit(function(){
... rest of your code here...
return false;
}
to post data to a separate php page without reloading current (parent or top) page, create a hidden iFrame and use it as the submit target. this type of solution allows posting and retrieving json responses. this snippet uploads a file to a php page.
<script type="text/javascript">
function init() {
document.getElementById('file_upload_form').onsubmit=function() {
document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe
}
}
window.onload=init;
</script>
</head><body>
<form id="file_upload_form" method="post" enctype="multipart/form-data" action="upload.php">
<input name="file" id="file" size="27" type="file" /><br />
<input type="submit" name="action" value="Upload" /><br />
<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
this tutorial explains the process step by step ->
http://www.openjs.com/articles/ajax/ajax_file_upload/
follow up on how to parse the response ->
http://www.openjs.com/articles/ajax/ajax_file_upload/response_data.php

replacing div content after form submission

I have a div with a form in it. After a user submits the form, I want to load new content into the div, replacing the form.
The new content will be static.
Do I need AJAX for this?
you don't HAVE to use ajax for this, after submitting the form you can issue a redirect to a static page without the form(post-redirect-get pattern).
But note that in this case the entire page will refresh while submitting,
and if the submit might fail from some reason(who said validation), hitting F5 will pop up the ugly "do you want to send crap..."
so no, you don't have to use ajax, but it is so easy with the form plugin that it is a crime not to.
if you do use the form plugin, then at the success callback hide the form with the static content
You do need Ajax: (I'll do it like SimpleCoder said, but with the ajax call)
$('#myForm').submit(function(){
var field1 = $("#field1").serialize(); // If this doesn't work just remove the serialize()
var field2 = $("#field2").serialize();
$.ajax({
type: "POST",
url : "???", //your processing page URL instead of ???
data: "&field1="+field1+"&field2="+field2,
success: function(){
$("#formHolder").html("Your static content");
}
});
});
( You should replace field1, field2 with your fields, and if it doesn't work, remove the serialize() function. )
All you have to do is .html() the static content in the success function of the ajax call.
Assuming your HTML looks something like this:
<div id="formHolder">
<form id="myForm">
...
</form>
</div>
Do something like this:
$("#myForm").submit(function(){
$("#formHolder").html("Your static content");
});
You can find an example of this here
https://www.write-about-property.com/seo-services/ the code to work on the form submit uses an instance of the object created in form.js
If you have a crack at it then come back we will help you perfect it for your purpose. You would put the div you wanted to update in the toupdate var
ajform.toupdate = $("#update")
you can simply make the divs invisible, and the submit button is just a button with js action to make the div visible
<script type="text/javascript" language="javascript">
function step2() {
document.getElementById('step1_container').style.display = 'none';
document.getElementById('step2_container').style.display = 'block';
}
function step3() {
document.getElementById('step2_container').style.display = 'none';
document.getElementById('step3_container').style.display = 'block';
}
</script>
...
<form action="validate.php" method="post">
<div id="step1_container">
PAGE 1 here
<input type="button" onclick="javascript:step2();" value="submit"/>
</div>
<div id="step2_container" style="display: none;">
Page 2 here
<input type="button" onclick="javascript:step3();" value="submit"/>
</div>
<div id="step3_container" style="display: none;">
Page 3 here
<input type="button" onclick="javascript:step4();" value="submit"/>
</div>
</form>
And so on
You don't need ajax, using only on-page javascript would be enough.
However, with ajax you can display the content from the page you're submitting the form to.
Try the jQuery From plugin for an elegant ajax solution:
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
});
});
</script>

Categories