jQuery UI Tabs and PHP Forms in Tabs - php

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

Related

Background color set up for dynamically added content via AJAX

I have problem with setting of background color for li elements dynamically added by AJAX.
I cannot use pure css, because it marks also new added item at the end of list.
I tried this solution at the end of code but it is still not working. When I add or delete item via AJAX background color settings will disappear.
$(document).ready(function() {
listItems.eq(0).css({backgroundColor: '#441515'});
listItems.eq(1).css({backgroundColor: '#442415'});
listItems.eq(2).css({backgroundColor: '#443a15'});
});
$(document).ajaxComplete(function(){
listItems.eq(0).css({backgroundColor: '#441515'});
listItems.eq(1).css({backgroundColor: '#442415'});
listItems.eq(2).css({backgroundColor: '#443a15'});
});
Here is jquery part of code:
/*
DELETE ITEM VIA AJAX
*/
// event listener must be attached to todoapp__list which is out of block changed by ajax
todoList.on('click', '.todoapp__list-delete', function(event) {
event.preventDefault();
var stringId = $(this).attr('href');
id = stringId.substring(stringId.indexOf('=') + 1, stringId.indexOf('&') ); // get id number of deleted item from href with url directed to delete-item.php
// id is between first = and first & in url string
// Dialog window confirmation if we want to remove item
var confirmDelete = confirm('Chcete danu polozku naozaj vymazat?');
// if click on yes, then AJAX
if (confirmDelete == true) {
$.ajax({
url: "_inc/delete-item.php", // get url form action parameter of form add-item
type: 'POST', // send data via POST method
dataType: 'json', // received data in format JSON
data: 'id=' + id // posiela data namiesto formulara z html => data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL.
}).done(function (data) {
if (data.status === 'success') { // check if add-item.php show success for process of data insertion to table
// get index.php with actual list of li and append last to end of list
$.ajax({ url: baseURL, }).done(function(html) {
var newList = $(html).find('.todoapp__list-items');
currentList = $('.todoapp__list');
currentList.html(newList);
});
};
});
};
});
Here is HTML code:
<ul class="todoapp__list">
<?php
if ( ! empty($data) ){
foreach ( $data as $item ) {
echo '<li id="item-' . $item['id'] . '" class="todoapp__list-items"><span class="editable-span">' . $item['text'] . '</span>';
echo '<div class="todoapp__list-controls float-right">';
echo 'edit';
echo '<i class="fas fa-times"></i>';
echo '<i class="fas fa-check-circle"></i>';
echo '<i class="fas fa-sort"></i>';
echo "</div></li>";
};
} else {
echo '<span>there are no tasks on your toapp</span>';
};
?>
</ul>
Thank you

jQuery Form Plugin doesn't submit forms per AJAX, it's still reloading the page, why?

Can't seem to get this running, I am using jQuery 3.2.1 together with the jQuery Form Plugin 4.2.1. I also have included the jQuery Cookies Plugin 1.4.1. Now, if I submit a Form, that is called by .ajaxForm(); it doesn't work and still reloads the page and redirects me to the action-path that is included in the form. I tried it with a lower version of jQuery, 1.2 and with that it worked fine. But if I use the older version, some other functions wouldn't work anymore, what's why I need to use the latest one.
Here's my head-tag:
<!--- JQUERY --->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!--- JQUERY FORM PLUGIN --->
<script src="js/de.jqu.form.421.js"></script>
<!--- JQUERY COOKIE PLUGIN --->
<script src="js/de.jqu.cookies.141.js"></script>
<!--- JQUERY MIGRATE --->
<script src="https://code.jquery.com/jquery-migrate-3.0.0.js">
The HTML form:
<form enctype="multipart/form-data" name='imageform' role="form" id="imageform" method="post" action="/functions/c_uploadcans.php">
...
<input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
</form>
And the script I am using to call the .ajaxForm():
(function() {
$('#imageform').ajaxForm({
beforeSubmit: function() {
count = 0;
val = $.trim( $('#images').val() );
if( val == '' ){
count= 1;
$( "#images" ).next('span').html( "Please select your images" );
}
if(count == 0){
for (var i = 0; i < $('#images').get(0).files.length; ++i) {
img = $('#images').get(0).files[i].name;
var extension = img.split('.').pop().toUpperCase();
if(extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){
count= count+ 1
}
}
if( count> 0) $( "#images" ).next('span').html( "Please select valid images" );
}
if( count> 0){
return false;
} else {
$( "#images" ).next('span').html( "" );
}
},
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
success: function(msg) {
},
complete: function(xhr) {
$('#loader').hide();
$('#image_upload').show();
$('#images').val('');
$('#error_div').html('');
result = xhr.responseText;
result = $.parseJSON(result);
base_path = $('#base_path').val();
if( result.success ){
name = base_path+'images/'+result.success;
html = '';
html+= '<image src="'+name+'">';
$('#uploaded_images #success_div').append( html );
} else if( result.error ){
error = result.error
html = '';
html+='<p>'+error+'</p>';
$('#uploaded_images #error_div').append( html );
}
$('#error_div').delay(5000).fadeOut('slow');
}
});
})(jQuery);
Maybe someone finds a mistake, I really have no idea. Thanks in advance.
how are you calling that function. may be its not even called. put that in `
$(document).ready(function()`{ your ajaxForm code });
like this ...
$(document).ready(function() {
$('#imageform').ajaxForm({
beforeSubmit: function() {
count = 0;
val = $.trim( $('#images').val() );
......
......
});
});
hope this works for you
My guess is because in your beforeSend all you are doing is showing the loader and hiding image_upload
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
Shouldn't you be handling ajax post call here as well?

PHP/JQUERY label to input in while loop on edit button click

I'm using php/jquery and html my requirement is when I click on edit button, label should be replaced with input text and I would be able to update in my mysql db and if I click on cancel button input to label..
Following is my code:
<?php
$sql = 'select * from demo';
while($row = mysql_fetch_object($sql)) {
?>
<label style="display:block;">abc</label>
<input type="text" style="display:none;"/>
<button id="edit">edit</button>
<button id="cancel">cancel</button>
<?php
}
?>
suppose If I display 10 records from mysql db, for each record I should be able to edit on particularly clicked row.
Any help is appreciated thanks!
I would wrap each label in a parent (for example a p).
On a click, you hide the label and add a input and two buttons to the parent.
By clicking the cancel button, the label gets visible again and the other elements will be removed.
The "tricky" part is the submit button. You'll need a PHP page that processes the data you post to it. Then when it succeeds you should echo an ok . The $.post function knows a success argument. This function will check if the returned value will be ok, and if so, changes the text from the label, shows it, and removes the other items.
$(function() {
$('.edit').on('click', function(e) {
e.preventDefault();
var elem = $(this) ,
label = elem.prev('label') ,
parent = elem.parent() ,
value = label.text() ,
input = '<input type="text" value="'+value+'" />' ,
save = '<button class="save">Save</button>' ,
cancel = '<button class="cancel">Cancel</button>';
parent.children().hide();
parent.append(input+save+cancel);
});
$(document).on('click', '.cancel', function(e) {
e.preventDefault();
var elem = $(this) ,
parent = elem.parent() ,
label = parent.find('label');
parent.children(':not(label,.edit)').remove();
parent.children().show();
});
$(document).on('click', '.save', function(e) {
e.preventDefault();
var elem = $(this) ,
parent = elem.parent() ,
label = parent.find('label') ,
value = parent.find('input').val();
parent.addClass('active');
var data = '&name='+value;
$.post("processingPage.php", data)
.success( function(returnedData) {
if( returnedData == 'ok' ) { /* change this to check if the data was processed right */
var active = $('.active');
active.find('label').text( active.find('input').val() );
active.children(':not(label,.edit)').remove();
active.children.show();
}
});
$('.active').removeClass('active');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><label>Some text</label><button class="edit">Edit</button></p>
<p><label>Some text</label><button class="edit">Edit</button></p>
<p><label>Some text</label><button class="edit">Edit</button></p>
<p><label>Some text</label><button class="edit">Edit</button></p>
You're PHP would look like this:
<?php
$return = false;
if( isset( $_POST['name'] ) ) {
if( mysqli_query( ... ) ) {
$return = true;
}
}
if( $return )
echo 'ok';
else
echo 'not ok';
?>

Ajax display msg on submit without refresh

I am submitting form data via Ajax and would like to display a message above the form on successful submit.
Currently the form does send the data successfully. It should render the feedback message on form submit <?php $this->renderFeedbackMessages(); ?> as defined in my config.php
Where am I going wrong? Possibly doing things in the wrong order due to first time working with mvc?
my config.php file I have the following defined;
define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");
my model;
public function addIsbn($isbn)
{
// insert query here
$count = $query->rowCount();
if ($count == 1) {
$_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
my controller;
function addIsbn()
{
// $_POST info here
header('location: ' . URL . 'admin/searchIsbn');
}
my searchIsbn.php;
<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
event.preventDefault();
var isbn = $('#isbn_search').val();
var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
$.getJSON(url,function(data){
$.each(data.items, function(entryIndex, entry){
$('#result').html('');
var html = '<div class="result">';
html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
html += '<hr><button type="button" id="add" name="add">add to library</button></div>';
$(html).hide().appendTo('#result').fadeIn(1000);
$('#add').click(function(ev) {
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
}
});
});
});
});
});
</script>
No console error messages.
You are redirecting here:
header('location: ' . URL . 'admin/addIsbn');
remove it.
echo the success message here and add it to an HTML element's .html() API.
Your page will not be refreshed.
Your page is making the call to admin/addIsbn which is redirected to admin/searchIsbn. So you already have the output of renderFeedbackMessages() being sent to your function.
Use the success callback to output the results to the page:
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
},
success: function(data) {
$('#result').html(data);
}
});
The only way I could get this to work was to add an auto-refresh to my Ajax success function as follows;
window.location.reload(true);
Working however open to suggestions.

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

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

Categories