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.
Related
Okay I think I am going mad because I have done this a million times before and now I can't make it work. I am doing an ajax post to a PHP script with some simple JSON and then returning the JSON from my PHP, however it is currently showing $_POST as an empty array.
Here is my js:
$.ajax({
type: "POST",
url: "/account/book-promo.php",
data: '{"firstName":"Peter" , "lastName":"Jones"}',
success: function(response) {
console.log(response);
}
});
And my PHP:
<?php
var_dump($_POST);
exit;
Firebug shows that my request is using POST as it is supposed to and my data is being sent as JSON yet I am getting a response of:
array(0) {
}
The only thing I can think is that there is some kind of server settings that are preventing this from working, however I cant think why there would be. Maybe I have missed a bracket or something, it is driving me mad!
Any and all suggestions welcome!
send it like if you want to send it as json.
data: { data : '{"firstName":"Peter" , "lastName":"Jones"}' },
and if you want to send it as POST just remove quotes '
data: {"firstName":"Peter" , "lastName":"Jones"},
You have to do this:
$.ajax({
type: "POST",
dataType: "json", // <---------------its required if response is json
url: "/account/book-promo.php",
data: {"firstName":"Peter" , "lastName":"Jones"}, //<---instead of string send the object this way
success: function(response) {
console.log(response);
}
});
You said in your post retuning the JSON from my PHP:
so you need to use dataType:"json" and the data you are sending to your php should be sent as object (which is usually to be pair of key and values separated by : like {key:value}) as of your code you are sending a string.
I would like to create an app that will send out a get request, then take the response and display it on the page,
this is part of my learning process, ultimately i would like to have the response be parsed and turned into
elements etc. but for now i am having trouble accessing the information within the response.
How can i alert() any of the results in the response?
the results of the script below ranged from undefined, to [object ojbect]
<script type="text/javascript">
var bbz;
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "MyDomain - its defined and on the web",
success: function(response) {
bbz = response;
alert(bbz.length);
alert(bbz);
alert(bbz[0]);
}
});
</script>
It looks to me like you are expecting a JSON response...
I am assuming this because of the way you are accessing properties of the response object -
bbz = response;
alert(bbz.length);
You'll want to set your dataType to "json".
If you set the dataType property to html, you should be able to simply return HTML.
You set dataType: "jsonp" which attempts to parse a jsonp object out of the data that is to be returned. However, what you really want is the markup that is in the file you are requesting data from. In order to do this, you must state the correct return type, so that the AJAX knows what data to give you, i.e. you tell the AJAX how to parse the data.
In my php file 'login_success.php', I have a the variable $_COOKIE["user"]
Would it be possible to return that variable within a jQuery Ajax statment such as this one. ive made a guess with Var UserName =:
function StartAjax(NameID){
$.ajax({
type: "POST",
url: "login_success.php",
cache: false,
data: "name=Peter&location=Sheffield",
success: function(html, status){
$("#"+NameID).append(html);
//$('#status').append(status);
var userName =
}
});
login_success.php:
echo $_COOKIE['user'];
Ajax asks for the page, returns the output/content (what is echoed). Please note: Javascript is client side. PHP is server side. So you can't directly access PHP variables, but as done above, PHP can "give" the client the info it needs. If you're sending a lot of data, you can json_encode it for the ajax request. (you can learn about JSON on your own)
Also note, Javascript can access cookies, but I'm assuming this is just a sample question.
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)
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.