Extend jQuery AJAX Function - javascript

I'm using the HTML5 Neptune framework, to create SAPUI5 applications. At runtime my code gets inserted into the index.html file, mixed in between the code generated from the framework.
In a part of the code below the code area I control, the framework creates an ajax function I would like to modify. I would like to inject code into the jQuery AJAX success callback function. I this possible?
<html>
<head></head>
<body>
<form>
<div id="MobileContent"></div>
<input type="hidden" name="applid" value="XXX">
</form>
<script>
var JSONH, jsonh = JSONH = function(n, r) {
//Framework code
}(Array, JSON);
// framework code
...
// my code
...
// framework code
...
function getOnlineXxx(value) {
$.ajax({
type: "POST",
contentType: "application/json",
url: "neptune_ajax?ajax_id=xxx=" + value + "",
dataType: "json",
data: encodeURIComponent(modelXxx.getJSON(),
success: function(data) {
// framework code
// code I would like to execute!!!
}
});
}
....
jQuery(function() {
jQuery("form").submit(function(event) {
event.preventDefault();
return false;
});
});
</script>
</body>
</html>

Related

PHP & JS - append html and scripts on page

I'm using an ajax call to append a MVC partial view with some styles sheets and script files to my php page.
However it is not appending de <script> tags. I already checked my HTTP request on the network and it really brings those tags.
My code:
$.ajax({
type: 'POST',
url: 'http://localhost:63322/MyController/MyAction', //external url project
data: JSON.stringify(parameters),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
crossDomain: true,
processdata: true,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Headers": "*"
},
success: function(result){
$(".pageContainer").html(result);
},
error: function(er){ alert('Error'); }
});
On ajax success function I already tried:
to use $(".pageContainer").empty().append(result)
to separate the script tags and add to <head> like this:
var elems = $(result);
var scripts = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() == "script";
}catch(er){ return false; }
});
var remainElems = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() != "script";
}catch(er){ return false; }
});
$.each(scripts, function(){ $('head')[0].appendChild(this); });
$(".pageContainer").append(remainElems);
to give some time before appending with setTimeout(function(){ $(".pageContainer").html(result); }, 1000);
to change <script> tags to <link type="text/javascript" src="http://someurl.com" rel="tag"/> and it was appended but the code wasn't executed
But nothing works.
What is wrong? What I'm missing?
My PHP page uses jquery-1.8.3 and jquery-ui-1.9.2.custom. This is the problem?
NOTE:
My question is very different from that on: Executing inside retrieved by AJAX
If you read both you will see they are very different. I already readed what and noticed that.
Solved. I don't know why but seems jquery-1.8.3 don't performs the insertion of the <script> tags to the html code dynamically.
I changed
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
to
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
and now it works.

Including javascript file along with ajax response

I've got a dropdown that runs AJAX each time an option is selected. The ajax call returns HTML markup (buttons and text boxes) and a script tag, which the HTML(buttons) uses to submit to a database via ajax.
<html>
<head>........</head>
<body>........</body>
<select class="chooseOption">
...
...
</select>
<div class="ajaxResult">
<!-- after successful ajax -->
<!-- HTML Markup here -->
<!-- I'm having to include main.js here again so that HTML matkup can use AJAX -->
</div>
....
....
....
<footer> //include main.js </footer>
This arrangement seems to work fine only that, there's an exponential call to main.js each time an option is selected.
Doing something like this(below) doesn't seem to work, I'm guessing because AJAX is injected into the page and isn't aware of what scripts that are already available on the page?
<script>
var len = $('script').filter(function () {
return ($(this).attr('src') == 'main.js');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
var url = "main.js";
$.getScript(url);
}
</script>
Is there a simple way around this? To make sure that main.js works across all AJAX requests without having to include it with each request?
Sample main.js content.
Ajax snippet that populates the HTML Markup (buttons and textboxes)
$("#students").on("change", function (e) {
e.preventDefault();
var supervise = this.value;
var faculty = $("#faculty").val();
$.ajax({
method: "POST",
url: 'URL',
dataType: 'html',
data:
{
selectValue: supervise,
faculty: faculty
},
success: function (result) {
$("#ajaxResult").html(result);
}
})
});
When #statement_button from HTML markup returned from select dropdown is clicked
$('#statement_button').click(function (e) {
var student_statement = $("#student_statement").val();
if (student_statement == '') {
alert('Please enter your statement');
return false;
}
var student = $("#student").val();
var statement_button = $(this).attr("value");
$.ajax({
type: "POST",
url: formsUrl,
dataType: 'text',
data:
{
student_statement: student_statement,
student: studentusername,
statement_button: statement_button
},
success: function (result) {
$("#result").text(result);
$("textarea#student_statement").val('');
}
})
});
From the code you posted it looks like you can just delegate the button handling to the .ajaxResult element which is always present in the html (from the initial load).
So just changing how you bind your button handlers should be enough
$("#students").on("change", function (e) {
to
$('.ajaxResult').on('change', '#students', function (e) {
$('#statement_button').click(function (e) {
to
$('.ajaxResult').on('click', '#statement_button', function (e) {
etc..
So the script with the above code is run once in the initial load of the page (in a $(document).ready(..))

Unable to pass my Model from my Controller to my View using Jquery.Ajax

I'm relatively new to web app development, javascript and MVC so please bear with me.
I want to use the Jquery.Ajax command to post my Model to my controller.
My View:
#model MVC_Interface_May21.Models.DataValuesViewModel
...
<form method="post" id="testForm">
<input type="submit" class="subButton" value="Add New.." />
</form>
...
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>
$(document).ready(function () {
$('#testForm').submit(function (e) {
e.preventDefault();
#{var val = Json.Encode(Model);}
var check = '#Html.Raw(val)';
$.ajax({
url: 'Results/AddNew',
type: 'POST',
//data: JSON.stringify(check),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
}
...
</script>
I haven't included the code for my Model or Controller because I don't believe they are a part of the problem. Currently, my code simply posts back to the same page. As far as I can tell the ajax command is not being executed. The debugger doesn't help me in tracing the behavior, and I am assuming that the form is simply doing it's post submit and ignoring my function.
Any help is much appreciated, and I'm sorry if this has been answered in the past. I developed my code by looking at other solutions, but I can't identify what's making mine dysfunctional.
You have to read more about it MVC, im not even sure what you are trying to do serializing the Razor Model like that, but that is what you are getting from the server, not your HTML Form with whatever the user input is.
You can use this js function to submit a form with Ajax.
$(function () {
$('#myForm').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
And use the Create Form and imput helpers/
#Html.BeginFor
#Html.EditorFor

Parsing xml data from a remote website

I would like to parse the xml data from a remote website http://services.faa.gov/airport/status/IAD?format=xml...But I was not able to parse the xml data and I am only getting error. But I was able to parse the JSON data from the same remote website http://services.faa.gov/airport/status/IAD?format=json. The code I have used to parse the xml data is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Aviation</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=xml",
dataType: "xml",
success: function (xml) {
result = xml.city;
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
I was only getting the error as 'o Error' in the alert box since I have printed the error message. Anybody please helpout to parse the xml data from the remote website.
Note: I have also 'City' instead of 'city' but its not working...
Thanks in advance...
I don't believe that will work since the service is still returning xml. jsonp is expecting a n object literal as an argument to pass to the callback. I believe if you run this locally you'll realize there's no data being consumable in your success. Try this
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=json",
dataType: "jsonp",
success: function (data) {
document.myform.result1.value = data.city;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Here is the example for creating a proxy with asp.net mvc 3. I just created an action that returns a ContentResult which maps to a string but I define the content type as text/xml. This simply just makes a webrequest to the service and reads the stream in to a string to send back in the response.
[HttpGet]
public ContentResult XmlExample()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.faa.gov/airport/status/IAD?format=xml");
string xml = null;
using (WebResponse response = request.GetResponse())
{
using (var xmlStream = new StreamReader(response.GetResponseStream()))
{
xml = xmlStream.ReadToEnd();
}
}
return Content(xml, "text/xml");
}
Your xmlParser function will look like this:
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "XmlExample",
dataType: "xml",
success: function (xml) {
result = $(xml).find("City").text();
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
jQuery ajax's converts the data by using $.parseXML internally which removes the requirement for us to even call this in the success block. At that point you have a jQuery object that you can use it's default DOM functions to find the City Node.
Make sure to replace the XmlExample with the url that it maps to based on your controller.
The solution is quite simple (mentioned in Pekka's comment)
1.On your server add a file IAD_proxy.php
2.Put the following code inside it
header("Content-type: text/xml; charset=utf-8");
echo file_get_contents('http://services.faa.gov/airport/status/IAD?format=xml');
3.Change the url in your Ajax request to IAD_proxy.php.
In case you're using any other server-side language, try to implement the same idea.
Edit: Please read about Parsing XML With jQuery, here's what I've tried and it's working.
Javscript:
$.ajax({
type: "GET",
url: "IAD_proxy.php",
dataType: "xml",
success: function (xml) {
alert($(xml).find('City').text());
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
Here I tried it with document.write($(xml).find('City').text());

calling a javascript function inside .js file vs html page

I am having some trouble calling a javascript function inside of the html page. When I move the function inside the linked/external file it works fine. Can anyone help with this?
Here is my external file.js
function request_token(session) {
$.ajax({
url: api_url,
data: {api_id: api_id},
dataType: "jsonp",
jsonp : "callback",
success: function(data) {
var token = data.token;
alert(token)
}
});
};
And here is just the simple call to the function that I want to load once the document is ready...
<script>
$(document).ready(function() {
request_token('1234');
});
</script>
When I move request_token('1234'); into the file external file, it works fine
use jQuery's getScript() function.
<script>
$(document).ready(function() {
$.getScript('external.js');
request_token('1234');
});
</script>
Reference

Categories