how to decode serialize url from javascript in php - javascript

please consider following snippet
i have submited a form which contains a background image url , i have serialize the form data . in php the URL is not decoding , how to get orignal url
$("#slider_settings_form").submit(function(e) {
var postData = $(this).serialize();
submited form
$.ajax({
url: ajaxurl,
data: {
"params": postData,
"action": "saveFormSettings"
},
method: "POST",
success: function(response) {
alert(response);
},
});

Use string urldecode( string $str ) function to decode your encoded URL data
for more follow this link

A successful parsing could be done by adding urldecode like this:
parse_str(urldecode($_REQUEST['params']), $params);
urldecode is important because it converts url encoded string into parsable string.

If you want to achieve it from javascript you can use these methods:
var uri = "http://stackoverflow.com/questions/30587877/how-to-decode-serialize-url-from-javascipt-in-php"
var uri_enc = encodeURIComponent(uri); //for encoding
var uri_dec = decodeURIComponent(uri_enc); //for decoding
Here is the link for more details:
Url decode and encode

Have a look at this related question.
We need to see how you're decoding the data in PHP to help you, but in addition to the answer ahead of mine (suggesting the use of urldecode), you should also make sure postData actually has data in it.
Only "successful controls" are serialized to the string [...] - second answer
It's entirely possible postData is nil. You should test it by alerting it and go from there. The question I linked to has a more thorough answer with code examples.

var postData = $(this).serialize(); -- this would create a query string like 'a=1&b=2', where a and b are form fields. You might want to fetch the value of a or b -- the following code will help you:
parse_str($_GET['params'], $params);
// then you can use $params['a'] to fetch form field 'a'
print_r($params);
// =>
//Array
//(
// [a] => 1
// [b] => 2
//)
For more about parse_str, see http://php.net/manual/en/function.parse-str.php

Related

Struts 1.3 Ajax call Japanese character encoding issue

I am using Java 1.7 and struts 1.3 framework. I am working for Japanese client. Currently my requirement is to send Search key (containing Japanese string) to the Action class using JQuery Ajax call. But at the action side I found some Japanese character are corrupted.
My code:
var searchKey = $('#searchtxt').val();
// some Japanese string value for search.
var data = {
// other properties
"searchKey": searchKey,
// Other properties
};
$.ajax({
type: 'POST',
url: url,
data: data,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (resultData){//dostuff}
});
I am quite new to SO I don't know how to format.
I have tried many solution on SO but not work for me. Any help will be appreciated.
Thank you for any help.
To solve this Japanese encoding problem, use URL Encoding mechanism and then send data through ajax call. And then at the Struts action side simply you need to decode it by using URL decoder mechanism.
It will solve this problem.
For the more clarity see the below code.
At the Java script side while fetching data from the hidden field use URL encoding method:
var searchKey = encodeURIComponent($('#searchtxt').val().trim());
// It will encode the Japanese string before send from Ajax call.
At the Struts Action side use URLDecoder class to decode the string value:
String searchKey=form.getSearchKey();
if(!searchKey.isEmpty()) //Check for empty or null string
{
// Decode the string using URLDecoder class from java.net package
form.setSearchKey(URLDecoder.decode(searchKey, "UTF-8"));
}

IE11 inteprets AJAX POST reply as string, despite being JSON array

From an JQuery AJAX post request the server sends me an reply that just says Hello, and I want to get that Hello as a string.
I wrote this code to get the text value:
var posting = $.post(
"https://server/bla",
{
input: theinput
}
);
posting.done(function( reply ) {
console.log(reply);
console.log(typeof reply);
console.log(reply[0]);
}
It works perfectly on Firefox 55:
Array [ "Hello" ]
object
Hello
... but IE11 seems to believe it is a string (same code):
["Hello"]
string
"[\"Hello\"]"
I wrote a hackish workaround that just uses substring to remove the brackets and quotes at the beginning and end if the variable is a string, but it does not handle well quotes within the reply (Hell"o becomes Hell\"o).
Is there a cleaner solution?
By the way, here is the server side Java code:
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
jsonArray.put("Hello");
As tipped by Rory, the datatype parameter helps here.
dataType Type: String The type of data expected from the server.
Default: Intelligent Guess (xml, json, script, text, html).
I rewrote the query part to this:
var posting = $.ajax({
type: "POST",
url: "<%=addResUrl%>",
data: {
input: theinput
},
dataType: "json"
});
Note the dataType: "json".
And now it works in IE11 the same way as in Firefox: The JSON is recognized as JSON.

Difference between filter_input and direct acces on $_POST after objective ajax request

I have different results by using filter_input(INPUT_POST, 'attribute') and $_POST['attribute'] and don't know why this happens.
The Post-Request is send by a JavaScript build with JQuery and looks like that:
// type javaScript
var formData = {
field_a: "valueA",
field_b: "",
field_c: undefined
};
$.ajax({
url: 'serverAddress',
data: {action: 99, formData: formData},
dataType: 'json',
method: 'post',
success: function(){
console.log(arguments)
}
});
My PHP-Script looks like that:
// type php
$requestMethod = INPUT_POST;
$response = [
"fi-result" => filter_input($requestMethod, 'formData'),
"direct-result" => $_POST['formData'];
];
echo json_encode($response);
the result what is coming back is not what i was awaiting because the access via filter_input returns falsein my tests and not an json object like the direct access on the super global $_POST.
// type json response
{
"fi_result": false,
"direct-result": {
"field_a": "valueA",
"field_b": ""
}
}
Why are there differences between using filter_input and direct access on $_POST?
I don't want to access the super global $_POST. Is there any way to use filter_input like above without encode formData to a String in JavaScript and decode it in PHP one simple step after encoding?
By the way. I'm using TypeScript to generate my JavaScript. That is not supporting the FormData Object (transpiler throws error on new FormData()). So i can't use this.
I found the answer deep in the PHP docs. POST is not build to transport deep object. And filter_input method tries to get simple datatypes like string or int. this method does not parse internal so i have to send it as JSON string and decode it or i can't use filter_input in my case.
i took the first and send now strings.

serialize string for sending

I have such code
var serializeValues =$(this).find("input[type='hidden']).not('.table-element').serialize();
The Value:
martial_status=%D0%B6%D0%B5%D0%BD%D0%B0%D1%82+(%D0%B7%D0%B0%D0%BC%D1%83%D0%B6%D0%B5%D0%BC)&evidence_series=11-%D0%B2%D1%84%D1%8B&
This string I am sending as data in ajax. But I have table. I am changing my values from table and in the result I have:
work_status=working
How can I add this string for previous and convert in same format?
UPD
$.ajax({
type: 'POST',
data: serializeValues,
url: url,
complete: function()
{
alert('ok');
}
});
I want to send this ajax request, serializeValues is a data for this request, after that I use unserialize in php to get values.I am getting serializeValues automatical from form with the help of .serialize. And I am generating some string like work_status=working and I want add this string to serialize value, but I can't do it. data: serializeValues+mystring, is bad way, because in php unserialize doesn't work.
How can I add this string for previous and convert in same format?
Include & at beginning of string, use encodeURIComponent(), concatenate to serializeValues
serializeValues = serizlizeValues + encodeURIComponent("&work_status=working")

Using '&' in ajax form submit

I am submitting a form using .ajax().
The current script contains:
data: dataString,
dataString contains:
var list = $('.listsummary').val()
The class listsummary belongs to a textarea which users fill in,
or will be (partially) filled in dynamically through a different script.
The problem is that users nearly all of the time use the '&' sign, for example:
Potato & Patota blah blah blah
This screws up the dataString allowing to post everything written before the first '&' is found.
How can I achieve that the var list will be properly sent to the PHP handler in order to store the entire textarea content into the database WITH the use of '&'?
You can encode the string with encodeURIComponent()
var list = $('.listsummary').val();
var urlEncoded = encodeURIComponent(list);
You have 2 options. Either pack the data as an object:
data: { list: $('.listsummary').val() }
Or encode the URI components:
var dataString = "list=" + encodeURIComponent($('.listsummary').val());
Welcome to the world of injections. This is a simple problem, but there are multiple approaches that you can take:
If your data is simple unstructured text, you should set contentType to text/plain or application/octet-stream:
$.ajax({
....
data: "Hello & world",
contentType: "text/plain",
...
});
If your data is key values structured, then you should encode your data as application/x-www-form-urlencoded. This can be achieved in JQuery by passing a JavaScript key-value object to data:
$.ajax({
....
data: { text: "Hello & World", location: "Boston" },
...
});
If your data has more complex structure, you should encode your data in the most appropriate Content Type (e.g. JSON, XML, CSV) and set contentType to (e.g. "application/json", "application/xml", "text/csv")
$.ajax({
....
data: JSON.stringify(["Hello & world", {"Hello & World"}]),
contentType: "application/json",
...
});
--
On the PHP side, if you need to process anything other than application/x-www-form-urlencoded, you'll need to read the request body directly as a string. Which can be fine with this code:
$body = file_get_contents('php://input');
Or if you have PECL:
$body = http_get_request_body();
If you use a web framework, they probably also have ways to process custom content types. Check the documentation of your web framework.

Categories