So I've been able to apply some code online from previous discussions to a project that I'm working on however, now that there are multiple xml elements to grab I cannot seem to figure out how.
The xml structure is set up like this:
``
<DEPTId id = "1234">
<GROUP_DESCRIPTION>Something</GROUP_DESCRIPTION>
<DESCIPTION>Some department</DESCRIPTION>
<SOFTWARE>piece 1<SOFTWARE>
<SOFTWARE>DSFAON</SOFTWARE>
<SOFTWARE>asdvn</SOFTWARE>
<DEPTId>
I have tried to either reformat the structure to be SOFTWARE1, SOFTWARE2, .. but I felt as though one element should suffice as there can be many pieces of software, and couldn't find a way to iterate across each element. However the code I have only prints out the SOFTWARE elements text as one string, and not separate checkboxes which I want.
My JavaScript is below. It checks their group and department from the html page, and if it is equal to the xml it will append the listed software to the table on the page.
function defaultSoftware() {
$("#defaultSoftwareList").empty();
$.ajax({
type: "GET",
url: "blahblah.xml",
contentType: "charset=utf-8",
dataType: "xml",
async: true,
success: parsePersonaXML
});
function parsePersonaXML(xml) {
$(xml).find("DEPTId").each(function() {
var htmlDepartment = $("#b1Department").val();
var htmlGroup = $("#techpersonaGroup").val();
var xmlGroup = $(this).find("GROUP_DESCRIPTION").text();
var xmlDepartment = $(this).find("DESCRIPTION").text();
if (htmlDepartment == xmlDepartment && htmlGroup == xmlGroup)
$(this).find("SOFTWARE").each(function() {
var sd = ("SOFTWARE").text();
$("#techpersonaList").append('<input type="checkbox" checked /> ' + sd + '<br />');
});
});
}
}
If anyone knows what I am doing wrong or how I can change it your help would be much appreciated!
Related
I hope someone can help me with this:
I'm building a website with a product comparisontable (with checkbox filters) and I'm using a Javascript I found on the internet. I have some knowledge of JavaScript, but Ajax en jQuery are new for me :-).
The code that's working:
$(document).ready(function () {
filter_data();
function filter_data() {
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var walk = get_filter('walk');
var bike = get_filter('bike');
var swim = get_filter('swim');
var multi = get_filter('multi');
$.ajax({
url: "functions/fetch_data.php",
method: "POST",
data: {
action: action,
walk: walk,
bike: bike,
swim: swim,
multi: multi
},
success: function (data) {
$('.filter_data').html(data);
}
});
}
function get_filter(class_name) {
var filter = [];
$('.' + class_name + ':checked').each(function () {
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function () {
filter_data();
});
});
This code is working, but ... the variables inside this function, need to be generated from an external text file. Because the variables need to be edited easily and very frequent. And there are a lot more variables than you see in this code.
And this is what my (shortened) textfile looks like:
1,brand,Brand
2,walk,Walk
2,bike,Bike
2,swim,Swim
2,multi,Multi
The numbers indicate whether the field should be used in the filter or not. Lines with number 2 are the variables, and need to be 'pasted' in the code as variables and datafields.
Is it possible to get the fields/variables from the textfile within Javascript Ajax / jQuery? So with an extra function?
I hope someone can help me with this, I've been working on it for many hours but I can't get it to work properly.
Thanks!!
Alright guys I'm trying to make a filter system for posts using ajax and a select box. I am able to get the value from the select box no problem. But my issue is that when I try to include the selected value in my PHP file it doesn't do anything. I have a file called public_wall.php. This file contains PHP, Javascript, and HTML. How can I refresh this div whenever a user selects a different filter option? Basically I need the selected value to be passed onto my public_wall.php file and then I want to plug it into the PHP function that fetches the posts thats's in the same file and then I want to refresh that same file to display the filtered results. Here is my Javascript code.
$("#postRatings").on("click", function(e) {
selectedRatingFilter = $("#postRatings option:selected").val();
var dataString = "timeFilter="+selectedRatingFilter;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response){
hideSpinner();
jQuery('#postsPagingDiv').remove();
jQuery('#wsc_midbox').html(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
jQuery('#paging_in_process').val(0);
}
});
});
When the dataType is set to "json" nothing happens. But when it is set to html it prints some javascript code. Please help. The PHP file is too large to include here, but it basically contains PHP, HTML, and Javascript and some PHP functions that do sql queries. What is the best way to achieve a filter mechanism for my setup?
And on the public_wall.php file I want to get the value like so:
$ratingFilter = isset($_REQUEST['timeFilter']) ? intval($_REQUEST['timeFilter']) : 0;
And then plug it into the PHP function that fetches the posts which is in the public_wall.php file also so that I can filter the posts based on the selected value. And then finally I want to refresh the public_wall.php file with the new results. I hope that makes sense. Please help.
This is the output when I set my dataType to "html"
<script>
function refreshPosts() {/* only posts comments likes and count updated. */
var posts = jQuery("#all_post_id").val();
var arrays = posts.split(',');
var dataString = "postids="+posts;
jQuery.ajax({
type: "POST",
url: site_url+"includes/update_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
var x = response;
//############ skip posts whose comments are being read by users
var ExemptedPostsIDs = jQuery("#exemptedPostsID").val();
var ExemptedArray = ExemptedPostsIDs.split(',');
ExemptedArray = ExemptedArray.sort();
//////////////
for (i=0; i<arrays.length; i++) {
var val = 'row'+arrays[i];
if(x[val]) {
if(!inArray(arrays[i], ExemptedArray))
jQuery("#ajax_wall_"+arrays[i]).html(x[val]);
} else {
jQuery('#PostBoxID'+arrays[i]).parent().fadeOut(500);
}
}
}
});
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function refreshWall() {/* loads new posts real time */
var posts = jQuery("#all_post_id").val();
var pageUsing = jQuery('#pageUsing').val();
var dataString = "update_posts=1&postids="+posts+'&pagex='+pageUsing;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
if(response.all_post_id) {
jQuery('#wsc_midbox').prepend(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
}
}
});
}
</script>
I suggest you keep the form with select element and any JavaScript on the outer frame.
Via ajax, only load the results to a seperate DIVision below that.
When you put an Ajax response to a div, any JavaScript inside it will not be executed.
For the best throughput with Ajax, you should consider loading a json response via Ajax and create HTML elements on the client side. That way it becomes much easier to pull additional variables to front-end JS from server side along with the same request/response.
But that becomes bit difficult when you have a template engine in the back-end. You can still send the HTML content in a json value, so you can easily pass the "all_post_id" as well..
I have a page that I have edited after load and what I want to do is get the pages current HTML and pass that off to a PHP script.
I first passed document.documentElement.innerHTML but that ended up including a bunch of computed style garbage at the top which I did not want. After googling around I found I could use ajax to get a copy of the current file on the server and then replace the edited part afterwards.
I can get the copy of the file using this:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
Which works fine and gets me the html I expected and see when viewing the page in notepad.
The next step is what I cannot figure out. All I want to do is swap out the innerHTML of a div with an id of 'editor' with what the current value is, so I have tried this:
origPage.getElementById('editor').innerHTML = e.html;
But I get the error "TypeError: undefined is not a function". I must be doing something simple wrong I feel but I don't know the proper formatting to do this. I have tried the following variations:
alert($(origPage).getElementById('editor').innerHTML);
//Different attempt
var newHtml = $.parseHTML( origPage );
alert($(newHtml).getElementById('editor').innerHTML);
//Different attempt
alert($(origPage).html().getElementById('editor').innerHTML);
But I always get "TypeError: undefined is not a function" or "TypeError: Cannot read property 'getElementById' of undefined". How can I do this properly?
EDIT:
Complete page html below:
<!DOCTYPE html>
<html>
<body>
<div id="editor">
<h1>This is editable.</h1>
<p>Click me to start editing.</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="snapeditor.js"></script>
<script type="text/javascript">
var editor = new SnapEditor.InPlace("editor", {onSave: function (e) {
var isSuccess = true;
//var origPage = e.html;
var origPage;
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
// Actually perform the save and update isSuccess.
// Javascript:
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
//origPage shows expected html as this point
//alert($(origPage).getElementById('editor').innerHTML);
//alert($(origPage).html().getElementById('editor').innerHTML);
$(origPage).getElementById('editor').innerHTML = e.html;//fails here
alert(origPage);
//alert(newHtml.getElementById('editor').innerHTML);
$.ajax({
data: {html: origPage, docName: 'example1.html'},
url: 'savePage.php',
method: 'POST', // or GET
success: function(msg) {
alert(msg);
isSuccess = true;
}
});
return isSuccess || "Error";
},
onUnsavedChanges: function (e) {
if(confirm("Save changes?")) {
if(e.api.execAction("save")){
//location.reload();
}
} else {
e.api.execAction("discard");
}
}});
</script>
</body>
</html>
It seems that you get the user's changes in a variable - you called the var e.html. That is not a good variable name, BTW. If you can, change it to something like htmlEdited
Question: If you add the command alert(e.html); what do you get? Do you see the HTML after user edits?
If yes, then what you need to do is send that variable to a PHP file, which will receive the data and stick it into the database.
Code to send the data:
javascript/jQuery:
alert(e.html); //you should see the user-edited HTML
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'userStuff=' + e.html, //var_name = var_contents
success: function(d){
window.location.href = ''; //redisplay this page
}
});
another_php_file.php:
<?php
$user_edits = $_POST['userStuff']; //note exact same name as data statement above
mysql_query("UPDATE `your_table_name` SET `your_col_name` = '$user_edits' ") or die(mysql_error());
echo 'All donarino';
The AJAX javascript code will send the var contents to a PHP file called another_php_file.php.
The data is received as $user_edits, and then inserted into your MySQL db
Finally, I presume that if you redisplay that page it will once again grab the contents of the #editor div from the database?
This is where you haven't provided enough information, and why I wanted to see all your code.
ARE you populating that div from the database? If not, then how do you expect the page to be updated after refreshing the page?
You would benefit from doing some tutorials at phpacademy.org or a thenewboston.com. Do these two (free) courses and you'll be an expert:
https://phpacademy.org/videos/php-and-mysql-with-mysqli
https://phpacademy.org/videos/oop-loginregister-system
If all you need to do is insert the contents of e.html to replace the #editor div, then try this:
$('#editor').html(e.html);
HOWEVER, you need an event to trigger that code. Are you able to do this?
alert(e.html);
If so, then put the first bit of code at that same spot. If not, we need more information about when your code receives that variable -- that is where you put the $('#editor').html(e.html); statement.
Is there a method to include more than one value at a time. Firstly, here is the script:
$(document).ready(function() {
$('.edit_link').click(function() {
$('.text_wrapper').hide();
var data=$('.text_wrapper').html();
$('.edit').show();
$('.editbox').html(data);
$('.editbox').focus();
});
$(".editbox").mouseup(function() {
return false
});
$(".editbox").change(function() {
$('.edit').hide();
var boxval = $(".editbox").val();
var dataString = 'data=' + boxval;
$.ajax({
type: "POST",
url: "update_profile_ajax.php",
data: dataString,
cache: false,
success: function(html) {
$('.text_wrapper').html(boxval);
$('.text_wrapper').show();
}
});
});
$(document).mouseup(function() {
$('.edit').hide();
$('.text_wrapper').show();
});
});
I want to have more than one field. I want to edit more than one entry at a time, instead of simply re-writing the code for each different value. Is there a way I can include them in the code? I tried this but had no luck:
$('.edit_link','.edit_link2','.edit_link3').click(function() {
$('.text_wrapper','.text_wrapper2','.text_wrapper3').hide();
var data=$('.text_wrapper','.text_wrapper2','.text_wrapper3').html();
Hopefully you get what I mean by this, I want to include more values but cannot achieve this, does anyone have some advice or a simply way to do this?
Put all in one string, for example:
$('.text_wrapper, .text_wrapper2, .text_wrapper3').hide();
But you can't read out the values with html() on multiple elements at the same time.
So for example use:
data = $('.text_wrapper').html();
data += $('.text_wrapper2').html();
data += $('.text_wrapper3').html();
But this depends on how you wanna have your data in the end.
I am having some trouble working out how to get data from a form to post via ajax. I have the following code but it doesn't seem to be sending though the data from elements like checkboxes and radio buttons. Instead it is sending though all the fields. ie if there is a set of radiobuttons it is sending through all the possibilities not just the checked ones. The form can be made up of any type of element and have an undermined amount of elements in it, so I need to iterate through in the way I am. That part seems to be working, but I can't seem to get the javascript to grab the selected data. Do I need to manually check each element's type and then check to see if it checked etc?
myString = "";
my_form_id = "1";
my_url = "phpscript.php";
elem = document.getElementById("form_" + my_form_id).elements;
for(var i = 0; i < elem.length; i++)
{
if (i>0) { myString += "&"; }
myString += elem[i].name + "=" + elem[i].value;
}
$.ajax({
type: "POST",
url: my_url,
data: myString,
success: function(data) {
// process the post data
}
});
`
Since you're using jQuery, you can drastically simplify it all:
var my_form_id = "1";
var my_url = "phpscript.php";
var form = $("#form_" + my_form_id);
$.ajax({
type: "POST",
url: my_url,
data: form.serialize(),
success: function(data) {
// process the post data
}
});
jQuery's serialize method does all the work for you. But if you wanted to do it by hand, then yes, you would have to check each field.