Hey guys, how can I preload an external XML file in Javascript/jQuery?
This is my XML loader:
jQuery.ajax({
type: "GET",
url: dictionaryList,
dataType: ($.browser.msie) ? "text/xml" : "xml",
success: function(xml) {
var xml2 = load_xml(xml);
var i=0;
$(xml2).find('wordle').each(function(){
$(xml2).find('w').each(function(){
var tmpHold = $(this).text();
if (tmpHold.substring(0, 1) == letter) {
if ($(this).attr('p') == 1) {
wordColor = 'color: #693030';
} else {
wordColor = 'color: #5a5a5a';
}
$('#wordList').append('<li class="w" style="'+wordColor+';">'+$(this).text()+'</li>');
}
});
});
}
});
one possibility, and it sounds like this is what you want, would be to send the response document, (xml) above, to a variable that could be processed on-demand at a later time based on some event.
the stored xml document, and the xml processing function, would live in an object, and the xml processing function would be called based on an event trigger rather than the ajax success event. if this doesn't make sense let me know and i can provide some sample code ...
also, i'd recommend adding an error: function to the ajax call if you don't already have one in place.
I think it's good to keep backend xml generator/retriever script in case if you want to get xml from a different domain.
jQuery.ajax({
type: "GET",
url: XML_GENERATE_BACKEND_URL, // data.xml, /generate/xml etc.
..
..
..
Sultan
Related
is it possible to call a page of another website from an ajax call ?
my guess is that is possible since connection is not denied , but i can't figure out how to make my ajax call works , I am calling a list of TV Channels of a website , but I am getting no results , would you please see if my script contains any errors
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl+"&callback=?",
data: "channelType="+all,
type: 'POST',
success: function(data) {
$('#showdata').html(data);
},
error: function(e) {
alert('Error: '+data);
}
});
}
showValues();
html div for results
<div id="showdata" name ="showdata">
</div>
Ajax calls are not valid across different domains.you can use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also, you need to ensure thatJSONP has to also be implemented in the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
You can try this :
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl,
data: channelType="+all,
type: 'POST',
success: function (data) {
//do something
},
error: function(e) {
alert('Error: '+e);
}
});
}
I have made a booking system that utilizes FullCalendar; though that part should be irrelevant. My problem is that upon saving an appointment, a 'notes' field I have created very occasionally has this strange string inserted into it, generally at a random point in the string. Here is the latest example:
Has this been changedjQuery1112010047650896012783_1444929292744 with Rich- finishing sleeve off.bringing deposit in on saturday. told him space isnt secure.
As you can see, there is a totally out of place "jQuery1112010047650896012783_1444929292744" placed in the middle of the note. I can't find anything about this online (mainly because I have no idea what terms I'd use to find it). It must be related to jQuery, considering the string.
I am using jQuery v1.11.2 - obviously the string looks like a long version number.
Why is my ajax request seemingly succeeding, but placing this message in the middle of the sent string? I cannot replicate this issue at all, especially this time since it was another user who managed to cause it.
The function that fetches/prepares/sends data looks like this:
function postForm(content, action, update) {
loader('show');
var popup = content.parent();
var children = content.find(".input");
var data = {}
var elements = [];
data['elements'];
$( children ).each(function() {
var child = {};
child['name'] = $(this).attr('data-name');
if ($(this).is(':checkbox')) {
child['value'] = $(this).is(":checked");
} else {
child['value'] = $(this).val();
}
elements.push(child);
});
data.elements = elements;
data.request = action;
dataPost = JSON.stringify(data);
console.log(dataPost);
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
return false;
}
The note section is just a textarea with the class 'input' (which is looped through and fetched).
I don't think there will be a solution for the exact problem, however, I'm looking for an explanation for the modification of the string. The application works perfectly, except for this very rare case.
Question marks (??) are replaced with a jQuery time stamp. To fix, I had to add jsonp: false to the parameters. Final ajax:
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
jsonp: false,
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.
My Script to call ajax
<script language="javascript">
function search_func(value)
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
</script>
HTML
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.
For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.
When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.
Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.
I believe I had explained up to reader knowledge.
You should check if the value has changed over time:
var searchRequest = null;
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "sample.php",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
EDIT:
The searchRequest variable was added to prevent multiple unnecessary requests to the server.
Keep hold of the XMLHttpRequest object that $.ajax() returns and then on the next keyup, call .abort(). That should kill the previous ajax request and let you do the new one.
var req = null;
function search_func(value)
{
if (req != null) req.abort();
req = $.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
Try using the jQuery UI autocomplete. Saves you from many low-level coding.
First i will suggest that making a ajax call on every keyup is not good (and this why u run in this problem) .
Second if you want to use keyup then show a loading image after input box to show user its still loading (use loading image like you get on adding comment)
Couple of pointers. Firstly, language is a deprecated attribute of javascript. In HTML(5) you can leave the attribute off, or use type="text/javascript". Secondly, you are using jQuery so why do you have an inline function call when you can do that with jQuery too?
$(function(){
// Document is ready
$("#sample_search").keyup(function()
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg)
{
//Receiving the result of search here
}
});
});
});
I would suggest leaving a little delay between the keyup event and calling an ajax function. What you could do is use setTimeout to check that the user has finished typing before then calling your ajax function.
Hi Am new to Jquery/ajax and need help with the final (I think) piece of code.
I have a draggable item (JQuery ui.draggable) that when placed in a drop zone updates a mysql table - that works, with this:
function addlist(param)
{
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');}
});
}
but what I cannot get it to do is "reload" another page/same page to display the updated results.
In simple terms I want to
Drag & drop
Update the database
Show loading gif
Display list from DB table with the updated post (i.e. from the drag & drop)
The are many ways of doing it. What I would probably do is have the PHP script output the content that needs to be displayed. This could be done either through JSON (which is basically data encoded in JavaScript syntax) or through raw HTML.
If you were to use raw HTML:
function addlist(param)
{
$.ajax(
{
type: 'POST',
url: 'ajax/addtocart.php',
data: 'img=' + encodeURIComponent(param),
dataType: 'html',
beforeSend: function()
{
$('#ajax-loader').css('visibility','visible');
},
success: function(data, status)
{
// Process the returned HTML and append it to some part of the page.
var elements = $(data);
$('#some-element').append(elements);
},
error: function()
{
// Handle errors here.
},
complete: function()
{
// Hide the loading GIF.
}
});
}
If using JSON, the process would essentially be the same, except you'd have to construct the new HTML elements yourself in the JavaScript (and the output from the PHP script would have to be encoded using json_encode, obviously). Your success callback might then look like this:
function(data, status)
{
// Get some properties from the JSON structure and build a list item.
var item = $('<li />');
$('<div id="div-1" />').text(data.foo).appendTo(item);
$('<div id="div-2" />').text(data.bar).appendTo(item);
// Append the item to some other element that already exists.
$('#some-element').append(item);
}
I don't know PHP but what you want is addtocart.php to give back some kind of response (echo?)
that you will take care of.
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');
success: function(response){ /* use the response to update your html*/} });