slim framework and ajax. '/' character as a parameter - javascript

I'm making an ajax call to a Slim framework web service. This is for sending notes to my database.
The problem is that the users can write for example "send 1/2 piece". So when I make the call, the URL throws 404 not found because of the '/' character.
Is there any way to avoid this problem?
notes = 'send 1/2 piece'
$.ajax({
type: 'GET',
url: 'http://Myserver/orders/notes/' + MyOrder + '/' + notes,
dataType: "json", // data type of response
beforeSend: function(xhr, settings){
},
success: function(data){
},
error: function(xhr, status, errorThrown){
errorPopup(errorThrown);
},
complete: function(xhr, status){
}
});

You need to run EncodeURIComponent against notes, only.
Before your ajax call:
notes = 'We have funny characters in here like /es';
encNotes = EncodeURIComponent(notes);
Then, create your url string using the encoded string.
url: 'http://Myserver/orders/notes/' + MyOrder + '/' + encNotes,

Related

POST file data with AJAX is appending unknown jquery callback string

I'm building a configuration file web editor that lets the user edit settings in a textarea, converts the contents to a Blob file, and then POST the data to a remote API. For some reason, it's appending a random callback parameter and I have no idea where it's coming from...
http://ipaddr:8080/compile?callback=jQuery341029448751790349491588432312011&=1588432312012
Here is what the code looks like. If anyone can point me in the right direction, I would greatly appreciate it.
<script>
$(document).ready(function() {
$('#btnCompile').click(function(event) {
// Convert TextArea contents to a Blob file
var configText = $('#configuration').val();
configText = configText.replace(/\n/g, "\r\n"); // retain line breaks
var configFile = new Blob([configText], { type: "text/plain" });
var documentData = new FormData();
documentData.append('file', configFile, "configuration.cpp");
$.ajax({
url: "http://ipaddr:8080/compile",
method: "POST",
data: documentData,
dataType: 'jsonp',
crossDomain: true,
cache: false,
contentType: false,
processData: false,
success: function(data, textStatus, jqXHR)
{
alert('success: ' + textStatus);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error status: ' + textStatus + ' error message: ' + errorThrown);
}
});
});
});
</script>
You said dataType: 'jsonp' and so your request is subjects to the limitations of JSONP (including being a GET request, putting data in the query string, adding a callback argument, and being unable to set custom request headers).
If you don't want that (and everything about your code indicates you don't), don't use JSONP. It's a dreadful hack with a security risks that was superseded by CORS over a decade ago.

Send ajax GET request to ASP .NET Web API

I use the following ajax script.
$.ajax({
dataType: 'json',
url: url,
data: tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
The attribute Route in Web API before method.
[Route("api/tudisp/Edit/{tuDispId}")]
public IHttpActionResult Edit(int tuDispId)
{
}
The genarated request from ajax.
http://localhost:xxxxx/api/tudisp/Edit/?179
How to force ajax to not generate sign '?' by id parameter.
The simplest way to do it is to change the url property of the Ajax options...
$.ajax({
dataType: 'json',
url: "http://localhost:xxxxx/api/tudisp/Edit/" + tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
GET parameters are automatically appended to the Url as a querystring, which is fine if that's what your application is expecting, but not when you're using routing as you are.
However, if you wanted to modify existing Ajax requests you can use prefiltering. This example modifies the Url of the ajax call, replacing {variable} with a given value from the data object...
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.data = ""; // this removes the querystring
for (key in originalOptions.data) {
options.url = options.url.replace("{" + key + "}", originalOptions.data[key]);
}
});
$.ajax({
url: "http://localhost:xxxxx/api/tudisp/Edit/{tuDispId}",
data: {
"tuDispId": 179
}
});
If you wanted to use something like that then I'd strongly recommend spending a bit of time making it more robust, but it's an example of how you could do what you want.

Access array in Javascript

I cannot seem to understand why I cannot access an array I get send back by PHP.
I send this back when AJAX makes a call: $response['success'] = true;
I do this by echo json_encode($response); in my PHP file.
Now I want to access it in Javascript, but response.success doesnt work, it logs 'undefined' in the console. Now I check the response, and that is this: {"success":false}
But if I check for if(response.success) it always sends back false, because response.success is undefined. Does anyone know what I mean and what is causing this issue?
This is my AJAX call:
$$.ajax({
type: 'POST',
url: url + "applogin.php",
crossDomain: true,
data: {
username: e,
password: p
},
//dataType: 'json',
success: function(response) {
console.log(response);
if (response["success"]) {
window.localStorage["username"] = e;
window.localStorage["password"] = md5(p);
mainView.router.loadPage('beurslist.html');
} else {
console.log("Your login failed");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText)
},
});
The answer by #SZenC is fine, there's a point though about best practices:
The reason jQuery didn't recognize the response as JSON is because the server probably didn't send a Content-type header, so just add to your server-side code a call to -
header('Content-type: text/json');
You won't need the explicit call to JSON.parse in each API call, you'll get better integration with test tools, and your app will be better self-documented for other folks who use/will-use this code (including yourself should your code need some future maintenance).
In any case it is advised also to document the expected input on the client side by either explicitly specifying dataType as json or by making the API call using a shortcut method such as $.getJSON().
Your ajax-call will return a string, you need to decode it with JSON.parse. You'd get something like this then.
$$.ajax({
type: 'POST',
url: url + "applogin.php",
crossDomain: true,
data: {
username: e,
password: p
},
//dataType: 'json',
success: function(r) {
var response=JSON.parse(r)
console.log(response);
if (response["success"]) {
window.localStorage["username"] = e;
window.localStorage["password"] = md5(p);
mainView.router.loadPage('beurslist.html');
} else {
console.log("Your login failed");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText)
}
});

Cross Domain AJAX POST / HTTPS / Header Authentication?

I have to issues:
1) I've tried using JsonP, but can't get POSTing to work. Essentially, I'm trying to authenticate with an API, passing a Base64-encoded namevaluepair in the header over HTTPS.
2) How do I pass this key/value in the header? Any help would be appreciated! Here is an example of what I want, though this obviously doesn't work:
// where does this go?
var headerString = 'user=' + encodeURIComponent(username + ':' + password);
$.ajax({
type: "POST",
url: "https://anotherurl.on.another.server/LOGIN",
data: "I have no data, I'm logging in with header authentication",
dataType: "json",
success: function(data) {
},
error: function(data){
}
});
add headers to ajax call:
var headerObj = {'user': encodeURIComponent(username + ':' + password)};
$.ajax({
type: "GET",
url: "https://anotherurl.on.another.server/LOGIN",
data: "I have no data, I'm logging in with header authentication",
dataType: "json",
headers: headerObj,
success: function(data) {
},
error: function(data){
}
});
The best way to do this is probably through a server side proxy on your own domain.
See this page for tips.
This way you will be able to get the response from the other server

Posting to YouTube API with jQuery

I am trying to post a request to the google authSub for youtube. I use jQuery for AJAX posts etc. When I make the POST I get a 405 error: "405 Method Not Allowed".
Here is my js:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
},
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
});
The page I am using in the API for this is here.
Here is what the error looks like:
Your data parameters for the request are misplaced see below:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
data: {
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
}
});
Now it may be something youre doing wrong additionally, but this for sure needs to be corrected.
Ah, here is a solution to the problem. If I make the request with the url built out and assigned as an href to an anchor or call it in window.open(); it works.
window.open('https://www.google.com/accounts/AuthSubRequest?scope=http://gdata.youtube.com&next=http://' + globalBrand + '/sitecreator/view.do&session=1');
As for why jQuery's method with the ajax was being rejected I know not. It seems to be an issue elsewhere also.
Solution to error HTTP HEADER OPTIONS in JQuery, this request is ok for me:
var word = 'search+word';
$.ajax({
type: "GET",
url: "http://gdata.youtube.com/feeds/api/videos?q="+word+"&max-results=10&alt=json-in-script&format=5,
cache: false,
dataType:'jsonp',
success: function(data){
//json 'data' var treatment
},
error: function(XMLHttpRequest, textStatus, errorThrown, data){
alert("Not able to fetch the data due to feed unavailability!!!");
}
});
Reference: http://www.mohammedarif.com/?p=180

Categories