I'm new to PHP and jQuery, so I have doubt when declaring PHP data in JSON format with AJAX.
I don't know how to receive the JSON data again and place it inside a PHP variable.
Here's my current attempt:
<?php
$id = $_GET['id'];
?>
function load_topic()
{
$.ajax({
url:"fetch_topic.php",
method:"POST",
data:{
tpid :"<?php print $id; ?>"
},
dataType:"JSON",
success:function(data)
{
$('#display_topic').html(data);
}
})
}
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data:{
"tpid" :"<?php print $id; ?>"
},
dataType:"JSON",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
I assume you want to retrieve the tpid which you pass with ajax in your files fetch_comment.php and fetch_topic.php.
To do this, you simply use
$tpid = $_POST['tpid'];
This retrieves the 'tpid' which was send via the ajax post request and stores it in the variable $tpid.
Source: http://php.net/manual/en/reserved.variables.post.php
check by inspecting in browser under network that it is sending data or not?
if it is sending the data using method post
then in php file where you are receiving data use
print_r($_POST);
if it print something in and it is showing in json try print_r(json_decode($_POST));
There's a few issues with your post, here:
1/ It's not clear what JSON data you are returning from fetch_topic.php and fetch_comment.php. Your code is fine, but without knowing what JSON data you are returning from those pages, it's difficult to help.
2/ The function that handles the response is a bit odd in that it will print the raw JSON data to those elements. If you want to process the JSON a bit better, i suggest something like this:
$.ajax({
url:"fetch_comment.php",
method:"POST",
data:{
"tpid" :"<?php print $id; ?>"
},
dataType:"JSON",
success:function( response )
{
if ( response.status == 'success' ) {
$('#display_comment').html( response.html );
} else {
// handle your error here.
}
}
});
and your fetch page responds with:
{"status":"success","html":"<p>Here is an HTML response!<\/p>"}
or not use JSON and just return html from your fetch pages:
$.ajax({
url:"fetch_comment.php",
method:"POST",
data:{
"tpid" :"<?php print $id; ?>"
},
dataType:"HTML",
success:function( response )
{
$('#display_comment').html( html );
}
});
A little more clarity in your request would be super helpful.
Related
I need to pass a json object from JS to PHP, and it will pass, but the result is an empty array.
Ajax request in 'adopt.php':
var info = JSON.stringify(filteredArray);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {'info': info},
success: function(data){
console.log(data);
}
});
ajax.php code:
if(isset($_POST['info'])){
$_SESSION['array'] = $_POST['info'];
}
back in adopt.php, later:
if(isset($_SESSION['array'])){
$arr = $_SESSION['array'];
echo "console.log('information: ' + $arr);";
}
in both of the console.logs, it returns an empty object. Does anybody know what could be causing this? (i've tried just passing the json without stringifying it, but it throws a jquery error whenever i do this.)
Try below code i think you miss return ajax response
adopt.php
<script>
var info = JSON.stringify(filteredArray);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {info: info},
success: function(data){
console.log(data);
}
});
</script>
ajax.php
if (isset($_POST['info'])) {
$_SESSION['array'] = $_POST['info'];
echo json_encode(["result" => "success"]);
}
To get the response data from PHP, you need to echo your data to return it to the browser.
In your ajax.php:
if (isset($_POST['info'])) {
$_SESSION['array'] = $_POST['info'];
echo json_encode(['result' => $_SESSION['array']]);
}
Your ajax.php is not returning any data.To get data at the time of success you need to echo the data you want to display on success of your ajax.
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'<?php echo site_url($this->config->item('admin_folder').'/catalog/get_all_option');?>',
type:'POST',
data:{category_id:1},
dataType: 'json',
success:function(data){
$('#attribute_form').html('<?php add_attribute_form("'+data+'");?>');
}
});
}
});
on callback function success return the data and pass it to add_attribute_form(data) php function but nothing response.
what is the correct way to pass js object to php function
What you will need to do here is, use Ajax to send data to a separate php page passing it some information, then, based on that information, the php page should return data to the Ajax callback function which will add the returned data to the original page.
Here's a simple example (and a working demo here):
In index.html do this:
<script>
$(document).ready(function(){
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'somepage.php',
type:'POST',
data:{category_id:1},
dataType: 'json', // this setting means you expect the server to return json formatted data
// this is important because if the data you get back is not valid json,
// the success callback below will not be called,
// the error callback will be called instead
success:function(response){
$('#attribute_form').html(response.html);
// if not using json, this would just be $('#attribute_form').html(response);
},
error:function(xhr, status, error){
// handel error
}
});
}
});
});
</script>
<input type="checkbox" class="select_category"> Check this box
<div id="attribute_form"></div>
Then in somepage.php do the following:
<?php
$category_id = isset($_POST['category_id']) ? $_POST['category_id'] : null;
if($category_id == '1'){
echo json_encode(array('html'=>'<h1>This text came from the php page</h1>'));
exit;
// if you are not using dataType:json in your ajax, you can just do:
// echo '<h1>This text came from the php page</h1>';
// exit;
}
?>
The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}
i have a jquery ajax post that for some reasons doesn't work:
<script>
var callback = function(data) {
if (data['order_id']) {
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { myid: 123456 },
success: function(data) {
alert("Transaction Completed!");
}
});
}}
</script>
<?php if ($_POST['myid']) { echo $_POST['myid']; } ?>
the 'callback' functions works fine(i test it), just that it stops at the ajax post
and i cant see my echo's
any ideas on what i am doing wrong?
thanks
edit:
i edited the script a bit at the point where the ajax is posting successfully but i cant get the php to echo anything
If the AJAX - Call is succeeding now, you can't just echo anything with PHP. The data is sent to the client, but PHP is interpreted at the server. You're not sending an HTTP - Request anymore (which is pretty much the point of an AJAX-Call), so PHP is not going to do anything at this point.
You have to add your new content to the DOM with JavaScript. Try this and see if you get the message shown on your page. I append it to the body, because I don't know how your Markup and your returned data looks like:
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { myid: 123456 },
success: function(data) {
alert("Transaction Completed!");
$('body').prepend('<p>Successful AJAX - Call</p>');
}
});
Then you can take a look at your data-variable with console.log(data), access the returned data and modify the DOM via JavaScript.
ok, for a start.
writeback("Transaction Completed!";
fix it to:
writeback("Transaction Completed!");
you have a trailing comma after 123456
data: { myid: 123456, },
you're missing a closing } to your callback function
Sorry if this is basic, but I have been dealing with figuring this out all day and have gotten to where I can do everything I need with Jquery and cakephp (not sure if cakephp matters in this or if its same as any PHP), I want to return a variable from a cakephp function to jquery, I had read about how to do it, like here:
the cakephp:
$test[ 'mytest'] = $test;
echo json_encode($test);
and the jquery:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
}
});
I just can't figure out how to get one or more variables back into usable form within jquery, I just want the variable so I can do whatever else with it, I've been looking at what I can find through searching but its not making it fully clear to me.. thanks for any advice.
The JSON variables are in the data variable. In your case, it'll look like this:
var data = {
myTest: "Whatever you wrote here"
};
... so you can read it from data.myTest.
(Not sure whether it's relevant but you can remove the http://localhost/ part from the URL;
AJAX does not allow cross-domain requests anyway.)
Your variables are in data.
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
var values = eval( data ); //if you 100 % trust to your sources.
}
});
Basically data variable contain the json string. To parse it and convert it again to JSON, you have to do following:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
json = $.parseJSON(data);
alert(json.mytest);
}
I haven't test it but it should work this way.
Note that when you specify dataType "json" or use $.getJSON (instead of $.ajax) jQuery will apply $.parseJSON automatically.
So in the "success" callback you do not need to parse the response using parseJSON again:
success: function(data) {
alert(data.mytest);
}
In case of returning a JSON variable back to view files you can use javascript helper:
in your utilities controller:
function ajax_component_call_handler() {
$this->layout = 'ajax';
if( $this->RequestHandler->isAjax()) {
$foobar = array('Foo' => array('Bar'));
$this->set('data', $foobar);
}
}
and in your view/utilities/ajax_component_call_handler.ctp you can use:
if( isset($data) ) {
$javascript->object($data); //converts PHP var to JSON
}
So, when you reach the stage in your function:
success: function(data) {
console.log(data); //it will be a JSON object.
}
In this case you will variable type handling separated from controllers and view logic (what if you'll need something else then JSON)...