i am trying to make a call to a rest server using jquery/ajax
The rest Server is built in Codeigniter
The ajax function is as follows:
var req = $.ajax({
type: 'GET',
url: "http://localhost/projects/comp6300Server/index.php/resources/token//username/" + email + "/password/" + pword + "/institution/" + inst,
contentType: "application/json; charset=utf-8",
dataType: "json"
})
The request that is generated is as follows:
http://localhost/projects/comp6300Server/index.php/resources/token//username/etambie#yahoo.com/password/qwerty/institution/BCC
The status returned is '400 Bad Request'
I think the problem may be with the email that is passed in "etambie#yahoo.com". Is there a way for the ajax automatically convert the '#' to '%40', or would i have to convert all special characters in my strings manually?
Two things to check out:
The "_" parameter is probably added to that each request is unique. If this isn't done, then the browser may attempt to get the result of calling the URL from it's cache, which is probably not what you want.
On the bad request ... are you sure you want two slashes after the word 'token' in your url?
Related
I'm currently using the following ajax function to send ajax queries.
$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function (htmltwo) {},
error: function (htmltwo) {}
});
The problem is when i send the text which include the operator "&", the items on the right of the operator is deleted. The following is my dataString.
var dataString = 'id=' + id + '&dateoccur=' + dateoccur + '&timeoc=' +
timeoc + '&hitype=' + hitype + '&hid=' + hid;
So e.g if hid is text containing "EEEE&LLLLL", the items on the right of & will be removed when receiving it on the server side. So on the server end, will receive "EEEE". I assume ajax recognizes this because it's part of the dataString variable. How would I be able to solve this issue ?
You could use encodeURIComponent in Javascript to encode characters such as & and then decode them back at the server.
var hidValue = "EEEE&LLLLL";
var hidValueEncoded = encodeURIComponent(hidValue);
console.log(hidValueEncoded);
I always recommend using an object rather than a string. jQuery will then automatically encode everything properly.
var dataString = {
id: id,
dateoccur: dateoccur,
timeoc: timeoc,
hitype: hitype,
hid: hid
};
It's also much more readable, IMHO.
But if you really want to build the string yourself, use encodeURIComponent as in Nisarg Shah's answer. You should do this for all parameters, unless you're sure they don't contain any special characters.
On site1.domain.com I am running a greasemonkey script that takes in user credentials to authenticate to site2.domain.com and pull the entire page and parse out a server generated token that is needed to complete the rest of the script running on site1.domain.com and then make another URL GET to site2.domain.com.
xmlhttp.open("GET", url, false, username, password );
is the call I'm attempting but I'm receiving the error "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied". I looked around and I understand that there are complications with this type of functionality but I haven't figured out what I need to do in this situation.
EDIT: Tried this using verisons of the code below but receiving Cross-domain error for any datatype other than jsonp but with jsonp I recieve "htmlString is undefined". I also tried defining the return value as a String and in that case I received "6" (without any manipulation).
var htmlString = getPage(url,username, password);
var index = htmlString.indexOf("Token");
//some other code that parses out just the token, shown as "finalString" in the end
$("#logMessage").text (finalString);
function getPage(url, username, password) {
return $.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
async: false,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', btoa(username + ":" + password));
}
}).responseText;
}
I encountered a very peculiar problem and none of the answers I found here solves it.
On SOME clients (IE7, IE8) when I post the data using jQuery Ajax, such as:
$.ajax({
type: 'POST',
url: '<%= ResolveUrl"~/User.svc/GetUserListForCity") %>',
data: '{"city":' + cityId + '}',
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
success: processList,
error: showErrorAlert
});
The error I am getting:
"The OperationFormatter could not deserialize any information from the Message because the Message is empty (IsEmpty = true)."
However when I attempt to use Fiddler to look at the data, the request is successful.
The server is IIS and the request is served by WCF Web Service (webHttpBinding). Removing contentType to allow defaults is being rejected by the server as it expects JSON.
Any suggestions are very appreciated.
Try this.. look's like you are sending data object is wrong
data: {"city": cityId }, // If cityID is a string this should do
OR
data: '{"city":"' + cityId + '"}',
There might also be a problem with the way you are sending the url.. Try using a absolute path and check if that works..
When I put ":))" in my textarea and send via ajax, it inputs into the database a value like
"jQuery172039628539560362697_1345324072488", how can I stop this? Should I parse my text in some way in javascript first to make it recognize it's text, and not part of the javascript coding?
This is how i get my text
var message = $("textarea.message_thread").val();
var dataString = 'id=' + id + '&message=' + message;
// make ajax call
sending with
$.ajax(
{
type: "POST",
url: "/inbox/instsend",
data: dataString,
dataType: 'json',
success: function(results) {}
}
See the comments under the question; the problem is that what has been submitted in dataString is actually a url-encoded string, and not a JSON-izable or JSON literal variable.
Hence:
dataString = {id: id, message: message};
Will fix this problem, here. jQuery will take that object-initialized variable and encode it for you to JSON.
This is done automatically by jQuery when you're using JSONP for cross-domain AJAX calls. It should be sending this string as the value of the callback parameter.
You need to sanitise the input and escape any control codes - e.g. : and )
Since you are doing POST here. This would work
var dataString = '{'+'id:' + id + 'message:' + message +'}'
I'm attempting to make use of the Beanstalk (beanstalkapp.com) API by pulling data into a webpage so people can view it without accessing my SVN.
What I'm doing to try and access it is by using an AJAX request through jQuery. The code is below, but I get an error each time, and can't return the data.
<script type="text/javascript">
$(document).ready(function() {
var tok = 'username' + ':' + 'password123';
hash = btoa(tok);
authInfo = "Basic " + hash;
$.ajax({
url: "http://username.beanstalkapp.com/api/changesets.json",
beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", authInfo); },
type: "GET",
async: false,
crossDomain: true,
dataType: "json",
success: function(html){
console.log(html);
},
error: function(html){
console.log('error');
}
});
});
</script>
If I access the URL straight through my browser (http://username.beanstalkapp.com/api/changesets.json) it works just fine and returns the json. However, I cannot get the AJAX to return it. Any help is appreciated. Thanks!
You will need to make proxy for cross-domain ajax requests.
Usual scenario looks like this:
Client send ajax request to server
Your server forwards request to external/remote server
Waiting on response from remote server
Parse and process response from remote server
Send response back to client
If you are using php you can send requests with curl, and it is pretty easy to implement. I have wrote article on this topic recently http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/.
you cant get a json from other domain than yours. this is a security issue called same origin policy to get over it use JSONP not JSON.
Check this jsfiddle. The username and password is incorrect. Give the correct username and password and check it once again.