PHP/JQuery/AJAX, few teething problems - html

Morning/Afternoon guys.
Writing some JQuery AJAX shizz and getting a bit stuck. I've got the actual proccess of calling the php file done perfectly, its just trying to get the html on the page to change in a way I want it to. I want to get rid of the a with the id of the one used in the ajax call etc, and replace it with the html passed from the PHP file. Code is as follows...
$(".save_places").click(function() {
$.ajax({
url: "{/literal}{$sRootPath}{literal}system/ajax/fan_bus.php",
type: "POST",
data: ({id : this.getAttribute('id')}),
dataType: "html",
success: function(msg){
$(this).before(msg);
$(this).empty();
alert(msg);
}
});
return false;
});
And the HTML is pretty simple;
<p class="links">
<img src="{$sThemePath}images/save_places.png" alt="Save to My Places" />
<img src="{$sThemePath}images/send_friend.png" alt="Send to a Friend" />
</p>
All the stuff in the success function is experimental mashing of code, any help please?
Thanks as always.

I think what you're after is .replaceWith(), like this:
$(this).replaceWith(msg);
This replaces the <a></a> with the content coming back in msg.
Also, if you're sure the elements have IDs, you can just do this:
data: {id : this.id},

linksPara.replaceChild(newElements, oldAtag);

Related

HTML from ajax request console logs as object

I am requesting some HTML content via an API using jQuery ajax. The data I get back console logs as an object, even when I parse it with jQuery.
Here is what I am doing
$.ajax({
url: ajaxUrl,
success: function(data){
var html = data
var parseData = $(html);
console.log(parseData);
}
});
I have tried dataType it made no difference. I have tried to find elements within the data return, but that returns the same.
The data I am returning does not have a doctype, html or body tag.
<div class="item">
<h2>Title</h2>
<p>...</p>
</div>
<div class="item">
<h2>Title</h2>
<p>...</p>
</div>
<div class="item">
<h2>Title</h2>
<p>...</p>
</div>
Am I doing something wrong, or is the data being returned wrong?
EDIT
Here is the console log
This is absolutely correct that you get an object in your console.
By default jQuery tries to guess the type of the content (what they call an "intelligent guess") and in your case it probably thinks this is HTML. Probably - because you did not provide us with an example of the thing you are asking.
After jQuery thinks this is HTML, it wraps it into a jQuery object, which I guess you see in your console.
Try to call console.log(data.find(".item").length) - I have a feeling the result will be 3.
To get the pure HTML you must use a dataType: "text". This will stop jQuery from attempts of parsing the data and will give you the raw string result.
Try the below
$.ajax({
url: ajaxUrl,
dataType: "html"
})
.done(function( html ) {
console.log( html );
});

JQuery selecting dynamically generated html without adding event (with live)

Several posts on stackoverflow say to use live to select dynamically generated html. However you need an event like click to use live. What do you do if you just want to use .val or .html and change the element instead of adding an event handler?
(Solution with live: Jquery not working with dynamically created table)
I am generating code through:
$.ajax({
url: "/JobFeed/JobFeed.php",
type: "POST",
dataType: "html",
success: function(html) {
$("#jobFeed").html(html);
}
});
The html once generated looks like this (with the form repeated several times):
<div id="jobFeed" class="contentContainer">
<div id="jobs">
<div class="job">
<form class="subscription">
</form>
</div>
</div>
</div>
I then add inputs with:
$("form .subscription").html("<input ... />");
You can use a plugin called "livequery" and do something like this:
$(selector).livequery(function(){
});
As you can see, there is no click or other event that you must use.
Plugin link: http://docs.jquery.com/Plugins/livequery
On github: https://github.com/brandonaaron/livequery
Hope this helps :-)

Why is Html.Raw escaping ampersand in anchor tag in ASP.NET MVC 4?

I have a URL I would like to render in an anchor tag as-is in a Razor view. I would have thought Html.Raw would be the way to go:
#{
string test = "http://someurl.com/someimage.png?a=1234&b=5678";
}
<div>
Test
</div>
But this doesn't work. The ampersand gets encoded and the HTML is rendered as:
<div>
Test
</div>
The strange thing is that if I do the Html.Raw call outside of the anchor tag, the HTML output is as expected:
<div>
#Html.Raw(test)
<div>
is rendered as:
<div>
http://someurl.com/someimage.png?a=1234&b=5678
</div>
Can anyone explain why this is?
Edit:
Tried a few other things out, and found that the following works as expected:
<div data-url="#Html.Raw(test)"></div>
outputs:
<div data-url="http://someurl.com/someimage.png?a=1234&b=5678"></div>
To add a little more context, my goal is not actually to use the URL in an anchor tag, since hrefs can be HTML encoded and still work (I just used the anchor tag case as an example). Rather I wish to use the URL in an <object> <param> value tag for a Flash object. The Flash object doesn't properly recognize the HTML encoded URL, but I can't get the raw URL to output correctly.
I am at a loss. Time to break out the MVC source code I guess...
This is happening because something in the pipeline (I'd guess razor but I'd need to look it up) attribute encodes all attribute values. This should not affect the browser from reaching your desired location however.
You can test this with the #Html.ActionLink(text, action, routeAttributes) overload.
#Html.ActionLink("Test", "Index", new { tony = "1", raul = 2 })
outputs
Test
In regards to your edit, you just need to make the entire <param> part of your raw value.
#{
var test = "<param src=\"http://someurl.com/someimage.png?a=1234&b=5678\">";
}
<div>
<object>
#Html.Raw(test)
</object>
</div>
Like this:
#{
string test = "http://someurl.com/someimage.png?a=1234&b=5678";
}
<div>
Test
</div>
produces valid markup:
<div>
Test
</div>
But this doesn't work. The ampersand gets encoded and the HTML is
rendered as:
But that's exactly how a valid markup should look like. The ampersand must be encoded when used as an attribute. Don't worry, the browser will perfectly fine understand this url.
Notice that the following is invalid markup, so you don't want this:
<div>
Test
</div>
Try
<div>
Test
</div>
just try below...
It works perfect.
#{
string test = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="+#ViewBag.Token;
}
<div>
#Html.Raw(System.Web.HttpUtility.HtmlDecode(test))
</div>
why don't you use jquery to post the url:
$(function () {
$('form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: { a:'firstvalue', b: 'secondvalue'},
success: function (result) {
//code for successful result
}
});
return false;
});
});
in controller
public ActionResult Fetch(string a, string b)
{
//write required codes here
return View();
}

Cannot see js in mvc page using Firebug

I have a separate js file where I put my js. I can't even get into the js to debug it to see what the problem is.
Firebug prior to this page has inline js I can see (from my master page (_Layout.cshtml).
Once I get into this page, I get this from Firebug:
No Javascript on this page
If tags have a "type" attribute, it should equal "text/javascript" or "application/javascript". Also scripts must be parsable (syntactically correct).
I don't know what I'm missing to simply fill this dropdownlist.....
Here is my new js file with the contents:
$(document).ready(function () {
GetCategories();
});
function GetCategories() {
$.ajax({
type: "POST",
url: "Index/Category",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var listItems = "";
for (var i = 0; i < data.length; i++) {
listItems += "<option value='" + data.CategoryID + "'>" + data.Description + "</option>";
}
$("#Categories").html(listItems);
}
});
}
Here is the content of the html page. Note that my html is in my masterpage. So, I just need a simple script here...
<div title="JSON callback for dropdownlist">
<table>
<tr>
<td>
<select id="Categories">
</select>
</td>
</tr>
</table>
</div>
<script type="text/javascript" src="../../Scripts/JSON_DDL.js"></script>
Here is my result:
[{"CategoryID":1,"Description":"ECommerce","Projects":[]},{"CategoryID":2,"Description":"Medical","Projects":[]}]
I've had similar problems in the past with Firebug.
One course of action is that Firebug has crashed and is not reading properly, close and reopen the brower. It's not as common a problem as it used to be, but it does happen.
The second problem took me a long time to find when it happened to me... and it sent me crazy for a couple of hours - but the solution was very simple - sometimes if your JavaScript syntax is bad (e.g. missing a closing curly brace) it won't be read and the browser won't even display an error. Double check your code carefully.

How to append JSON data into an HTML element inside an AJAX call

I'm unsure how to append a Python value into an actual HTML element with JSON and AJAX. This is what I currently have, and below that is the ideal output as a list element. I'm not sure where to include the actual HTML element in the function. Currently it just spits out the unformatted data (obviously).
jQuery
$.ajax({
url: url,
dataType: "json",
data: {'tag_title': tag_title, 'function': 'tag_add'},
success: function(data) {
$('.related-questions ul').html(data['question_title']); }
});
HTML
<li>Why is the sky blue?</li>
Also, ideally I could chain multiple data in the success function into one HTML element, like...
<li>Why is the sky blue?<span>14th December 2011</span></li>
in success function try:
alert($('.related-questions a').html());
Since it seems you're just trying to get some html content for your page, try jQuery's load() function. Instead of sending json back to the browser, your python function could return simple "text/html". For example:
HTML
<ul class="myContainer">
</ul>
Javascript
$("ul.myContainer").load(myUrl, {'tag_title': tag_title, 'function': 'tag_add'});
HTML after:
<ul class="myContainer">
<li>New Content with <b>whatever</b> tags you want</li>
</ul>
Look at .load() here