ajax interview questions
Top ajax frequently asked interview questions
In my ajax call, I want to return a string value back to the calling page.
Should I use ActionResult or just return a string?
Source: (StackOverflow)
Using jQuery, how can I cancel/abort an Ajax request that I have not yet received the response from?
Source: (StackOverflow)
I either dreamt about chrome (dev channel) implementing a way to update the address bar via javascript (the path, not domain) without reloading the page or they really have done this.
However, I can't find the article I think I read.
Am I crazy or is there a way to do this (in Chrome)?
p.s. I'm not talking about window.location.hash, et al. If the above exists the answer to this question will be untrue.
Source: (StackOverflow)
I am trying to send data from a form to a database. Here is the form I am using:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and Ajax, is it possible to capture all of the form's data and submit it to a PHP script (in example, form.php)?
Source: (StackOverflow)
I have a JavaScript widget which provides standard extension points. One of them is the beforecreate
function. It should return false
to prevent an item from being created.
I've added an Ajax call into this function using jQuery:
beforecreate: function (node, targetNode, type, to) {
jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
function (result) {
if (result.isOk == false)
alert(result.message);
});
}
But I want to prevent my widget from creating the item, so I should return false
in the mother-function, not in the callback. Is there a way to perform a synchronized Ajax request using jQuery or any other API?
Source: (StackOverflow)
Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?
For example, if I want to throw an exception on the server side via Struts by throw new ApplicationException("User name already exists");
, I want to catch this message ('user name already exists') in the jQuery AJAX error message.
jQuery("#save").click(function () {
if (jQuery('#form').jVal()) {
jQuery.ajax({
type: "POST",
url: "saveuser.do",
dataType: "html",
data: "userId=" + encodeURIComponent(trim(document.forms[0].userId.value)),
success: function (response) {
jQuery("#usergrid").trigger("reloadGrid");
clear();
alert("Details saved successfully!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
On the second alert, where I alert the thrown error, I am getting undefined
and the status code is 500.
I am not sure where I am going wrong. What can I do to fix this problem?
Source: (StackOverflow)
I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?
My specific situation: I have an array defined as shown below:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...
and I need to turn this into a string to pass to $.ajax()
like this:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: "{'countries':['ga','cd']}",
...
Source: (StackOverflow)
Why does Google prepend while(1);
to their (private) JSON responses?
For example, here's a response while turning a calendar on and off in Google Calendar:
while(1);[['u',[['smsSentFlag','false'],['hideInvitations','false'],
['remindOnRespondedEventsOnly','true'],
['hideInvitations_remindOnRespondedEventsOnly','false_true'],
['Calendar ID stripped for privacy','false'],['smsVerifiedFlag','true']]]]
I would assume this is to prevent people from doing an eval()
on it, but all you'd really have to do is replace the while
and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.
I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, Google Docs starts with &&&START&&&
instead, and Google Contacts seems to start with while(1); &&&START&&&
.
What's going on here?
Source: (StackOverflow)
I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?
Source: (StackOverflow)
I have implemented an AJAX request on my website which I am calling from a webpage. It always returns 200 OK but jQuery executes the error event. I tried a lot of things but could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# Code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted")
string after successfully deletion. I am able to delete content but I am not getting this message. Is this correct or am I doing anything wrong. Please suggest the correct way to solve this issue.
Source: (StackOverflow)
In Firefox 3, the answer is 6 per domain: as soon as a 7th XmlHttpRequest (on any tab) to the same domain is fired, it is queued until one of the other 6 finish.
What are the numbers for the other major browsers?
Also, are there ways around these limits without having my users modify their browser settings? For example, are there limits to the number of jsonp requests (which use script tag injection rather than an XmlHttpRequest object)?
Background: My users can make XmlHttpRequests from a web page to the server, asking the server to run ssh commands on remote hosts. If the remote hosts are down, the ssh command takes a few minutes to fail, eventually preventing my users from performing any further commands.
Source: (StackOverflow)
Here are two pages, test.php and testserver.php.
test.php
<script src="scripts/jq.js" type="text/javascript"></script>
<script>
$(function() {
$.ajax({url:"testserver.php",
success:function() {
alert("Success");
},
error:function() {
alert("Error");
},
dataType:"json",
type:"get"
}
)})
</script>
testserver.php
<?php
$arr = array("element1",
"element2",
array("element31","element32"));
$arr['name'] = "response";
echo json_encode($arr);
?>
Now my problem: when both of these files are on the same server (either localhost or web server), it works and alert("Success")
is called; If it is on different servers, meaning testserver.php on web server and test.php on localhost, its not working, and alert("Error")
is executing. Even if the URL inside ajax is changed to http://domain.com/path/to/file/testserver.php
Source: (StackOverflow)
I've seen a couple questions around here like How to debug RESTful services, which mentions:
Unfortunately that same browser won't allow me to test HTTP PUT, DELETE, and to a certain degree even HTTP POST.
I've also heard this, that browsers support only GET and POST, from some other sources like:
However, a few quick tests in Firefox show that sending PUT
and DELETE
requests works as expected -- the XMLHttpRequest
completes successfully, and the request shows up in the server logs with the right method. Is there some aspect to this I'm missing, such as cross-browser compatibility or non-obvious limitations?
Source: (StackOverflow)
Since the upgrade to iOS 6, we are seeing Safari's web view take the liberty of caching $.ajax
calls. This is in the context of a PhoneGap application so it is using the Safari WebView. Our $.ajax
calls are POST
methods and we have cache set to false {cache:false}
, but still this is happening. We tried manually adding a TimeStamp
to the headers but it did not help.
We did more research and found that Safari is only returning cached results for web services that have a function signature that is static and does not change from call to call. For instance, imagine a function called something like:
getNewRecordID(intRecordType)
This function receives the same input parameters over and over again, but the data it returns should be different every time.
Must be in Apple's haste to make iOS 6 zip along impressively they got too happy with the cache settings. Has anyone else seen this behavior on iOS 6? If so, what exactly is causing it?
The workaround that we found was to modify the function signature to be something like this:
getNewRecordID(intRecordType, strTimestamp)
and then always pass in a TimeStamp
parameter as well, and just discard that value on the server side. This works around the issue. I hope this helps some other poor soul who spends 15 hours on this issue like I did!
Source: (StackOverflow)