JQuery and AJAX post to php without reloading page in Wordpress - php

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

Related

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();
......

jquery is resetting my div content

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);
});
});

JS working locally, but not on webserver - any odd JS quirks I'm missing?

First, let's get this out of the way:
No errors (JS, etc) exist on the local and remote dev page. The jQuery lib is also called correctly.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
Basically both pages are identical.
What I'm trying to have my webpage achieve:
Submit my form if the user (accidentally) clicks away on a link instead of using the normal form submit button.
Link:
<a class="arrow autoSaveLeft" href="<?php echo $prevWeekURL ?>">←</a>
<form>
// ...
<input type="submit" name="submit" class="submitForm" value="Update" />
</form>
JS (at bottom):
<script>
$(document).ready(function() {
$('.autoSaveLeft').click(function(event){
event.preventDefault();
$('.submitForm').click();
window.location = $(this).attr('href');
});
});
</script>
Any idea why this might fire correctly on MAMP (form is submitted and url is followed), but not when I try live on a shared host (form is NOT submitted, but url is followed)?
Thank you.
If you wanted to save your user's progress on a form before leaving, you'd have to submit the form without actually, submitting it via the browser. Thus you could use AJAX to send the information that's been provided so far, upon success - carry on with the href provided on the original .click() handler.
<a class="arrow autoSaveLeft" href="somepage.php">←</a>
<form id="userform">
<input type="submit" name="submit" class="submitForm" value="Update" />
</form>
<script>
$(document).ready(function() {
$(document).on('click', '.autoSaveLeft', function( event ) {
var $that = $(this);
event.preventDefault();
$.ajax({
type: "POST",
data: $('#userform').serialize(),
url: 'yourpostscript.php',
success: function(){
window.location.href = $that.attr('href');
}
});
});
});
</script>

Why can't a submit button send to PHP and jQuery at the same time?

I have this code.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action = "" method = "POST" id = "form">
<img src = "circle.gif" id="loading" style="display:none; "/>
<input type="text" name = "text2">
<input type="submit" name="submit2" value="Send">
</form>
<?
if (isset($_POST['submit2'])){
echo $_POST['text2'];
}
?>
<script>
$('#form').submit(function(e) {
$('#loading').show();
return false;
});
</script>
</body>
</html>
I want to store in my db the value written in the textbox using PHP, and while it's being saved, I want to show a gif using jQuery, once the page is loaded, this gif should be removed.
Then, If I don't comment nothing, gif appears when submit button is submitted but echo fails.
If I comment the jQuery script, PHP echoes the vale written.
If I comment the PHP script, gif is shown but no echo of course...
How could I do what i'm asking. I know that my full script does until only showing the gif, but this without this I can't continue.
You can achieve your desired behaviour, but you need to do it by submitting an AJAX request to the server and then handling the return value. So basically you'd add this ajax request to the click or submit event of the form, and handle the behaviour and request via javascript.
Perhaps something like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action = "formSubmitHandler.php" method = "POST" id = "form">
<img src = "circle.gif" id="loading" style="display:none; "/>
<input type="text" name = "text2">
<input type="submit" name="submit2" value="Send">
</form>
<script>
$(document).ready(function(){
$('#form').submit(function(){
// Show the loading icon before the processing begins
$('#loading').show();
// Send the query/form details to the server
jQuery.ajax({
data: $(this).serialize(),
url: this.action,
type: this.method,
success: function(results) {
// Now that the processing has finished, you
// can hide the loading icon
$('#loading').hide();
// perhaps display some other message etc
}
})
return false;
});
});
</script>
</body>
</html>

submit form using Jquery Ajax Form Plugin and php?

this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>

Categories