AJAX GET request sending mal-formed URL string - javascript

I have a simple javascript / jquery AJAX request to submit a form to a php file for processing.
I want to send the parameters to the php file via GET.
If I send the parameters to the file using a manually encoded query string the processing works as expected.
An example of the query string is:
http://example.com/processor?param_1=Dogs&param_2=Cats
As noted above, submitting this URL works OK.
When I make the same request using an AJAX call it fails.
If I dump the uri string sent by the AJAX call I see that it has added all the necessary parameters, but replaced & in the string with & - this change causes the call to fail (as the php file does not understand the query).
The query string sent to the AJAX call is:
http://example.com/processor?param_1=Dog&param_2=Cats
I do not understand why the call is being made this way.
Any help with fixing would be most appreciated.
The AJAX call looks like this:
function submitEdit(first_param,second_param) {
$.ajax({
method: "GET",
url: "/content/edit",
data: {
param_1: first_param,
param_2: second_param
},
});
}
Thanks in advance for whatever insights you can offer.

Related

Chrome extension ajax sending malformed accented characters

I am sending an AJAX POST request using jQuery on a chrome extension but the data doesn't arrive as expected, accented characters turn out malformed.
The text "HÄGERSTEN" becomes "HÄGERSTEN".
The text appears fine in the console etc, only via AJAX to this other page it appears as mentioned. My AJAX call is basic, I send a data-object via jQuery $.ajax. I've tried both with and without contentType, UTF-8 and ISO-8859-1. No difference.
This is how I make my AJAX call:
var newValues = {name: 'HÄGERSTEN'}
$.ajax({
url: POST_URL,
type: 'POST',
data: newValues,
success: function() ...
});
The newValues object has more values but I retrieve them from a form. However, I have tried to specify these values manually as newValues['name'] = 'ÄÄÄÄ'; and still would cause the same problem.
The original form element of the page that I am sending the AJAX to contains attribute accept-charset="iso-8859-1". Maybe this matters.
The target website is using Servlet/2.5 JSP/2.1. Just incase it might make a difference.
I assume this is an encoding issue and as I've understood it should be because Chrome extensions require the script files to be UTF-8 encoded which probably conflicts with the website the plugin is running on and the target AJAX page (same website) which is using an ISO-8859-1 encoding, however I have no idea how to deal with it. I have tried several methods of decoding/encoding it to and from UTF-8 to ISO-8859-1 and other tricks with no success.
I have tried using encodeURIComponent on my values which only makes them show that way exactly on the form that displays the values I have sent via POST, as e.g. H%C3%84GERSTEN.
I have no access to the websites server and cannot tell you whether this is a problem from their side, however I would not suppose so.
UPDATE
Now I have understood POST data must be sent as UTF-8! So a conversion is not the issue?
Seems like the data is UTF-8 encoded when it is sent and not properly decoded on the server side. It has to be decoded on the server side. Test it out with the following encode and decode functions:
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
var encoded_string = encode_utf8("HÄGERSTEN");
var decoded_string = decode_utf8(encoded_string);
document.getElementById("encoded").innerText = encoded_string;
document.getElementById("decoded").innerText = decoded_string;
<div>
Encoded string: <span id="encoded"></span>
</div>
<div>
Decoded string: <span id="decoded"></span>
</div>
We too faced the same situation but in our case we always sent the parameters using JSON.stringify.
For this you have to make changes, 1) While making call to the page via AJAX you have to add content-type tag defining in which encoding data is sent
$.ajax
({
type: "POST",
url: POST_URL,
dataType: 'json',//In our case the datatype is JSON
contentType: "application/json; charset=utf-8",
data: JSON.stringify(newValues),//I always use parameters to be sent in JSON format
EDIT
After reading your question more clearly I came to know that your server side JSP uses ISO-8859-1 encoding and reading some posts, I came to know that all POST method data will be transmitted using UTF-8 as mentioned.
POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard
But while reading post jquery-ignores-encoding-iso-8859-1 there was a workaround posted by iappwebdev which might be useful and help you,
$.ajax({
url: '...',
contentType: 'Content-type: text/plain; charset=iso-8859-1',
// This is the imporant part!!!
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
}
});
Above code is taken from Code Posted by iappwebdev
I don't know if it could have been solved using POST-data and AJAX. Perhaps if I made a pure JavaScript XHR AJAX call, I might be able to send POST-data encoded the way I like. I have no idea.
However, in my desperation I tried my final option (or what seemed like it); send the request as GET-data. I was lucky and the target page accepted GET-data.
Obviously the problem still persisted as I was sending data the same way, being UTF-8 encoded. So instead of sending the data as an object I parsed the data into a URL friendly string with my own function using escape, making sure they are ISO-8859-1 friendly (as encodeURIComponent encodes the URI as UTF-8 while escape encodes strings making them compatible with ISO-8859-1).
The simple function that cured my headaches:
function URLEncodeISO(values) {
var params = [];
for(var k in values) params[params.length] = escape(k) + '=' + escape(values[k]);
return params.join('&');
}
The client side character coding is not completely up to you (immagine the usage of the page from different users all around the world: chinese, italian...) while on the server side you need to handle the coding for your purposes.
So, the data in the Ajax-POST can continue to be UTF8-encoded, but in your server side you coan to do the following:
PHP:
$name = utf8_decode($_POST['name']);
JSP:
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");

Calling a php function with ajax

Hi I am using ajax to do a post request. I think what I want to do is call a function within a php file but am a little confused if and how you do this, could anyone shed any light on this? This is what I have in my js file:
function callAjaxAddition2() {
arguments0 = jQuery('#code').val();
$.ajax({
type: "POST",
url: file.php",
data: {code: arguments0},
success: function(data) {
request( $posted )
}
});
return false;
}
'request' is a function within the php file.
Update I think I should be able to trigger what I need to using this: http://docs.woothemes.com/document/wc_api-the-woocommerce-api-callback/ if I put the url into the url field however that doesn't seem to work, how might I use a callback with ajax post?
First fix this line with the missing opening quote file.php".
You cannot call a PHP function through AJAX but can trigger when it needs to be called, the following demonstrates the same:
In your PHP, your code would be:
if(isset($_POST['code'])){
#'code' here is the identifier passed from AJAX
request($_POST['code']);
}
Once your function has been called, does the necessary and returns the output to AJAX, you can use the data parameter you have set to see what output was sent back from PHP:
success: function(data) {
alert(data); //contains the data returned from the
//PHP file after the execution of the function
}
Calling on a php file via ajax call is like running the script that you pass in the url parameter.
You don't get access to the inner functions, all you can do is pass data and get response.
If you want the request() function to be called in the script, you will have to call it in the php script.

Need to get serialized data from a form

I'm new to prototypejs. Can you guys tell me how to get serialized values from a posted form using Ajax in prototype?
http://www.prototypejs.org/api/ajax/request
Is this what you need?
http://prototypejs.org/api/form/serialize
Or you want to handle a form through ajax instead of page load? then
http://prototypejs.org/api/form/request
"how to get serialized values from a posted form using Ajax " Makes it sound like you're expecting the Ajax response to include the serialized data sent to the server, but what the response contains is entirely up to the server. Typically, once you make an Ajax request, the onComplete handler doesn't really care about the properties that it sent. The response argument to the onComplete (and any other Ajax callback) contains a request property, which contains parameters object. This would be useful if you did indeed need to see what your request sent to the server, like so:
$('customerdetails').request({
method: 'get',
onComplete: function(response) {
console.log(response.request.parameters); // What you sent to the server
console.log(response.responseText); // What the server sent back to you
console.log(response.responseJSON); // JSON-ified version of what the server sent back
}
});
It's possible for response.responseJSON to be null if Prototype isn't sure that the response actually contains JSON (if, for instance, the response headers were improperly set). If you can bank on the response being JSON, you could do something like this:
onComplete: function(response) {
var jsonObj = response.responseJSON || response.responseText.evalJSON();
// now you can work with jsonObj
}
Hope this helps and I didn't just completely misunderstand your question.
new Ajax.Request('your_ajax_url',{
method:'POST',
parameters:Form.serialize($('your_form_id'))
});

How to modify the ajax Post data in a beforeSend event?

Hello I have a form that submits remotely with the jQuery UJS for rails. I binded to the beforeSend event to allow me to modify the data submitting to the serve. It's not working. Here is what I have in the beforeSend:
settings.data = JSON.stringify({
'list_item[title]' : 'hi?? there'
})
This doesn't work. In the server logs I see this:
Started POST "/lists/9/list_items" for 127.0.0.1 at 2011-10-24 14:04:36 -0700
Processing by ListItemsController#create as JSON
Parameters: {"{\"list_item"=>{"title"=>{"\":\"hi?? there\"}"=>nil}}, "list_id"=>"9"}
Any idea what I'm doing wrong? I want to customize the settings.data with added fields that aren't in the form. Thanks
You don't need to stringify anything to put it in settings.data. The data is:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. [...] Object must be Key/Value pairs.
What you're doing is putting this string:
"{"list_item[title]":"hi?? there"}"
into data but that string is not a query string so things are going to get confused. You should be able to simply assign your JavaScript object to settings.data:
settings.data = { 'list_item[title]' : 'hi?? there' };
and let jQuery sort it out from there.
Update based on evidence rather than documentation:
However, further investigation reveals that this doesn't work. If I send a GET request, any changes I make to settings.data are ignored but if I send a POST request, then changes to settings.data stick but you have to use the query string format to get anything sensible through:
settings.data = encodeURIComponent('list_item[title]')
+ '='
+ encodeURIComponent('hi?? there');
The version of settings.data combined with a POST request gets me this:
Parameters: {"list_item"=>{"title"=>"hi?? there"}}
on the server and that looks like what you're after. If you want to preserve some of the original parameters then you'll have to unpack and repack the query string by hand.

Error when calling webservice with jquery

I have read a lot about jquery and i have a webservice where i convert a companyID to the real companyName. Now i want to call that webservice with jquery or javascript. The webservice is on host http://webservice/service.asmx en i'm working on http://tlmos. I don't work and i always get an error
Here is my code:
<script type="text/javascript" src="http://kmosvi24/_layouts/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var test = "KBEACDNV";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://webservice/service.asmx/getCompanyByCompanyID",
data: "{'sCompanyID:' + 'test'}",
dataType: "json",
succes:function(response){ alert("good"); },
error: function(response) { alert("Uh oh"); },
complete: function(response) { alert("" + response); }
});
</script>
Can someone help me?
thx
Umm.. you spelled success wrong on line 11
.. and you probably want to format your data as
data: "sCompanyID=test"
Take a quick pass through the jQuery API page on this one to verify you are passing the parameters that your service expects. It looks like you are expecting a SOAP packet with an ASMX service, and jQuery is more suited to hitting a restful service generated from an ASHX file or WCF service.
You can make a request to a different server, but only if the call uses GET. Since all you do is lookup anyway, a GET request should be fine.
As some othe people have pointed out you cannot call a webservice on another domain, however as you are using ASP.NET, you can write a raw HTTP handler (normally with an .ashx extension to proxy your request from client to server.) Which you'd place on your "timos" server
so in your ashx file you can write something along the lines of...
public void ProcessRequest (HttpContext context)
{
XmlDocument wsResponse = new XmlDocument();
string url = "http://webservice/service.asmx/getCompanyByCompanyID?CompanyID="
context.Request.Form["CompanyID"].ToString()
wsResponse.Load(url);
string XMLDocument = wsResponse.InnerXml;
context.Response.ContentType = "text/xml";
context.Response.Write(XMLDocument);
}
Hope this helps.
You can't do AJAX calls to hosts other than your own. If you really have to do this make a call to your own server and use a simple proxy to redirect to the domain you need.
You could do this for example by using a ProxyPass-directive in your webserver:
ProxyPass /service/ http://webservice/service.asmx
ProxyPassReverse /service/ http://webservice/service.asmx
Then you can issue an AJAX-request to /service/getCompanyByCompanyID and it will be proxied to the correct URL.
I don't think you are using the data parameter right, usually it's a key-value pair like:
data: {sCompanyID: 'test'}
I believe that they way you are using it will result in jQuery attempting to post to http://webservice/service.asmx/getCompanyByCompanyID?sCompanyID:blah
Also aren't .NET web services SOAP? I don't think jQuery can parse that...
edit: Nevermind, didn't realize you were passing these as json data. Thanks commenters!
In order to run your web-services from Jquery, you should use either WCF or just usual web services, but you should add [ScriptMethod] to your service's method and [ScriptService] to your webservice description.
Wow wow
just noticed that you're trying to call the service from one host to another... that one won't work. service should be hosted on the same domain as the page where it's being called from.
as a reply to Jeff's answer, correct way to format data is data: {key: "value"}
With jQuery Ajax Requests you need to use the following format when defining the variables to be sent in the request:
data: "variableName=variableContent",
You wrote:
data: "{'sCompanyID:' + 'test'}"
This won't work for two reasons:
- You have included curly brackets which don't need to be there.
- You have used a semi-colon,":", instead of an equals sign,"=".
So long as you change these it should work.
P.S I only just realized that Jeff Fritz has already given you the right answer. His answer is spot on!

Categories