Use AJAX/JQuery to submit form and show results without reload - php

Im trying to use jquery and ajax to submit a form and show the results without reloading. Like your typical ajax commenting setup.
My HTML is setup like this:
<form id="create_new_heading" action="/display.php?brand=1" method="post">
<label for="entry">Heading:</label><br/>
<input type="text" id="heading" name="heading" maxlength="150"/><br/>
<input type="submit" value="Add this Heading" />
</form>
<div id="result">
</div>
JS:
<script>
/* attach a submit handler to the form */
$("#create_new_heading").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="heading"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post and put the results in a div */
$.post( url, { s: term },
function( data ) {
var content = $( data ).find( '#test_me' );
$( "#result" ).empty().append( content );
}
);
});
</script>
Form Processor looks like this:
public function write($p) {
if ( $_POST['type'] )
$type = mysql_real_escape_string($_POST['type']);
if ( $_POST['heading'])
$heading = mysql_real_escape_string($_POST['heading']);
if ( $type && $heading ) {
$uniqueid = uniqid();
$sql = "INSERT INTO headings VALUES('$type','$heading','$uniqueid')";
return mysql_query($sql);
} else {
return false;
}
}
I attempted to follow the jquery documentation for implementing this but I can't seem to get it to work. The form submits, and the entry gets put into the database but I still have to refresh the page to see the new entry. Any idea of what I am doing wrong?

Can you check on firebug, whether caching is screwing the request.
I had a similar problem and started giving a random_id along with the param and
it worked fine.
Proper way could be enable Cache-Control header (or) setting a past time as expiry time.

Why not take out the .empty()
$( "#result" ).append( content );
Or try
$( "#result" ).html( content );

Related

Contact form 7 - URL redirection

As you guys know in CF7 on_sent_ok command deprecated and scheduled to be abolished by the end of 2017. So I decided to use the new script for redirecting my contact forms with this script provided by CF7
function add_this_script_footer(){ ?>
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
location = 'http://websiteurl/thank-you';
}, false );
</script>
<?php }
add_action('wp_footer', 'add_this_script_footer');
but this applies to all contact forms. Since I am using quite different types of forms, may I know how can I exclude one of them from this redirection?
Try this script:
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
if (event.detail.contactFormId != '123') { // This would exclude form with id 123
location = 'http://websiteurl/thank-you';
}
}, false );
</script>
Bonus tip: I often do it another way that makes it a bit more flexible. I put a <div class="do-some-action" data-something="foobar" style="display:none;"></div> in the CF7 form itself and then I can put this action in multiple forms if needed..
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
var $cf = $( '#' + event.detail.id );
var $actionDiv = $cf.find( '.do-some-action' );
if ( $actionDiv && $actionDiv.length ) {
// Div with action class found
// We can also extract some data if needed
var something = $actionDiv.data( 'something' );
console.log( 'something = ' + something );
location = 'http://websiteurl/thank-you';
}
}, false );
</script>
I hope this helps!

ajax php post on clicking outside div

I want to post something after writing it into a textarea without clicking any button but on clicking outside the textarea..How can I achieve that?? My code...
<form action="javascript:parseResponse();" id="responseForm">
<textarea align="center" name="post" id="post">Write something</textarea>
<input type="button" id="submit" value="submit" />
</form>
AJAX:
$('#responseForm').submit(function({$('#submit',this).attr('disabled','disabled');});
function parseResponse(){
var post_status = $("#post");
var url = "post_send.php";
if(post_status.val() != ''){
$.post(url, { post: post_status.val()}, function(data){
$(function(){
$.ajax({
type: "POST",
url: "home_load.php",
data: "getNews=true",
success:function(r)
{
$(".container").html(r)
},
})
})
document.getElementById('post').value = "";
});
}
}
I want to remove the button...and when an user clicks outside the textarea it will automatically submit the information...The whole body outside the textarea will act as the submit button...when user writes any info on the textarea...How can I achieve that??
Try the following:
$(document).on("click", function(e) {
var $target = $("#YOUR_ELEMENT");
if ($target.has(e.target).length === 0) {
your_submit_function();
}
});
You could also attach your submit function to the blur event for improved functionality:
$(document).on("click", function(e) {
var $target = $("#YOUR_ELEMENT");
if ($target.has(e.target).length === 0) {
your_submit_function();
});
$("#YOUR_ELEMENT").on("blur", function() {
your_submit_function();
});
You can attach a click handler to the entire document, and then cancel the event if the user clicked inside the text area. Something like this might do the trick:
$( document ).on( "click", function( ev ) {
if( $( ev.target ).index( $( "#post" )) == -1 ) {
// User clicked outside the text area.
}
} );
I use code similar to this to accomplish essentially the same thing (check when a user clicked outside of something). This is a copy and paste (slight alterations) of that code, and I haven't tested for your purposes. Essentially, it adds a handler to the entire document for the click event, then only executes the code if the element clicked on was not your textarea.

CKEditor submit value empty (no ajax)

I have a problem with the ckeditor. I downloaded the current version and included it to my form as follows:
<form action="/news.php?frame=edit&id=185" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<textarea class="edit" name="news_content" id="news_content" rows="30" cols="32" style="width:95%;">{$news_content}</textarea>
<script type="text/javascript" src="ext/ckeditor/ckeditor.js"></script>
<script type="text/javascript">
CKEDITOR.replace( 'news_content' )
</script>
<input type="submit" accesskey="s" value="Eintragen (Alt+S)" class="button">
</form>
It is loaded correctly and I can use the editor to make any changes. However, when submitting the form using a normal submit button (no AJAX or JS at all here), there is no entry "news_content" in the $_POST array, nor is there any other element containing the data at all.
How can I make use of the content after submitting the form using a normal submit button?
Thanks in advance and best regards
Daniel
You have to run a function to update the actual form field, I had the same issue let me find my code. The actual form data doesn't get updated until you run a function to move the CKEditor data into the form field.
function updateAllMessageForms()
{
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
}
This worked for me:
if( $('.ckeditor').length > 0){
$('form').on('submit', function(e){
for (instance in CKEDITOR.instances) {
$('#' + instance).val(CKEDITOR.instances[instance].getData());
}
});
}
i had the same problem in jquery ui dialog. this code has worked for me:
function updateAllMessageForms(){
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
}
CKEditor does do this for you automatically, as far as I know. I ran into the same problem, my POST variable for the textarea was blank. Turned out I had an error in my javascript onsubmit function that did validation. The javascript would error out and the form would be submitted, but the CKEditor code to populate the original textarea would not fire, due to that error.
I looked around in the source code, I think this updates the original textarea on submit:
// Integrate with form submit.
if ( editor.config.autoUpdateElementJquery && $element.is( 'textarea' ) && $( element.form ).length ) {
var onSubmit = function() {
$element.ckeditor( function() {
editor.updateElement();
} );
};
// Bind to submit event.
$( element.form ).submit( onSubmit );
// Bind to form-pre-serialize from jQuery Forms plugin.
$( element.form ).bind( 'form-pre-serialize', onSubmit );
// Unbind when editor destroyed.
$element.bind( 'destroy.ckeditor', function() {
$( element.form ).unbind( 'submit', onSubmit );
$( element.form ).unbind( 'form-pre-serialize', onSubmit );
} );
}

jQuery UI Tabs and PHP Forms in Tabs

I am having an issue submitting $_POST Data from a form located in a tab and updating the tab with the expected $_POST Data.
I am using jQuery-UI Tabs to load different portions of a script through Ajax.
Here are my Navigation Tabs:
<div id="tabs" style="width:970px;">
<ul>
<li>Cl Total</li>
<li>Rental Leads Export</li>
<li>Sphere Count Statistics</li>
<li>E-Campaign Statistics</li>
</ul>
</div>
Here is my jQuery Code:
jQuery(document).ready(function() {
jQuery("#tabs").tabs({
spinner:'<b>Retrieving Data...</b>',
ajaxOptions: {
data: { $_POST: getVariable
},
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"error occured while ajax loading.");
},
success: function( xhr, status ) {
//alert("ajax success. "); //your code
}
}
});
jQuery('#tabs ul li a').click(function () {location.hash = jQuery(this).attr('href');});
primeDateInputElements();
});
Inside the AjaxFunctions file I have a switch statement to load the correct include depending on the tab selected.
$p = $_GET['mgmtDbrdPge'];
switch($p) {
case "1": default:
$page = 1;
break;
case "2":
$page = 2;
break;
case "3":
$page = 3;
break;
case "4":
$page = 4;
break;
}
include("path/to/file/fileToInclude.include.php");
Inside this file I have a form that looks similar to this. When the form is submitted, it should reload the tab with the POST data loaded so that the next function can be executed. However no POST data is being loaded at all.
echo '<form name="CityExport" action="/managementDashboard#visibleTab-2" enctype="multipart/form-data" method="post">' . chr(10);
echo '<input type="hidden" name="mode" value="submitNorthShoreExport" />' . chr(10);
echo '<input type="submit" value="North Shore Export" id="submitButton">' . chr(10);
echo '</form>';
How do I go about doing this?
I have figured it out. The best way to do it is to set an id to each of the forms and have it reload the div with current results.
jQuery("form#ajaxForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* Send the data using post and put the results in a div */
jQuery.post( '/postpage', jQuery("#ajaxForm").serialize(),
function( data ) {
var content = jQuery( data ).find( '#content' );
jQuery( "#visibleTab-2" ).empty().append( data );
}
);
})

jquery/ ajax callback doesn't fire twice without a page reload. Part 1

I'm learning how to apply ajax to my jquery/php/mysql script for the purpose of callback firing. This question is probably from my ignorance when it come to the name of this term.
The Question: Is there a way to reset ajax callback without reloading the page script.
The Goal: I have a mysql query displaying on jQuery Accordian 1, 2, and 3. The goal is to click a query result href from Accordian and display the results in jQuery UI Tab 3 without a page reload...So far the script fires on my first callback but it doesn't fire a second time. Is there a term or jquery command that will reset jquery/ajax?
index.php
<?php
...script... include'right.content.php';
?>
<script type="text/javascript" >
$(function() {
$("#submit").click(function(){ // when submitted
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load('test.arena/test.php', {'string2':name, 'string3':lname,} );
});
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});
</script>
index.php - html section
<div id="stage">
<?php include'test.arena/test.php';?>
</div>
right.content.php
while ($row = mysql_fetch_array($result)){
if($row['stats'] == "1"){
$data .= "<tr><td colspan='2'>".$row['order_number']."</td>
<td colspan='2'>
<input type='hidden' id='string3' value='".$row['details']."'>
<input type='hidden' id='string2' value='".$row['order_number']."'>
<input type='button' id='submit' value='View'></td>
<td>info</td></tr>";
test.arena/test.php
if(!isset($_POST['string2'])){
$_POST['string2'] = "";
}else{
$string3 = "PO Number:" .$_POST['string3'];
$string2 = "Order:" .$_POST['string2'];
echo $string3 ."</br>";
echo $string2 ."</br>";
}
Is the element with ID 'submit' inside the one with ID 'stage'? If so, try changing $("#submit").click(function(){ to $("#submit").live('click', function(){.
The problem is probably because your submit button is inside of the 'stage' div. This means that when you load the new 'stage' content, it will delete the old button and add a new one and the new one won't have any click thing attached.
The quick fix for this is to use a 'live' handler.
$(function() {
$("#submit").live('click', function(){ // when submitted
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load('test.arena/test.php', {'string2':name, 'string3':lname,} );
});
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});
But the other solution, which might make the problem clearer, is to re-add the click handler after the load finishes.
$(function() {
function submitClicked() {
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load(
'test.arena/test.php',
{ 'string2':name, 'string3':lname },
function() {
addClickHandler();
}
); // display results from test.php into #stage
}
function addClickHandler() {
$('#submit').click(submitClicked);
}
addClickHandler();
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});

Categories