replaceWith does not replace old div - php

What i am doing:
I am appending a div with a form and some buttons.The two buttons are save and cancel.When save is clicked,i am posting the form and getting the response.I want to replace the old div that houses the save was clicked.
This is the html and jquery http://jsfiddle.net/thiswolf/vSnJJ/1/
I am using this php but the post data is not sanitized since its an example
<?php
/**
test if replaced item can post and be deleted
#move ---->next
*/
$sliderKey = $_POST['sliderKey'];
$sliderPosition = $_POST['sliderPosition'];
$sliderTitle = $_POST['sliderTitle'];
$sliderLocation = $_POST['sliderLocation'];
$sliderDescription = $_POST['sliderDescription'];
$uniqid = uniqid();
echo "<div class='krudItem' id='$uniqid'><form class='aj' name='itemForm' method='post'action=''><section><label>Slider Title</label><input type='hidden' name='sliderKey' value='$sliderKey'/><input type='hidden' name='sliderPosition' value='$sliderPosition'/><input type='text' name='sliderTitle' value='$sliderTitle'/></section><section><label>Slider Location</label><input type='text' name='sliderLocation' value='$sliderLocation'/></section><section><label>Slider Description</label><textarea name='sliderDescription'>THIS IS THE REPLACEMENT</textarea></section><button name='saveNew' class='saveNew' id='$uniqid'>save</button><button name='newCancel'>delete</button></form></div>";
?>
This is the entire jquery i am using
jQuery(function() {
function randString(n)
{
if(!n)
{
n = 5;
}
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for(var i=0; i < n; i++)
{
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
$("#button").click(function () {
$("<div class='krudItem' id='xxx'><form class='aj' name='itemForm' method='post' action=''><section><label>Slider Title</label><input type='hidden' name='sliderKey' value='16'/><input type='hidden' name='sliderPosition' value='12'/><input type='hidden' name='clickedButton' value='initial'/><input type='text' name='sliderTitle' value='lorem'/></section><section><label>Slider Location</label><input type='text' name='sliderLocation' value='ipsum'/></section><section><label>Slider Description</label><textarea name='sliderDescription'>hello world</textarea></section><button name='saveNew' class='saveNew' id='buttonId' value='saveNew'>save</button><button name='newCancel'>cancel</button></form></div>").appendTo('.krudSpace');
});
//save new
jQuery('.saveNew').live("click",function(event)
{
jQuery(this).attr("id",randString(7));
event.preventDefault();
var contentPanelId = jQuery(this).attr("id");
jQuery.ajax({
type: "POST",
url: "insert.php",
data: jQuery(".aj").serialize(),
success: function(data){
var quoted = "#"+contentPanelId;
jQuery(quoted).replaceWith(data)
}
});
return false;
});
});
It works to some extent but the old div is not replaced at all but the response is appended below the old.

You're making things difficult. Just save the parent itself:
var $p = jQuery(this).parent();
and do:
$p.replaceWith(data)
Here's an updated jsFiddle (it uses error rather than success because there is no PHP): http://jsfiddle.net/vSnJJ/2/.

Related

Display information based on the autocomplete selected value

I have dynamic text field at Demo JSFiddle and I have done the autocomplete part for my item part no.
$ (document).ready(function() {
$("#addField").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div id=\"field" + intId + "\"/>");
var fpartNo = $("<input type=\"text\" name=\"erfq_partNo[]\" class=\"partNumber\"/>");
var fDescription = $("<input type=\"text\" name=\"erfq_desc[]\" disabled/>");
var fPrice = $("<input type=\"text\" name=\"erfq_price[]\" disabled style=\"width:80px\"/>");
// remove textboxes and dropdown boxes
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fpartNo);
fieldWrapper.append(fDescription);
fieldWrapper.append(fPrice);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
$(".partNumber").autocomplete({
minLength:1,
source: 'readPart.php',
select: function(event, ui){
var selected = ui.item.value;
}
});
});
});
readPart.php
$searchTerm = $_GET['term'];
$getPartSQL = base_executeSQL("SELECT * FROM eitem_item where eitem_item_part_no LIKE '%".$searchTerm."%' ORDER BY eitem_item_part_no" );
while($Partdata_row = base_fetch_array($getPartSQL))
if (base_num_rows($getPartSQL)!= 0)
{
$data[] = $Partdata_row['eitem_item_part_no'];
}
echo json_encode($data);
The first text field is uses for entering the part No.
My question is once the part no has been entered, the other relevant information (description and price) will be displayed at the other readonly text fields which the data are extract from my database. I have no idea what to continue with this select: function(event, ui){. Any help will be appreciated.
well, if you want to get the data on the basis of part # from database you can trigger an ajax call on blur of text box part number.
you can do something like this
$("#partNum").blur(function(){
var part = $("#partNum").val();
$.ajax({
type: 'get',
url:'/echo/js/?js='+part, //url to your database fetcher code.
complete: function (response) { //response contains what you got from pap page
$('textarea#des').val(response.responseText); //set textarea and textbox value popping out from db file
}
});
});
Here is HTML snippet to this request.
<input type = 'text' id = 'partNum' name = 'parts' />
<textarea id = "des" name = 'description' disabled></textarea>
FIDDLE
this will work on blur means when clicked outside the textbox. But if you want to get real time data(while user is typing) then you've to bombard the ajax requests on keyup event.
something like this:
$("#partNum").keyup(function(){
var part = $("#partNum").val();
$.ajax({
type: 'get',
url:'/echo/js/?js='+part,
complete: function (response) {
$('textarea#des').val(response.responseText);
}
});
});
FIDDLE here
Hope this will help.

Send form row datas to external PHP file

I need some help to resolve a problem.
I'm trying to send some datas from a form ROW to a php file.
Here's the first php code (It's inside an echo and value come from a MySQLi query):
<form id=\"comedivid\" method=\"post\">
<input class=\"numer-qua\" type=\"number\" id=\"dadivid\" min=\"0\" max=".$_GET['qua']." autofocus autocomplete=\"off\" name=\"dadivid\" maxlength=\"4\" size=\"5\">
<input type=\"hidden\" value=\"".$row["id_tes"]."\" name=\"ord\" id=\"ord\">
<input type=\"hidden\" value=\"".$_GET['codice']."\" name=\"cod\" id=\"cod\">
<input type=\"hidden\" value=\"".$_GET['qua']."\" name=\"arr\" id=\"arr\">
<input type=\"hidden\" value=\"".$row['descri']."\" name=\"desc\" id=\"desc\">
<input type=\"hidden\" value=\"".$row['unimis']."\" name=\"um\" id=\"um\">
<input type=\"hidden\" value=\"".$row['quanti']."\" name=\"qua\" id=\"qua\">
<input type=\"hidden\" value=\"".$row['prelis']."\" name=\"pre\" id=\"pre\">
<input type=\"hidden\" value=\"".$row['sconto']."\" name=\"sco\" id=\"sco\">
<input type=\"hidden\" value=\"".$row['codvat']."\" name=\"cva\" id=\"cva\">
<input type=\"hidden\" value=\"".$row['pervat']."\" name=\"iva\" id=\"iva\">
<input type=\"hidden\" value=\"".$row['codric']."\" name=\"ric\" id=\"ric\">
<button id=\"dividili\" class=\"btn btn-blue\" type=\"submit\"><i class=\"fa fa-copy\"> Dividi Riga</i></button>
\n";
The form is included in a table. The query may give more as one result.
Here's my AJAX code:
$("#dividili").click(function(){
$(this).closest("form#comedivid").submit(function(event) {
event.preventDefault();
var dadivid = $("#dadivid").val();
var ord = $("#ord").val();
var cod = $("#cod").val();
var arr = $("#arr").val();
var desc = $("#desc").val();
var um = $("#um").val();
var qua = $("#qua").val();
var pre = $("#pre").val();
var sco = $("#sco").val();
var cva = $("#cva").val();
var iva = $("#iva").val();
var ric = $("#ric").val();
$.ajax({
type: "POST",
url: "../../modules/acquis/dividi.php",
data: "dadivid=" + dadivid + "&ord=" + ord + "&cod=" + cod + "&arr=" + arr + "&desc=" + desc + "&um=" + um + "&qua=" + qua + "&pre=" + pre + "&sco=" + sco + "&cva=" + cva + "&iva=" + iva + "&ric=" + ric,
success: function(){alert('success');}
});
});
});
It's not working, no data are sent to URL.
Is it because the form is in more rows?
Or is there a mistake in my code?
I tried with serialize also, with no results.
Here's the code:
$("#dividili").click(function(e){
$.ajax( {
type: "POST",
url: "../../modules/acquis/dividi.php",
data: $('#comedivid').serialize(),
success: function( response ) {}
});
});
Thank you so much for your help!
I would suggest using serialize():
$("#dividili").click(function(){
$(this).closest("form#comedivid").submit(function(event) {
event.preventDefault();
var form_data = $('form#comedivid').serialize();
// or
var form_data = $(this).serialize();
// try to output that just to make sure you are doing it right
console.log( form_data );
// or
alert( form_data );
$.ajax({
type : "POST",
url : "../../modules/acquis/dividi.php",
data : form_data,
success : function(){alert('success');}
});
});
Since you already tried that, and if the output is ok, then it's a problem with your PHP, so try to output at the beginning of your file what was received:
<?php
echo '<pre>';
print_r( $_POST );// or $_REQUEST for both $_POST and $_GET
echo '</pre>';
die;
// the rest of your code...
If everything is received well in PHP, you need to make sure you are using the right way to fetch your data, like $dadivid = $_POST["dadivid"];
jQuery 'serialize' method made data like get query form.
so, Data length would be limited in apache configuration.
Try use this custom method.
(function($) {
$.fn.serializeObject = function () {
"use strict";
var result = {};
var extend = function (i, element) {
var node = result[element.name];
if ('undefined' !== typeof node && node !== null) {
if ($.isArray(node)) {
node.push(element.value);
} else {
result[element.name] = [node, element.value];
}
} else {
result[element.name] = element.value;
}
};
$.each(this.serializeArray(), extend);
return result;
};
});
How to use is same default jQuery 'serialize' method.

Jquery checkbox unchecks on submit

My checkboxes are empty when page refreshes after submit. I would like to keep them checked. How can I do that in jquery?
Here is my jquery code.
$(document).ready(function () {
$(':checkbox.selectall').on('click', function () {
$(':checkbox[id="' + $(this).data('checkbox-name') + '"]').prop("checked", $(this).prop("checked"));
$( "#frm1" ).submit();
});
$(':checkbox.checkme').on('click', function () {
var _selectall = $(this).prop("checked");
if (_selectall) {
$(':checkbox[name="' + $(this).attr('name') + '"]').each(function (i) {
_selectall = $(this).prop("checked");
return _selectall;
});
}
$(':checkbox[name="' + $(this).data('select-all') + '"]').prop("checked", _selectall);
$( "#frm1" ).submit();
});
});
My html is as follows...
<input type='checkbox' id='selectall' name='sa_subcatinput[]' value='$row[id]'
data-checkbox-name='$row[id]' class='selectall'/></label></a></li>
<input type='checkbox' name='subcatinput[]' value='$test[id]' id='$test[category]'
class='checkme' data-select-all='sa_subcatinput[]'/>
You cannot do this unless you send a value back to your page which indicates the checkbox to be checked.Since you said the page refreshes, a server communication is happened. So you may use ajax to keep the check box checked
Pass a querystring parameter of the id or number or value or whatever of the checked checkbox.
request the parameter using server side code or a client-side javascript using a get parameter function (there on many on this site).
rechecked the box using your custom function and the value returned.
$('#ckeckbox1').val(unescape(getParam(document.URL,'checkbox1')));
function getParam(url,name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if( results == null )
return "";
else
return results[1];
}
function removeParameter(url, parameter) {
var urlparts= url.split('?');
if (urlparts.length>=2) {
var urlBase=urlparts.shift(); //get first part, and remove from array
var queryString=urlparts.join("?"); //join it back up
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;) //reverse iteration as may be destructive
if (pars[i].lastIndexOf(prefix, 0)!==-1) //idiom for string.startsWith
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
}
return url;
}
I was able to get the code working with php. Here is the code I inserted in the input to make it work.
echo"<input type='checkbox' id='selectall' name='sa_subcatinput[]' value='$row[id]'
data-checkbox-name='$row[id]' class='selectall'";
if (isset($_POST['sa_subcatinput'])) {
if (in_array($row['id'], $_POST['sa_subcatinput'])) {
echo"checked='checked'";
}
}
echo"/>
echo"<input type='checkbox' name='subcatinput[]' value='$test[id]'
id='$test[category]' class='checkme' data-select-all='sa_subcatinput[]'";
if (isset($_POST['subcatinput'])) {
if (in_array($test['id'], $_POST['subcatinput'])) {
echo"checked='checked'";
}
}
echo"/>

JQuery Post to php with dynamicaly created IDs

I am trying to create a method that posts data to mysql when called. The only problem is I can't figure out how to pass it the correct information from the fields as their IDs are created at runtime.
The fields are created using a while loop and on double click they become editable then on blur they are supposed to revert to their previous state and post any changes made to the database.
(this is my first time writing one of these I hope I'm clear!)
My JS
function disablefarm(farmid) {
$(function() {
var farmstr = farmid.replace(/[^0-9\.]+/g, ""),
farmID = $("#farm" + farmstr + "").val(),
farmName = $("#farmn" + farmstr + "").val(),
fieldarray = $([]).add(farmName).add(farmID);
$("input:text[id=" + farmid + "]").attr('readonly', 'readonly');
$("input:text[id=" + farmid + "]").addClass("noshow");
var epost_url = "editfarm.php";
var epost_data = fieldarray.serialize();
$.post(epost_url, epost_data, function(response) {
alert(response);
});
});
}
The html elements are created in a while loop that outputs
echo "<td name='farmL' ><input type='hidden' value='$id' id='farm$id' /> <input type='text' id='farmn$id' value='$fname' readonly='readonly' class='noshow' size='33' ondblclick='enablefarm(this.id)' onblur='disablefarm(this.id)' />";
And finally editfarm.php looks like
if (filled_out($_POST)){
$efarmID = check_input ($_POST['farmID']);
$efarmName = check_input ($_POST['farmName']);
}
else{
echo "not committed";
}
$query = "UPDATE farm_name
SET farmName='".$efarmName."'
WHERE farmID=".$efarmID.";";
$result = mysql_query($query);
if(!$result)
{
echo"".stripslashes($efarmName)." not updated";}
else{
echo"".stripslashes($efarmName)." updated";
}
The HTML output looks like this
<tr id='row27'>
<td name='farmL'>
<input type='hidden' value='27' id='farmid27' />
<input type='text'
id='farmn27'
value='111 Gary farms'
readonly='readonly'
class='noshow'
size='33'
ondblclick='enablefarm(this.id)'
onblur='disablefarm(this.id)' />
</td>
</tr>
Thanks!
Reducing js to minimum, I would have done this by introducing an extra attribute to your dynamically generating inputs.
<td><input type="text"
data-id="27"
name="farmid27"
value="111 Gary Farms"
class="farmEdit" /></td>
Now simply update your js to:
$(document).on("blur", "input.farmEdit", function() {
$.post("editfarm.php",
{
farmID : $(this).attr('data-id'),
farmName : $(this).val()
},
function(response) {
alert(response);
});
});
Here you can see the 'data-id' attribute removed the dependency on input name, and I would suggest why to introduce input name when you are posting it individually using ajax(atleast for these types of cases).
You may find it easier if you refactor your code somewhat. If you modify your PHP code to output the table content to look something like this:
<td>
<input type="text"
name="farmid27"
value="111 Gary Farms"
class="farmEdit" />
</td>
(The indentation is just to make it readable.)
Then you can rewrite your JavaScript to something like:
$(document).ready(function() {
$(document).on("blur", "input.farmEdit", function() {
var $inputElement = $(this),
inputName = $inputElement.attr("name"),
inputValue = $inputElement.attr("value")
curFarmId = inputName.substr(6); // Strip off the "farmid.." prefix
$.post(
"editfarm.php",
{
farmID : curFarmId,
farmName : inputValue
},
function(response) {
alert(response);
});
});
});
This takes advantage of jQuery delegated events and the fact that the this object in a click handler refers to the page element that was clicked (the <input> in this case).

Creating a comments page selection using AJAX data

I decided to go AJAX route for the heck of it, mainly to learn it, and to see how it worked. I want to add a page selection for comments that exceed, say, 10 posts.
I am using Codeigniter, and will post what I have so far:
Controller:
public function updatefilters()
{
$this->blurb_model->create_session_filter($_POST['filters']);
$this->blurb_model->get_threads($_POST['pagenum']);
}
Model:
public function get_threads($page = 0)
{
$NEEDPAGEHERE = $page
[fetch threads]
[return threads / count / etc]
}
So my goal is to display the number of pages to the user. This part is done. I have a submit button displayed for each page based on the total count of items returned in the "get_threads" model (code is omitted for relevance sake).
Here is my AJAX/javascript
Focus lies on the updatefilter function. I use the returned thread list to construct HTML and post it within the div. This works fine.
The problem is that I want to reuse the updatefilters() function when the user clicks on a page button...but its not working. I want to pass the value of the submit button into the updatefilter(pagenum) so that it then goes to the controller -> method, and I can do the math, but it does not work.
Javascript:
function updatefilters(pagenum){
// get the selected filters
var html;
var i = 0;
if (!pagenum)
{
pagenum = 0
}
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
async: false,
url: 'welcome/updatefilters',
dataType: 'json',
data: { filters: filters, pagenum: pagenum },
success: function(data){
var html = "";
html += "<div id=board>"
html += "<div class='board' id='table'>"
html += "<div id='row'>header here</div>"
var pages = Math.ceil(data['num_threads']/10);
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' id='page"+i+"' value='"+i+"' onclick='updatefilters(this.value);' /></li>"
}
htmlpage += "<div>"
htmlpage += "</ul>";
htmlpage += "</br></br></br>";
html += htmlpage;
for (i=0 ; i < data['threads'].length ; i++)
{
html += "<div id=row>";
html += " <div id='author' style='background: url("+data['threads'][i].location + ") no-repeat; background-position: center;'><p>"+data['threads'][i].username + "</p></div>";
html += " <div id='arrow'></div>";
html += " <div id='subject' title='"+ data['threads'][i].body +"'>";
html += " "+ data['threads'][i].subject +"<p>Created: "+data['threads'][i].posttime+"</p></div>";
html += " <div id='info'>";
html += " <div id='replies'>" + data['threads'][i].replies_num + "</div>";
html += " <div id='lastpost'>"+ data['threads'][i].lastreply+"</div>";
html += " </div>";
html += "</div>";
}
html += "</div></div>";
$('#board').html(html);
}
});
}
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
getactivesession();
function getactivesession(ev, ui){
var i = 0;
var actfilter, strfilter;
var strfilterarray = new Array();
$.ajaxSetup({cache: false})
$.ajax({
type: "POST",
async: false,
url: 'welcome/getactivesession',
dataType: 'json',
success: function (data){
strfilter = JSON.stringify(data)
strfilterarray = strfilter.split(',')
for (i=0 ; i < strfilterarray.length ; i++) {
strfilter = strfilterarray[i]
strfilter = strfilter.replace(/[\[\]'"]+/g,'');
var strfilterdash = strfilter.replace(/\s+/g, '-')
actfilter = '#'+ strfilterdash
$(actfilter).addClass('ui-selected')
}
updatefilters();
}
});
}
});
This would be an INCREDIBLE learning experience for myself, and a huge help if someone can spot the problem and explain it in an easily understood manner. I am extremely new with javascript and programming in general (which might explain the ugliness of the code).
Thanks!
Modify your selected event callback.
$("#selectable").selectable({
// Here is the event callback signature for reference
selected: function(event, ui) {
updatefilters();
}
});
You were passing an unexpected first parameter to updatefilters function.

Categories