I am creating an application that converts an online form into various PDF forms to reduce admin burden. I am using an XML file so that users can enter a course code and the form will automatically populate some of its data to fill in the course information, however for the code below I am just using test files to figure it out first.
The user is to enter the course code in a text input and click a button to call Ajax to read the xml and create variables to populate the form. I have looked through dozens of tutorials and forums and can't seem to solve my problem - I need to filter the child nodes according to the course code entered, but I can only get it to work by entering the course code as text in the js file, when I attempt to use a variable argument it doesn't work and I have tried so many different ways.
HTML...
<html>
<head><title>XML Reader</title></head>
<body>
<input type="text" id="argumentText">
<input type="button" id="button" value="process">
<input type="text" id="outputText">
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
XML...
Will have more coursecodes and child nodes eventually when I can get jQuery to work
<?xml version="1.0"?>
<course type="array">
<coursecode>CWI416D01F
<description>Signmaking L2</description>
</coursecode>
<coursecode>CWI490D01F
<description>Business Admin L2</description>
</coursecode>
<coursecode>CWA061D01S
<description>Dental Nurse L3</description>
</coursecode>
</course>
My jQuery...
Note that the code below does actually work, but the outputVar that is created doesn't use the argumentVar at all...
$('#button').click(function(){
$.ajax({
url: 'test.xml',
type: 'GET',
dataType: 'xml',
success: function(data){
//an argument is taken from the argumentText field
var argumentVar = $("#argumentText").val();
//Doing it this way works
var outputVar = $(data).find('coursecode:contains(CWI416D01F)').children('description').text();
//The outputVar is output as text in the outputText field, in this case "Signmaking L2"
$('#outputText').val(outputVar);
},
error: function(){
}
}); //ajax is closed
}); //click function is closed
But I want the outputVar to take the argumentVar as the text argument in contains() rather than having to set updozens of cases in a switch, I have tried several methods, here are a couple of examples below...
var outputVar =
//Attempt 1
$(data).find('coursecode:contains(argumentVar)').children('description').text();
//Attempt 2
$(data).find('coursecode:contains('"+argumentVar+"')').children('description').text();
//Attempt 3 & 4 (I added an ID into each xml coursecode tag for this attempt)
$(data).find('coursecode[id="argumentVar"]').children('description').text();
$(data).find('coursecode[id=argumentVar]').children('description').text();
I've even tried a bunch of other different ways such as attempting to parse, if statements, filter return functions, you name it. Hopefully there is someone out there who can answer this, ideally with a really simple snippet of code.
This question was answered thanks to Ryan Wilson, here is answer in case anybody else confronting this problem...
$('#button').click(function(){
$.ajax({
url: 'test.xml',
type: 'GET',
dataType: 'xml',
success: function(data){
//an argument is taken from the argumentText field
var argumentVar = $("#argumentText").val();
//This code finds a single xml node using the argumentVar variable
var outputVar = $(data).find('coursecode:contains(' + argumentVar + ')').children('description').text();
//The outputVar is output as text in the outputText field as according to whatever argument the user entered into argumentText
$('#outputText').val(outputVar);
},
error: function(){
}
}); //ajax is closed
}); //click function is closed
Related
I have a problem of clearing out of the text area in my application. The app has two methods of getting a specific data format: searching online database and using a javascript library.
First method: a user types a chemical name in a text field and presses "Search" button. If requested compound is in the database, a proper format is displayed in the text area.
Second method: if the name was not found in the database, then a user can use a JS library to generate a proper format which is displayed in the same text area.
If a user uses database first, the text area contains generated data from the database which can be replaced by data generated by JS library if a user decides to use it. The problem is that if the text area already has data generated by JS library it cannot be replaced by data from the database when first method is used. I don't know how to clear the text area containing data (generated by JS library) before inserting data from the database. Sorry if it still sounds confusing.
Here is a javascript code:
<script>
var sketcher = new ChemDoodle.SketcherCanvas('sketcher', 400, 300, {useServices:true});
var mol = sketcher.getMolecule();
var molFile = ChemDoodle.writeMOL(mol);
function myFunc($data)
{
document.getElementById('txt_area').value = $data
return false
}
</script>
<span onclick="myFunc(ChemDoodle.writeMOL(sketcher.getMolecule()));"
<button href='javascript:void(0)'; type="submit" id="get_mol">Get Mol</button>
</span>
Jquery/ajax:
$('#search').on('click', function()
{
chemical = $('#chemical').val();
$.ajax({
type: "GET",
url: "/_get_smiles",
data : { 'chemical': chemical},
success: function(data)
{
$('#txt_area').text(data.smiles);
},
error: function(error)
{
console.log(error)
}
});
});
HTML:
<input type="text" id="chemical" size="40">
<button type="submit" id="search" value="Search">Search</button>
<textarea id="txt_area" name="smiles_mol" rows="28" cols="49"></textarea>
To clear text area I the methods below but unsuscessfully:
$('#txt_area').text = "";
$('#txt_area').html = "";
$("#txt_area").attr("value", "");
Method $('#txt_area').val(""); clears the text area but prevents inserting data from database. Any comments and suggestions are highly appreciated!
I think you simply need to change the jQuery/AJAX portion to use this:
$('#txt_area').val(data.smiles);
However it's a bit confusing as to how the parts relate to one another since you seem to have two different pieces of JavaScript and two pieces of HTML but haven't written them together. Is that how the file is structured? If one is supposed to be a fallback to the other, it feels like it should be done automatically.
Edit - like this, if I'm understanding correctly:
$('#search').on('click', function() {
chemical = $('#chemical').val();
$.ajax({
type: "GET",
url: "/_get_smiles",
data: {
'chemical': chemical
},
success: function(data) {
if (data.smiles) {
$('#txt_area').val(data.smiles);
} else {
$('#txt_area').val(ChemDoodle.writeMOL(sketcher.getMolecule()));
}
},
error: function(error) {
console.log(error);
$('#txt_area').val(ChemDoodle.writeMOL(sketcher.getMolecule()));
}
});
});
How about $('#txt_area').val(null);?
That's how you clear a textbox but maybe it's something else that's preventing the library from doing its stuff.
If you're certain that there's some weirdness going on with clearing the data, you could try the following in your AJAX callback
$newTextArea = $('<textarea>').attr({ id:'txt_area', name:'smiles_mol', rows:'28', cols:'49'}).text(data.smiles)
$('#txt_area').replaceWith($newTextArea);
This replaces the old text area with a totally new text-area DOM element
I want to know how an I target javascript variable using jquery. Here is situation of my web page where I want to use some details that are stored in javascript variable which I will use in user registration. My page codes looks like this
<html>
<head>
<script>
var userData =
{"country":"null","region":"","timezone":"null","key":"sessionSecret","browser":"Chrome","bversion":"0.0","loggedIn":"false"};
</script>
</head>
<body>
<form id="register">
<button id="regbtn">Register</button>
</form>
</body>
<script src="jquery.js"></script>
<script src="custom.js"></script>
</html>
So now how can I use custom jquery function that will target "userData" variable on click of "regbtn"?
I am doing in my custom javascript is
$( document ).ready(function() {
$('#regbtn').click(function(){
//do something here that will target that userData variable and will send its data using ajax
//$ajax function will send data to page with details that user entered and userData
});
});
But I don't know how to target that userData variable using json. This variable in json data format out put of php. Can anyone help me?
And with negative votes I'd appreciate if you tell me why are you voting negative this question. I am not pro so asked this question. May be this is stupid but not for me. So thank you anyways for seeing this question
If you need to access your json object "userData", you'll want to add the following in your click function:
var country = userData['country'];
var region = userData['region'];
and so on.
You could send the whole object without separation if you plan on sending it via AJAX. Below is an example of this:
$(function() {
var userData = {"country":"null","region":"","timezone":"null","key":"sessionSecret","browser":"Chrome","bversion":"0.0","loggedIn":"false"};
$('#regbtn').click(function() {
$.ajax({
url: "someURL",
data: userData,
type: "POST",
cache: false,
dataType: "json"
}).done(function(data, textStatus, jqXHR) {
// check if response was valid/invalid or do other stuff here
});
});
});
So i have a form like so:
<form>
<input type="submit" value="X" id="deleteButton" onclick="ConfirmChoice(<?php echo $id; ?>)" />
</form>
and a function like this:
<script type='text/javascript'>
function ConfirmChoice(theid)
{
var dataString = 'id=' + theid;
answer = confirm("Are you sure you want to delete this song?");
if (answer !=0) {
$.ajax
({
type: "POST",
url: "deleteSong.php",
data: dataString,
});
}
}
</script>
So basically I want it to delete whatever they click on from my database which deleteSong will take care of.
It gives the id of the song and as far as I know should confirm deletion then delete it right?
Any help would be appreciated.
Thanks
change it from
input type="submit" to
input type="button"
Also because your are not setting it, the request to the server is in json which in your case is badly formed.
Try something like this:
var dataString = "{'id'= '"+ theid + "'}";
this should make it work :)
It's hard to answer this without knowing where exactly the problem is. Is deleteSong.php working correctly?
Like others have said you should change the input type to button or return false from your function, otherwise the browser will try and submit the form in the normal manner but as you haven't specified an action within the <form> tag it won't work properly.
Personally, I would do things quite differently:
HTML:
<input type="button" value="<?php echo $id ?>" id="deleteButton">
Javascript:
$(document).ready(function () {
$('#deleteButton').click(function () {
var answer = confirm("Are you sure you want to delete this song?");
if (!answer) {
return false;
}
var data = 'id=' + $(this).val();
$.ajax({
type: 'POST',
url: 'deleteSong.php',
data: dataString,
success: function (response) {
// response will contain the output from your php script.
// Do something with it here. If you just want to see what it
// says, do something like:
console.log(response);
// then look in the console (view > javascript console in chrome)
}
});
});
});
Just to explain what I'm doing here (sorry if I'm telling you things you already know, I want to be as explicit as possible for anyone who might be reading this in the future:)
I enclose the whole thing in $(document).ready(function() { ... } ); so it only gets run when the page is finished loading, other wise you might end up trying to bind functions to the click action on a button that doesn't exist yet.
if (answer !=0) is redundant, you can just write if (!answer) as any positive integer will evaluate to true
I included a success callback above which might help you in debugging.
Is there only going to be one 'delete' button on the entire page? Or is there going to be a delete button next to every song? If it's the latter, you'll have to give each button a different ID, not just deleteButton because all IDs must be unique.
If the above doesn't work, are you sure that jQuery has loaded correctly? To check, type jQuery in the console, if you don't get an error then you're fine. The other possibility is that something's wrong with your deleteSong.php script but I can't help you there without seeing it.
My question is as follows: I have started using the $.ajax function with jQuery and I am wondering how I work with the return of an HTML page. The request completes and I can console.log the returned HTML page however I would now like to select a single element from that page. I have had several attempts which included:
$(data).find('p');
$('button').click(function() {
$.ajax(funciton() {
dataType: 'html',.
url: 'localhost/sw',
success: function(data) {
// This is where I would like to select a element or node from the complete
// returned html document
});
});
I know i can simply use .load() which you can provide select criteria but .ajax is the root function to begin with and I would like to learn that way as well for more complicated queries. Second half of this would be should I not be trying to select elements this way and just serve up json or a single key phrase instead of the entire html page? All help is appreciated.
Just pass the returned HTML to jQuery, and treat it like a regular jQuery collection:
$.ajax({
dataType: 'html',.
url: 'localhost/sw',
success: function (html) {
var paragraphs = $(html).find('p');
// Manipulate `paragraphs` however you like. For example:
$(document.body).append( paragraphs );
}
});
Joseph's answer above is correct if you just want to get the objects.But if you want to load the content of that element, you may change this:
var paragraphs = $(html).find('p');
to
var paragraphs = $(html).find('p').html();
Hope it helps.
I have a page and I ask them zipcode. While they are filling the form right after they finish writing 5 numbers of zipcode, It will check if it is covered from my database and will show a check or cross sign near it and will disable submit.
To summarize.
Will wait for visitor to type 5 digits zip code( If we can check if customer only enters number it will be a plus and great)
It will check if it is covered in database ( I don't ask for php part. Probably we will send it as POST to a php file)
If it exists in database it will show check else it will show cross and will not allow the form to be submitted.
I checked some websites but couldn't find an exact solution.
Thank you
Probably you need have an image tag besides the zip code text box with the src attribute set to an invisible image. Then perform an ajax upon the blur event.
HTML:
<input type="text" id="zip" name="zip"> <img id="imgconf" src="images/blank.png">
Javascript:
$('#zip').blur(function() {
$.ajax({
url: "script.php",
type: "POST",
data: "zip=" + $('#zip').val(),
dataType: "text",
success: function (data){
if (data=="1"){
$('#imgconf').attr("src", "images/correct.png");
} else {
$('#imgconf').attr("src", "images/wrong.png");
}
}
});
});
For the numeric validation, you may use the same PHP script to return another flag besides "1" and display it in another span element that the data entered is not numeric. Just add another key-value pair in the data part, maybe.
You will need to use AJAX. JQuery has a built in AJAX function. On each keyup event, you can have it run this AJAX function. The PHP should return a value of either 1 or 0 to make it easy. 1 obviously is match, and 0 is no-match.
$('#YourObjectID').keyup(function (event) {
searchZips();
})
function searchZips()
{
var myJSON = $.ajax({
url: options.script + '?Q=' + curValue,
type: 'POST',
contentType: 'application/json',
success: function (msg) {
if(msg==="1"){
// CODE TO SHOW YOUR X DIV
}
}
}
You will want to also add functionality on clearing the search, checking if null or empty string, etc., etc., but this is the basics that should get you going. I use this all the time. Once you get the hang of it, it's VERY useful. Then look into building a jQuery plugin. Once you can do the above functionality, you can build it into a plugin (with tons of cool options!) GOOD LUCK and happy programming.