I have a script that makes an ajax request to the server. Then the server returns HTML code. After the request finish, I want to take the HTML code and put it on my site.
The problem that I am having is that the function .html() will display the html as text instead of making it an html.
Here is what I have done
var postData =
{
'campaign_id': 1,
'page_role': 'intro'
};
$.ajax({
type: 'POST',
url: 'url/to/get/html',
data: postData,
dataType: "text",
beforeSend: function(jqXHR, settings){
$('#MasterContentViewer').html('<div class="well innerwell">' +
'<h3>Please wait while loading the next page</h3>'+
'</div>');
},
error: function( jqXHR, textStatus, errorThrown ){
alert('Loading content failed! Error Code: ' + jqXHR.status);
},
success: function(page){
$('#MasterTable').removeClass('heightForIFrame');
$('#MasterContent').removeClass('heightForIFrame');
$('#MasterContentViewer').html(page);
}
}).done(function(page) {
var tags = $("meta[name^='is_system_'],meta[name^='is_attr_']" );
$.each(tags, function(index, tag){
var value = $(tag).attr('value');
var name = $(tag).attr('name').replace('is_attr_', '').replace('is_system_', '');
$('#attr_' + name + ':input').val( value );
$('#attr_' + name).not('input').text( value );
$('.attr_' + name + ':input').val( value );
$('.attr_' + name ).not('input').text( value );
});
I tried to change the following like
$('#MasterContentViewer').html(page);
to
$('#MasterContentViewer').empty().append(page);
which also did not work.
I also tried to change the dataType from "text" to "html" which also did not work.
How can I make the force the page to display html code instead of text?
UPDATED
Here is sample of what the user sees on the screen
<strong>Store Name: </strong><span class="attr_storename"></span> </div> <div class="scripter_header_label"> <strong>Store Number: </strong><span class="attr_alt_id_1"></span>
If .html(string) is appending elements as text, then that means that the elements are already HTML Encoded (e.g., <'s are in the string as >'s). jQuery will only encode html if you tell it to by using .text(string) instead of html(string).
Two possible solutions are:
Modify your server-side code to send non-encoded HTML
HTML Decode the string using Javascript (I would not recommend this method, however, because it caters to HTML Injection attacks).
Related
test.xml
<Bock1>
<No>123</No>
<RoomNo>10</RoomNo>
<UpdateTime>1230</UpdateTime>
</Block1>
run.js
$.ajax({
type: "GET",
url: test.xml,
dataType: "xml",
success: function (xml) {
$(xml).find('Block1').each(function () {
var updateTime = $(this).find("UpdateTime").text();
var no= $(this).find("No").text();
var roomNo = $(this).find("RoomNo").text();
var status = no + '<br/>' + roomNo + '<br/>' + updateTime;
});
}
});
$('<div>')
.attr({
'data-role': 'collapsible', 'data-collapsed': 'false', 'data-mini': 'true'
})
.html('<h4>' + item_name + '</h4><p>' + status + '</p>')
.appendTo(collapsibleset);
}
});
I'm using this to generate collapsibleset with xml data,
but status can't correctly fill into
<p> + status + </p>
status will get correctly inside ajax, but can't get to collapsibleset.
I've tried to use global variable, but get same situation.
How could I fill it in correctly?
I'm new to jquery & javaScript,
Thanks for any answers!!!
jQuery.ajax() is expecting string for the URL value.
Therefore your URL just needs wrapping in quotes.
Then your DOM reference of the
$('< div >')
is wrong.
To reference an element in JQuery, you have several options, but the easiest is to give an element an id and then reference that (think CSS)
$('div') would get all divs
$('div#my_id') would get this particular element:
I have an a tag that is dynamically generated with database content, it includes a data-target that I capture in javascript when it is clicked on, this is an example of one of the generated buttons:
Edit
Simple, right?
Now, what I do in the JS when it is clicked, is as so:
var $this = $(this),
$target = $this.data("target"),
$endpointURL = "";
$endpointURL = $target.split("?id=")[0];
$id = $target.split("?id=")[1];
This allows me to set the endpoint I want, in out example above, it would be "edit" and also set the id which is just a number at this point.
Now, I have to POST this ID to the edit endpoint to return the right info, correct?
So, here is my AJAX for that:
$.ajax({
type: "POST",
data: '{"id": ' + $id + ' }',
url: "../assets/scripts/php/" + $endpointURL,
success: function (data) {
$("#content-lockup").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error: " + textStatus + ", error thrown: " + errorThrown);
}
});
This does not throw an error and does indeed output a var dump of the $_POST array as I have set it to, however it doesnt contain my ID that I passed over, here is the code on the endpoint and a screenshot of the output:
<?php
var_dump($_POST);
?>
Why would the vardump on $_POST not contain the id that I passed over in the apparently successful AJAX request?
What I expect is that I can say on the endpoint, something like:
$id = $_POST['id'];
Maybe its something obvious that i'm doing wrong but yeah, any ideas?
it's because you are passing a string to data that isn't form encoded
Make it an object and jQuery will encode it for you
data: {"id": $id },
If it's a string it needs to be in format
data: 'id=' +id + '&someOtherParam=' + somevar
I have a div popup and there are some links that show this popup.
the problem is here that the content of popup will be different depending on what user click on links:
//my div popup
<div id="show-popup">
<p>$value</p>
</div>
//one,two and three values fetch from database by using Ajax.
show popup = the value must be one
show popup = the value must be two
show popup = the value must be three
now, I don't know how to send 1,2,3 to database by Ajax then how to open that popup after fetch value from database .
I know by below method I can send some value to my url but how I can open popup and then load new value on this popup ?
$.post('myurl' , {id:id} , function(data){
//do stuf
})
Use .html() ; chain .show() to .html() if element is not displayed before click.
To append data instead of replacing existing data at #show-popup , substitute .append() for .html()
function toGetValues(id) {
$.post("myurl", {id:id}, function(data) {
// do stuff
// `.html()` replaces `html` of `#show-popup`
$("#show-popup").append("<p>$" + data + "</p>")
// .show()
})
}
You can also try this
function toGetValues(myvar)
{
$.ajax({
url: "test.php",
type: "post",
data: {mypar: myvar},
success: function (response) {
$( "#show-popup").html(response);
$( "#show-popup").dialog();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
$.get( "url", {id: id} ).done(
function( data ) {
$("#show-popup").append("<p>" + data + "</p>");
});
You will get the id from the onclick event you have just to send it and put the the value you get back as responce from your PHP page to the paragraph p using text() :
function toGetValues(id)
{
$.post("myurl", {id:id}, function(value) {
$("#show-popup p").text(value); //append returned value from php to the paragraph
$("#show-popup").dialog(); //Show popup
})
}
Is there any way to get the text inside an element which is a response from an ajax jquery load. I need to get the text inside element which is present inside the response text from ajax page. Following is my ajax code:
var url = '...';
var saveData = $.ajax({
type: 'POST',
url: url,
data: {data : data},
dataType: "text",
success: function (resultData) {
callback(resultData); // need to get the <h2> text here..
}
});
saveData.error(function () {
console.log("Request to API not send");
});
You can pass HTML to jQuery and use it in the same way as if the element was on the DOM, for example with find():
console.log( $(resultData).find('h2').text() );
If your HTML doesn't have a root element then you can wrap it like so:
resultData = '<div>' + resultData + '</div>';
console.log( $(resultData).find('h2').text() );
How about:
$(resultData).find('h2').text()
I have 41 JSON objects, each with the same scheme.
These objects are fairly large, and so I would like to load the object conditionally into a JavaScript script, when selecting an <option> from a <select> menu with an id of myPicker.
So far, I have set up jQuery to handle changes on the <select>:
$('#myPicker').change(function() {
alert('Value change to ' + $(this).attr('value'));
$('#container').empty();
init();
});
The function init() draws stuff in div called container.
When I change myPicker, I want init() to behave like init(value), which in turn tells init to load one of 41 JSON objects from a file (based on value).
Is loading a chunk of JSON from a file (located on the server-side) doable in this case, or do I need to use a server-side script handling Ajax form submissions and responses, etc.?
EDIT
I wrote the following code:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$('#cellTypePicker').change(function() {
alert('Value change to ' + $(this).attr('value'));
$('#container').empty();
initFromPicker($(this).attr('value'));
});
});
function initFromPicker(name) {
// pick default cell type from picker, if name is undefined
if (typeof name === "undefined")
name = 'AG10803-DS12374';
var jsonUrl = "file://foo/bar/results/json/" + name + ".json";
alert(jsonUrl);
$.ajax({
url: jsonUrl,
dataType: 'json',
success: function(response){
alert("Success!");
},
error: function(xhr, textStatus, errorThrown){
alert("Error: " + textStatus + " | " + errorThrown + " | " + xhr);
}
});
init(); // refills container...
}
</script>
<body onload="initFromPicker();">
...
The line alert("Success!"); never gets called.
Instead, I get the following error:
Error: error | Error: NETWORK_ERR: XMLHttpRequest Exception 101 | [object Object]
I am checking the value jsonUrl and it appears to be a proper URL. The file that it points to is present and I have permissions to access it (it is sitting in my home folder). Is there something I am still missing?
Let me make sure I understand your question. I think you want to:
have a handful of files out there that contain JSON objects
depending on which option is selected a particular file is loaded
the contents of the file is JSON and
you want to be able to use the JSON object later on in other javascript
If this is the case then you would just need to do something like:
$('#myPicker').change(function() {
$('#container').empty();
init($(this).val());
});
function init(jsonUrl){
$.ajax({
url: jsonUrl
dataType: 'json'
success: function(response){
// response should be automagically parsed into a JSON object
// now you can just access the properties using dot notation:
$('#container').html('<h1>' + response.property + '</h1>');
}
});
}
EDIT: Exception 101 means the requester has asked the server to switch protocols and the server is acknowledging that it will do so[1]. I think since you're using file://foo/bar/... you might need to toggle the isLocal flag for the $.ajax function [2], but honestly, I'm not sure.
[1] http://en.wikipedia.org/wiki/Http_status_codes#1xx_Informational
[2] http://api.jquery.com/jQuery.ajax/
Below is a complete working example that pulls a JSON object from Twitter, so you should be able to copy/paste the entire thing into a file and run it in a browser and have it work. If your server is configured correctly and your .json files are in the document_root and have the appropriate permissions, you should be able to swap them out for the Twitter URL and have it work the same way...
<!doctype html>
<html>
<head>
<title>My Super Rad Answer</title>
</head>
<body>
<form id="my-form">
<select id="cellTypePicker">
<option value=''>No Value</option>
<option value="AG10803-DS12374">AG10803-DS12374</option>
</select>
</form>
</body>
<!-- Grab the latest verson of jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
// Wait until the page is fully loaded
$(document).ready(function(){
$('#cellTypePicker').change(function() {
// Grab the value of the select field
var name = $(this).val();
if (!name) {
// Make sure it's not null...
// This is preferred over using === because if name is
// anything but null, it will return fale
name = 'AG10803-DS12374';
}
// Right now I'm overwriting this to a resource that I KNOW
// will always work, unless Twitter is down.
//
// Make sure your files are in the right places with the
// right permissions...
var jsonUrl = "http://api.twitter.com/help/test";
$.ajax({
url: jsonUrl,
dataType: 'json',
success: function(response){
// JSON.stringify takes a JSON object and
// turns it into a string
//
// This is super helpful for debugging
alert(JSON.stringify( response ));
},
error: function(xhr, textStatus, errorThrown){
alert("Error: " + textStatus + " | " + errorThrown + " | " + xhr);
}
});
});
});
</script>
</html>
You can use $.ajax() for this - or one of the shortcuts, e.g. $.getJSON():
$.getJSON('somefile', function(data) {
// here, data is javascript object represented by the json in somefile
});