I have a onclick function in which there is a javascript function that runs to fetch data from xml. it is with jquery. but its not working. help plzzz.
jsp page
<script>
function read() {
$.ajax({
url: "dictionary.xml",
datatype: "xml",
success: function data() {
$("ul").children().remove();
$(data).find("word").each(function () {
var info = '<li>Eng = ' + $(this).find("eng").text() + '</li><li>Beng = ' + $(this).find("beng").text() + '</li>';
$("ul").append(info);
});
}
});
}
</script>
<script src="WEB-INF/js/jquery.min.js" type="text/javascript"></script>
<script src="WEB-INF/js/jquery-2.1.0.min.js" type="text/javascript"></script>
<ul></ul>
Read
xml file
<?xml version="1.0" ?>
<corporate>
<word>
<eng>Male</eng>
<beng>Man</beng>
</word>
<word>
<eng>Female</eng>
<beng>Woman</beng>
</word>
</corporate>
Here you describe a function with no arguments, but with a local name:
success: function data() {
So, when you try to access data, you actually pass your function to jQuery, which does not make too much sense.
success: function data() {
$(data).find("word").each(... // here, data is a function
data should be an argument:
success: function(data) {
$(data).find("word").each(... // here, data is an XML object, passed to a handler
<script src="WEB-INF/js/jquery.min.js" type="text/javascript"></script>
<script src="WEB-INF/js/jquery-2.1.0.min.js" type="text/javascript"> </script>
remove any of these, as this will create two references to $ object.
put them into header or body tag, but before your script.
working version
function read() {
$.ajax({
url: "test.xml",
datatype: "xml",
success: function (data) { //change it to function(data)
console.log(data);//check what is comming...
$("ul").children().remove();
$(data).find("word").each(function () {
var info = '<li>Eng = ' + $(data).find("eng").text() + '</li><li>Beng = ' + $(data).find("beng").text() + '</li>';
$("ul").append(info);
});
}
});
}
Related
I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});
I have a JSON file called person.json. JSON file is in the data folder.
This is the JSON data:
{
"name": "Goa Wei",
"age": 31,
"phone": "202-555-0104",
"group": 3
}
I have the html code to display information in a div class called containerDatadump when clicking on <input id="get" type="submit" value="Get"></input>. I have written the following Javascript code.
var container = $("div.containerDatadump");
$(document).ready(function () {
$("input#get").click(function () {
$.ajax({
type: "GET",
url: "data/person.json",
dataType: "json",
success: function (data) {
$.each(data, function (index, item) {
$.each(item, function (key, value) {
container.append(key + " :" + value + "</br>");
});
container.append("<br/></br>");
});
}
});
});
});
I have done this. I try my best to debug the problem but couldn't succeed.
Can anyone help me figure out what is wrong with my code? It would really help me.
My answer looks like that of forgo but i think you can improve you code a little bit by using $.getJSON instead of a regular ajax call.
$.getJSON is a shorthand ajax call for (more info):
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
I also used JSON Generator for the data (LINK) to prevent browser issues.
Your code is a much cleaner this way (in my opinion).
$(document).ready(function () {
var container = $(".containerDatadump");
$("#get").click(function () {
$.getJSON("https://www.json-generator.com/api/json/get/ceoSrTPote?indent=2", function(data){
$.each( data, function( key, val ) {
container.append(key + " :" + val + "</br>");
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="containerDatadump"></div>
<input id="get" type="submit" value="Get"></input>
I think the biggest problem is that you defined your container outside of your $(document).ready function. This means that your markup doesn't exist yet to properly get a handle on your containerDatadump class.
I made a temporary JSON file hosted on a remote server using this JSON Generator tool to test. Otherwise, I run into CORS issues in my browser.
{
"phone": "202-555-0104",
"age": 31,
"group": 3,
"name": "Goa Wei"
}
With this data, I have modified your function to simplify the loop in your ajax success handler, and I have placed the container variable assignment inside the ready function so that it works properly:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var container = $("div.containerDatadump");
$("input#get").click(function() {
$.ajax({
type: "GET",
url: "http://www.json-generator.com/api/json/get/bOxnwzyhIO?indent=2",
dataType: "json",
success: function(data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key + " -> " + data[key]);
container.append("<div>" + key + " :" + data[key] + "</div><br/>");
}
}
}
});
});
});
</script>
</head>
<body>
<input id="get" type="submit" value="Get"></input>
<div class="containerDatadump" />
</body>
</html>
What i require? I need to get a total share count using javascript.
Using this link: https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=http://google.com
I can get the result:
receiveCount({"url":"http://google.com","count":11278})
My code which is not working, i'm not sure which part of the code is wrong. Below:
#pin-div {
color: red
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
<div id="pin-div">0</div>
<script type="text/javascript">
$(function() {
var url = "http://facebook.com";
var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;
$.ajax({
url: apiUrl,
success: function(result) {
$.each(result, function(key, val) {
console.log(key + " - " + val["receiveCount"]["count"]);
var shareCount = val["receiveCount"]["count"];
$("#pin-div").html(shareCount);
});
}
});
});
</script>
Your data is jsonp: receiveCount({"url":"http://google.com","count":11278}). Where the receiveCount function must be created in the window context to hold the data.
You need to add: dataType: "jsonp" in your $.ajax code.
You can try with this version of your code:
#pin-div {
color: red
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
<div id="pin-div">0</div>
<script type="text/javascript">
$(function() {
var url = "http://facebook.com";
var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;
$.ajax({
url: apiUrl,
dataType: "jsonp",
success: function(result) {
receiveCount(result);
}
});
});
function receiveCount(data) {
$("#pin-div").html(data.count);
}
</script>
I have one html page which contains a jquery function.
<script>
function loadCustomers() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getCustomers',
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td><a href="clientSiteInfo.html?client=">'+id+'</td><td>'+value+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadCustomers;
</script>
I have linked another html page for each row. When each rows populated, the id values has to be passed to the clientSiteInfo.html page.
In the clientSiteInfo.html page i have another jquery function similar to above.
<script>
function loadSites() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getSite?clientName='+${param.client},
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadSites;
</script>
in the GET url I try to read client parameter. But it is not passing from my initial page.
What Im doing wrong here? I look for simple solution
jQuery doesn't have a native way to read the url parameters. However, javascript works just fine:
function getParameterByName(name) {
const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' ') );
}
In your code you would just call it as getParameterByName('client')
I have a script like this.
The jQuery ajax loads all my files with no issues.
The ajax_load_books.php file have lot of css and js(inline edit, sliders etc.) files in it.
The problem is:
How to load all the files before the success function so that the user can see the loader_div message untill all the files are loaded.
In other words - Load all the js/css files and proceed with the success function.
Even I have checked with .load() function. Could someone redefine the below code .
<script type="text/javascript">
$(document).ready(function () {
$(".form-control").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "ajax_load_books.php",
data: dataString,
cache: false,
beforeSend: function () {
$("#loader_div").show();
},
success: function (html) {
$("#loader_div").hide();
$("#txtHint").html(html);
}
});
});
});
</script>
Thanks,
Kimz
For the css files, you can find them using jQuery.parseHTML() function, but the <script> will be stripped with this so instead we would have to use regex for the <script> tags.
Try:
<script type="text/javascript">
$(document).ready(function () {
$(".form-control").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$("#loader_div").show();
$.ajax({
type: "POST",
url: "ajax_load_books.php",
data: dataString,
cache: false,
beforeSend: function () {
//parsing <link>
var $str = $('<output>');
//loading html into fake tag
$str.load("ajax_load_books.php");
//now $str includes all your page code
temp = $.parseHTML(str);
$.each(temp, function (i, el) {
//finding the <link> tag
if (el.nodeName == 'LINK') {
//appending it to the <head> tag
$('head').append("<link rel='stylesheet' href='" + el.getAttribute('href') + "'>");
}
});
//for script we will use regex
var pattern = /<script[^>]+?>.*?<\/script>/gi;
var matches = str.match(pattern);
var scripts = "";
for (var i in matches) {
scripts += matches[i];
}
//appending script tag to <head>
$('head').append(scripts);
},
success: function (html) {
$("#loader_div").hide();
$("#txtHint").html(html);
}
});
});
});
</script>
Demo
There is a drawback with this, your stylesheets and script code will repeat. If the above code causes issue running because of the repetition, you should place the code of beforeSend() before the AJAX and have a parameter sent from your AJAX function indicating that when an AJAX is called with this parameter, to execute all the HTML except the stylesheets and js scripts.