Im trying to save this string:
~`##$%^&*()_+}{":?><,./;'[]=-|\
using a AJAX call in php. But in the database it saves as this:
~`##$%^????
this is my AJAX call
function saveComment(timesheetId,activityId,date,comment,employeeId) {
var r = $.ajax({
type: 'POST',
url: commentlink,
data: "timesheetId="+timesheetId+"&activityId="+activityId+"&date="+date+"&comment="+comment+"&employeeId="+employeeId,
async: false
}).responseText;
return r;
}
Edit: Fixed display of strings and code.
You need to in javascript call encodeURIComponent on the string with the weird characters before you send it to the server.
EDIT: Tomalak pointed out a better method.
If you want to put a variable 'text' in the data, you should run it through $.URLEncode(text) before doing so; as it is, the '&' character in the text introduces a new parameter.
jQuery supports an object as the data parameter in Ajax requests. This also does the URL encoding for you automatically:
$.ajax({
type: 'POST',
url: commentlink,
data: {
timesheetId: timesheetId,
activityId: activityId,
date: date,
comment: comment,
employeeId: employeeId
},
success: function (data) {
alert(data);
}
});
Also - you should never use synchronous Ajax requests. Always work with callback functions.
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 am trying to make a request to this file : http://traitdesign.com/work/tattva/get.php
this is the code I have so far:
function getRemote() {
return $.ajax({
type: "GET",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
}).responseText;
}
getRemote();
well the issue is response headers is empty it doesnt return any results. any help would be appreciated. thank you
Try with JSONP
function getRemote() {
return $.ajax({
type: "GET",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
dataType: "jsonp",
});
}
getRemote();
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
Problem is 'Same Origin Policy'. but you can escape from it. but some security issues will remain.
Please check this. http://enable-cors.org/server_php.html
header("Access-Control-Allow-Origin: *");
Include this line into your get.php file.
I think the best in your case would be to write simple ajax action on your server like:
print(file_get_contents('http://traitdesign.com/work/tattva/get.php');
And make ajax call to your new action. It will got through your server so additional server work will be done but you then don't need to care about security policy.
Use JSONP with callback. Also return the value once the call is done.
function getRemote() {
var jqXHR = $.ajax({
type: "GET",
dataType: "jsonp",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
crossDomain: true
});
return jqXHR.responseText;
}
getRemote();
i am sending data through ajax call to the php code my ajax code is this
var values = JSON.stringify({ dstring: dataString, ukey:ukey });
var page_path = server_url+"save_data.php";
$.ajax({
type: "POST",
url: page_path,
cache: false,
data: values,
dataType: "json",
success: function(msg){
},
error:function(xhr, status, error) {
}
});
and in the ajax it send data like this
{"dstring":{"q2":"11","q3":"22","q4":"33","q5":"44","q6":"55"},"ukey":"1"}
and in the php when i try to get it through REQUEST it dont show me data , i am bit confuse on how to handle this data in php
Don't stringify data on your ajax call. You should then be able to $_POST['dstring']on the PHP script. Also, you should add in some debug code at least into that error handler to know what's up. Last but not least, inspect the network calls.
You have to get file_get_contents("php://input") and run that through json_decode.
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)
I'm doing an AJAX call using jQuery's JSON feature.
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
pop_word_list(json, paging_value);
}
});
}
As you can see, I'm sending the response to another JavaScript function, but what I'd like to do is send the response to PHP. Is this possible, say to directly convert the response into a PHP array (not using JavaScript) and then use PHP to handle the array, etc?
Thanks in advance.
You could perform another Ajax call to the php script in the success function, passing along the JSON data as a POST param.
do this?
js (ajax) -> php (array conver to ajax) -> js (ajax) -> php ?
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
json["paging_value"] = paging_value;
$.post("x.php", json);
}
});
}
The whole idea doesn't stick together at all... but:
If there is a reason to do that - then You want to do the $.post('phpfile.php',json,function(){},'text or whatever type You want in return');
and the whole json object goes to PHP's $_POST[] as suggested above, but I can see NO case where it should be done that way.
If You get that json from some code You can't change and want to use data in php do:
use cURL to get the data from another thing
use json_decode($data,true) to get assoc table of the whole thing
If You don't know what You're doing :)
just pass the object to another function without useless sending stuff back and forth. You might want to do empty AJAX call to trigger the php file, nothing more.