Yes it is vulnerable, but not it the way you suspect. The attacker would not try modify the loaded URL, but to execute the code directly. For example:
$_GET['fname'] = '"+(function(){/*any_code_i_like*/})()+"';
will become:
$.ajax({
url: "http://mywebsite/script?param="+(function(){/*any_code_i_like*/})()+""
and the code will execute even before requesting the URL with ajax. It's just an example, there are other vectors that would work here too. The simplest way to escape the parameter to prevent XSS in this context would be using urlencode()
in PHP like this:
$.ajax({
url: "http://mywebsite/script?param=<?php echo urlencode($_GET["fname"]); ?>"
dataType: "jsonp",
success: function(response) {
document.write(/*fields from response object*/);
},
});
Also, take a look at OWASP XSS Prevention Cheat Sheet.
Update: After you updated the question - there is no XSS vulnerability here (you can't e.g. point the request to another domain), but the example is vulnerable to a different beast - HTTP parameter polution. It might not matter in this exact case, but imagine that the given parameter is:
a_valid_value¶m=another_param_injected
The attacker is able to inject additional HTTP GET parameters which might be important for your application and might change the execution flow (e.g. parameter admin=1
). You should get into habit of escaping/encoding everything coming from user input. In this modified case you should use Javascript encodeURIComponent
function which prevents attacker from injecting '&','=' and '?':
"http://mywebsite/script?param=" + encodeURIComponent($("#field").val()),