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

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';
?>

Related

Display a div after submit contact form 7 form

I want display a div contain some details after successful submission of a form. I am using contact form 7 plugin.. Please help me to do this.
Hi you can use Contact Form 7 DOM Events see this link
https://contactform7.com/dom-events/
below is example of calling alert after your form submission
var wpcf7Elm = document.querySelector( '.wpcf7' );
wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
alert( "Fire!" );
}, false );
and you can also append or place a div after submission as shown in below code,
in below code you have to replace #yourDivId with your desired div id.
var wpcf7Elm = document.querySelector( '.wpcf7' );
var div = '';
div += '<div class="custom_detail_div">';
div += ' .... your details here ..... ';
div += '</div">';
wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
jQuery('#yourDivId').html(div);
}, false );
also you can check this also,
https://wordpress.stackexchange.com/questions/282751/how-to-modify-contact-form-7-success-error-response-output
I hope this will help you.
Thanks
I find a solution ......
`<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( '33' == event.detail.contactFormId ) { // if you want to identify the form
var hid = document.getElementsByClassName("exp");
// Emulates jQuery $(element).is(':hidden');
if(hid[0].offsetWidth > 0 && hid[0].offsetHeight > 0) {
hid[0].style.visibility = "visible";
}
}
}, true );
</script>`
Here 33 is my form id and exp is class of my div

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.

Force selection with JQuery autocomplete

I know this question has been asked before, but I wasn't able to find any answers that are up to date or functional (at least for my application).
My JQuery autocomplete box is using a mysql database as its source. I want the user to be able to type to get recommendations, but then is forced to select from the dropdown choices before they can submit the form.
My Javascript:
<script type="text/javascript">
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
$(function() {
$("#college").autocomplete({
source: "search.php",
minLength: 5
});
});
var inputs = {college: false};
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
alert('incorrect');
return false;
}
}
alert('correct');
$('#college_select_form').submit();
});
</script>
My form:
<form action="choose.php" method="post" id="college_select_form" name="college_select_form">
<input type="text" id="college" name="college" class="entry_field" value="Type your school" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Type your school':this.value;" /><input type="submit" id="submit" name="submit" class="submitButton" value="Go" title="Click to select school" />
</form>
Search.php:
<?php
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM college_list where name like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
}
}
/* Free connection resources. */
//$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
So what would be the best approach to doing this? The only solution I can think of is using PHP to verify that the textbox's value matches a value in the database, but I'm not sure how to implement that with my current code.
You should always check it in "choose.php" (server-side) since the user can disable the JavaScript and post whatever they want in the inputs of your form
$college = mysql_real_escape_string($_GET['college']);
if ($college != "" || $college != null || $college != -1)
{
//DO STUFF
}
NOTE: YOU SHOULD ALWAYS USE "mysql_real_escape_string" to prevent SQL Injection!
more info: http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
So accordingly in search.php change the
$ac_term = "%".$_GET['term']."%";
to
$ac_term = "%". mysql_real_escape_string($_GET['term']) ."%";
You can also check the form before the user submit to just make it more user friendly (users don't want to wait couple of seconds for the page to gets refreshed with errors on it!)
so maybe something like this would help: Submit Event Listener for a form
function evtSubmit(e) {
// code
e.preventDefault();
// CHECK IT HERE!
};
var myform = document.myForm;
myform.setAttribute('action', 'javascript:evtSubmit();');
In my project i handled it by checking on focus-out , if the text entered in the autocomplete field actually matches my dropdown options.If not i will simply remove it.
change: function(event, ui) {
if (!ui.item) {
this.value = '';
}
}
See my full example here-Jquery auto comp example
it has an embeded fiddle,you can check the fiddle directly also
http://jsfiddle.net/9Agqm/3/light/
Add this code to your JavaScript before you instantiate your autocomplete object:
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
This will make it so whenever the menu appears, you have a list of current items the user can choose from stored in $.ui.autocomplete.currentItems. You can then use that to check against when you are submitting your form. Of course the way you implement this part is up to you depending on how dynamic your form is, but here is an example that requires hard-coding a list of input fields and making sure they all have ids.
//create an object that contains every input's id with a starting value of false
var inputs = {college: false};
//for each input, you will have a function that updates your 'inputs' object
//as long as all inputs have id's and they all are using autocomplete,
//the first line could be written as: $('input').change(function(){ and the
//function would only need to be written once. It is easier to maintain
//if you use seperate id's though like so:
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
//when you submit, check that your inputs are all marked as true
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
return false; //one or more input does not have correct value
}
}
//all inputs have a value generated from search.php
$('#myform').submit();
});
UPDATE
The only difference between our two examples (one that works and one that doesn't) is that you are binding other events to your input element, onclick and onblur. So by changing our listener from change to blur as well mostly fixes the problem. But it creates a new problem when the enter/return key is pressed to submit the form. So if we add a listener for that specific event then everything works out ok. Here is what the code looks like now:
var validateInfo = function(elem){
var id = elem.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(elem).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
}
$('#college').on('blur', function(){
validateInfo(this);
}).on('keydown', function(e){
if(e.which == 13){ //Enter key pressed
validateInfo(this);
}
});
Add a hidden input element to your form:
<input type="hidden" name="selectedvalue" id="selectedvalue" />
Add a select event handler to your autocomplete, that copies the selected value to the hidden input:
$("#college").autocomplete({
source: "search.php",
minLength: 5,
select: function (event, ui) {
$('#selectedvalue').val(ui.item.value);
}
});
Then just ignore the auto-complete form input in posted data.
As this is javascript, your only concern should be if an item is selected from the autocomplete list. This can simply be done by setting a variable to true on select and false on change. That is enough to prevent regular users from continuing without selecting a school. To prevent abuse you need to check the value server side after posting. All normal user will pass that check.
If I understand the question correctly, this is something I have encountered before. Here is some code pretty much lifted straight out of another project. I have used a local datasource here but the project this is lifted from uses remote data so there won't be a difference:
var valueSelected = '';
$('#college').autocomplete({
source: ['collegeA', 'collegeB', 'collegeC']
}).on('autocompletechange autocompleteselect', function (event, ui) {
if (!ui.item) {
valueSelected = '';
} else {
$('#submit').prop('disabled', false);
valueSelected = ui.item.label;
}
}).on('propertychange input keyup cut paste', function () {
if ($(this).val() != valueSelected) {
valueSelected = '';
}
$('#submit').prop('disabled', !valueSelected);
});
This will programatically enable and disable the submit button depending on whether a value has been selected by the user.
Fiddle here

Trying to make an AJAX edit in place in Codeigniter .. failing

I'm on my first CI project and I'm trying to do basically an AJAX "edit in place".
I have a user profile page with a number of fields. Basically the user is looking at his own data, and I would like to give him the option to edit his info on a field by field basis. I have about 20 fields like so..
<div id="desc_short">
<div class="old_info"><p><?php echo $the_user->desc_short; ?></p></div>
<div class="edit_buttons">
<button type="button" class="btn_edit">Edit Field</button>
<button type="button" class="btn_submit">Submit Change</button>
<button type="button" class="btn_cancel">Cancel</button>
</div>
The submit and cancel buttons start off with display:none. A click on the 'edit' button appends a form to the div with some hidden field info and "shows it in" along with 'submit' and 'cancel' buttons. SO now the user has a text field under the original info, and two new buttons.
$('.btn_edit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var form_HTML = "<form action='edit_profile' method='post'><input type='text' class='new_info' name='new_info'/><input type='hidden' class='edit_field' name='edit_field' value='"+this_field_id+"'/></form>";
$("#"+this_field_id).append(form_HTML).hide().show(500);
$(this).siblings().fadeIn(1000);
});
So I am dynamically adding the form to the appropriate div, and giving it a hidden field with the name of the datafield that is being edited. I'm also showing the "submit" and "cancel" buttons (although notice that the submit button is not in the form element).
I'll leave out the "cancel button" function, but here is the submit button jquery. As you can see I am trying to submit the form by "remote control", triggering a submit event on the form long distance from the submit button. And then on the submit event, I preventDefault and then try to $.post the info to an AJAX controller..
$('.btn_submit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var new_info = $("#"+this_field_id+" .new_info").val();
alert(this_button);
$("#"+this_field_id+" form").trigger('submit');
$("#"+this_field_id+" form").submit(function(e){
e.preventDefault();
alert(this_field_id); // alerting correctly
$.post('../ajax/profileEdit', { edit_field: this_field_id , new_info: new_info },
function(data){
if(data = 'true')
{
alert(data); // <<<< alerts "true"
}
else
{
alert("bad");
}
}
);
});
});
Here is the ajax controller
public function profileEdit()
{
$ID = $this->the_user->ID;
$field = $this->input->post('edit_field');
$new_info = $this->input->post('new_info');
$this->load->model('Member_model');
$result = $this->Member_model->edit_profile( $ID, $field, $new_info );
echo $result;
}
And the model..
public function edit_profile($ID, $field, $new_info)
{
$statement = "UPDATE users SET $field=$new_info WHERE UID=$ID"
$query = $this->db->query($statement);
return $query;
}
I am actually getting back "TRUE" back to Jquery to alert out .. but nothing is being edited. No change to the information. Frankly, I am surprised I'm even getting 'true' back (the whole remote submit thing .. I thought "no way this works").. but that makes it tough to see what is going wrong.
Ideas?
Apart from the if(data = 'true) error, i don't see where the other error could be.
When you alert data, what does it show you?
Try this in the model;
public function edit_profile($ID, $field, $new_info)
{
$data = array('field_table' => $field, 'new_info_table' => $new_info);
return ($this->db->where('UID',$ID)->update('tabel_name',$data)) ? TRUE : FALSE;
}
AND in
public function profileEdit()
{
$ID = $this->the_user->ID;
$field = $this->input->post('edit_field');
$new_info = $this->input->post('new_info');
$this->load->model('Member_model');
if($this->Member_model->edit_profile( $ID, $field, $new_info )){
echo 'success';
}else{
echo 'error';
}
}
Then
$('.btn_submit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var new_info = $("#"+this_field_id+" .new_info").val();
alert(this_button);
$("#"+this_field_id+" form").trigger('submit');
$("#"+this_field_id+" form").submit(function(e){
e.preventDefault();
alert(this_field_id); // alerting correctly
$.post('../ajax/profileEdit', { edit_field: this_field_id , new_info: new_info },
function(data){
if(data == 'success')
{
alert(data); // <<<< alerts "true"
}
else if(data == 'error')
{
alert('Database error');
}
else{
alert('');
}
}
);
});
});
Just wrote it on here, so i haven't tested it. But give it a try, at least you might be able to know where the error is coming from. If you still get the same error, try alert data before the if(data == 'sucess'), to see what the profile edit func is returning.

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