A quick question
Does php function json_encode or js JSON.parse function drops '+' character by default? I definitely get a '+' lost somewhere and at cannot figure out where. This is quite urgent as it's actually an xml feed from realex, which authorizes (or in this case doesn't authorize) payments on one of our live sites. To make things more complex, I cannot use dev environment at the moment and I cannot play in printing out values on the screen on the live site. So I'm trying to make a guessed-fix for the start
Ok, here's some exmaple
I get a value from Realex
$RESPONSE_THREEDSECURE_CAVV = 'jFvMUENpUEzLARAQBtmeh+Q5o/U=';
$parametersToPass['cavv'] = $RESPONSE_THREEDSECURE_CAVV;
There are more values in parametersToPass array, but this is the one that's causing troubles.
I encode it in php
$encoded = json_encode($parametersToPass);
die($encoded);
This is being returned in jquery ajax call success as 'data'
success: function(data) {
$.ajax({
type: "POST",
url: 'action/payment-process_auth.php',
data: "data="+data
});
}
I retieve it in payment-process-auth
$decoded = json_decode($_POST['data']);
$parametersToPass['cavv'] = $decoded->cavv;
At this point cavv value is jFvMUENpUEzLARAQBtmeh Q5o/U= instead of jFvMUENpUEzLARAQBtmeh+Q5o/U= (space instead of a +)
How can I sort this out?
No, json_decode and JSON.parse both respect + characters.
In a URL, though, a + is turned into a space if not properly urlencoded to %2B... so if you're json_decodeing a $_GET parameter that may be what's going on.
Try posting your data with AJAX in a proper JSON format?
success: function(data) {
$.ajax({
type: "POST",
url: 'action/payment-process_auth.php',
data: {"data": data}
});
}
Related
When I send serialised data to a PHP file using ajax, it is sometimes URL Encoded depending on how i do it.
Originally i had the following code which worked fine:
$.ajax({
type: 'POST',
url: 'ajax-process.php',
data: $("#sitestructure-form").serialize(),
success: function(d){$("#structureupdate").html(d);}
});
The data was sent to my PHP file and i could echo it and it looked like this.
[{"id":20,"children":[{"id":21}]},{"id":19},{"id":18,"children":[{"id":14}]},{"id":16},{"id":13,"children":[{"id":11}]},{"id":17},{"id":15},{"id":12}]
I wanted to send more than one piece of data, I called the serialized data 'order' and added 'process' to it so i updated my code to the following:
$.ajax({
type: 'POST',
url: 'ajax-process.php',
data: {
order: $("#sitestructure-form").serialize(),
process: "sitemap-reordernavigation"
},
success: function(d){$("#structureupdate").html(d);}
});
However when I retrieve the serialised data sent in 'order' the output looks like this:
data=%5B%7B%22id%22%3A20%2C%22children%22%3A%5B%7B%22id%22%3A21%7D%5D%7D%2C%7B%22id%22%3A19%7D%2C%7B%22id%22%3A18%2C%22children%22%3A%5B%7B%22id%22%3A14%7D%5D%7D%2C%7B%22id%22%3A16%7D%2C%7B%22id%22%3A13%2C%22children%22%3A%5B%7B%22id%22%3A11%7D%5D%7D%2C%7B%22id%22%3A17%7D%2C%7B%22id%22%3A15%7D%2C%7B%22id%22%3A12%7D%5D
The only way i can think of to fix this problem is to use php to urldecode it and then use str_replace to remove the 'data=' bit at the front, like so.
$data = str_replace("data=","",urldecode($_POST['order']));
How can I get this to work with AJAX though so i dont have to urldecode it?
Ive tried using a variable and setting the processData to false however that didn't seem to work.
var order = $("#sitestructure-form").serialize();
$.ajax({
type: 'POST',
url: 'ajax-process.php',
processData: false,
data: {
order: order,
process: "sitemap-reordernavigation"
},
success: function(d){$("#structureupdate").html(d);}
});
My knowledge of AJAX/Jquery is rather limited so any help would be greatly appreciated.
That's because you are feeding a serialized text string to the data attribute the first time around and jQuery does not convert it to a serialized string. The second you are assigning an object to the data attribute with the "order" attribute having the serialized text string, so jQuery basically double encodes it. For it to act as you'd like you would have to convert the form to an object and assign your "order" attribute to that object. See this post: Convert form data to JavaScript object with jQuery
// taking the example from the above link, you do this instead
order = $("#sitestructure-form"). serializeObject();
Fixed by doing the following:
$.ajax({
type: 'POST',
url: 'ajax-process.php?',
data: $("#sitestructure-form").serialize() + "&action=sitemap-reordernavigation",
success: function(d){$("#structureupdate").html(d);}
});
I have a registration form with a text field. I am trying to pass the string that is inputted on that field to a php file to validate the string dynamically. What would be the best(performance-wise) way to do it.
using
data: { cont: str , inputType : vtype}
or a query string
url: 'validate.php?q='+str+'t='+vtype;
this is my current script:
function validate(str,vtype) {
$.ajax({
type: 'GET',
url: 'validate.php?q='+str+'t='+vtype,
timeout: 1000,
success: function (data) {
$("#validationIndicator").html(data);
},
error: function (XMLHttpRequest, errorThrown) {
$("#validationIndicator").html('');
}
});
}
First of all, jQuery is meant to make JavaScript development easier; why go through string concatenation with more elegant alternatives?
The other thing jQuery does is to make sure your data is properly escaped; to give an example, the equivalent of using data: is actually this:
url: 'validate.php?q=' + encodeURIComponent(str) + 't=' + encodeURIComponent(vtype);
Otherwise, the values of str or vtype may mess up the query string.
Second, the time spent constructing the request vs the round trip to the server is negligible, so you should pick the option that's simpler and less error prone.
Conclusion
Go with this:
data: { cont: str , inputType : vtype}
Interesting question! When you pass data key-value pair within $.ajax({}), it converts it into a query string, and appends it to URL. This is similar to you doing following:
url: 'validate.php?q=' + str + '&t=' + vtype;
In other words, for GET request, it is better to build and use URL (with query string) explicitly, rather than letting jQuery do the conversion for you.
Also, there is a processData boolean that you can pass within your Ajax request. This boolean, if provided FALSE, won't convert data to query string automatically.
Source: https://api.jquery.com/jQuery.ajax/
In php, I have an array like this :
$arr['a'] = "some big data so may contain some chars that bring us headache"
$arr['b'] = "some big data same as above"
$data = json_encode($arr)
echo $data
My javascript code containing a jquery ajax call, $.ajax . It calls the file containing the above php code so, on success, the json_encoded(by php) is returned to my javascript variable . In my javascript file, I am doing like this :
jsdata = JSON.parse(data); //Getting error here
$.ajax({
type: "post",
data: jsdata,
url: "url",
crossDomain: true,
dataType: 'jsonp'
}).done(function(d) {
print("success");
});
From the above code, in the line jsdata = JSON.parse(data), I am getting errors something like
Error : UNEXPECTED TOKEN <
As the data contains lot of different content, its normal to get those errors . They need to be escaped properly . Can anyone tell me how to do that correctly . Whatever the data may be , I shouldnot get error regarding the data .
Thanks
Well, a couple of things you should probably know jsdata = JSON.parse(data); tries to parse whatever json string you assigned to data, and return it as a JS object. I think you want to do the opposite: jsdata = JSON.stringify(data);
Besides, since you are using jQuery, you could just leave that line out: jQuery will convert the data to the appropriate format before sending the request anyway, no need to bother with parsing or stringify-ing it yourself.
Yeah you forgot the ; at the end of two lines, so PHP is outputing an error, which is no JSON-compliant.
Always do this :
Catch errors and output them in a way that is understable by your application (a 5xx status can be enough)
Next time you have this, use Chrome Developper tool or Firebug to see what your app really returns
Also, you're outputing json, not jsonp which is different and what your app expects
$.ajax({
type: "post",
data: jsdata,
url: "url",
crossDomain: true,
dataType: 'jsonp',
success: function(d) {
print("success");
}
})
try it this way
This is much more simple than it might seem.
Call urlencode($arr['a']) and urlencode($arr['b']) (for each data value in $arr) before encoding the JSON and echoing $data to the JavaScript. This will URL-Encode the data in the array so that it will cause you no problems.
When you are done parsing the JSON, you will have to call the JavaScript function unescape(string) on each of the large data values. This will return them to the way they originally were. It's a sort of superhero-team-up of PHP and JavaScript!
I have a standard javascript ajax call where I'm setting the data: to json data.
$.ajax({
type: "POST",
url: BaseUrl + "User/Login",
//url: BaseUrl + "User/Limit/1/2",
data: '{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
},
});
I was trying to get the data in php $_POST["data"] this doesn't work.
However, data: 'test={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}' works.
I was wondering is it possibly my framework or anything like that preventing $_POST["data"] from working or is this just not possible at all? Or is there something else I could use to get that data?
EDIT:
So the framework YII and the extension Restfullyii has a method to get the data it is using one line
return json_decode(file_get_contents("php://input"), true);
Which is getting all the data without the need for data= or {data: However it seems to be returning an array so Im accessing my properties like $data["userName"] where a true json object should be $data->["userName"]. Correct me if I'm wrong on any of this am I getting array in this case because I'm really sending a json string? versus a json object?
EDIT x2:
So php is making it an assoc array because it is sending true to the json_decode..
I think problem with your code is in the line where you set data: '{....}'.
It should be in json format in order to be passed properly (though it also could be in string format but you'll need to parse it on the server side)
The code below should be working right:
$.ajax({
type: "post",
url: BaseUrl + "User/Login",
data: {"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"},
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
}
});
On the server side try: $_POST['apiKey'] $_POST['appIDGiven'] and so on.
data option must be an object or serialized(e.g. "name1=value1&name2=value2") string.So you need to pass like this:
data: /*object*/{data:'{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}'},
// ^-----this is added for $_POST["data"]
or like:
data: /*serialized string*/'data={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
// ^-----this is added for $_POST["data"]
First, the data sent must be a JSON object and not a string. Remove the quotes.
Also, in your server-side, you'll better decode the input $_POST['data'] with json_decode() (see documentaion)
My html file:
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
url: "search.php",
data: "id=1",
datatype: "json",
success: function(msg){
$('.result1').html(msg["name"]);
}
});
})
</script>
<span class="result1"></span>
My php file:
<?
$a["name"] = 'john';
echo json_encode($a);
?>
Why the name John doesn't appear in class result1? Why? Please help me, I am going insane.
edit: Is it possible to make bounty right now?
The dataType parameter has a capital T. It works if you correct this.
Currently it is (by default) trying to guess the response format based on the mime-type, so probably defaulting to html - debugging in firebug you can see that the msg argument of the success callback is a string containing the JSON.
Not to distract you from solving this problem. But you may want to look into the .getJSON() function http://api.jquery.com/jQuery.getJSON/. It's a little cleaner if you're just getting some data.
Also, take a look at the JSON format, I think data: "id=1" should be data: "{id:1}"
And on the response side, keep in mind it's expecting multiple records so try: msg[0].name;, check out the each() function to process multiple records.
I think you should use:
$('.result1').html(msg.name);