I need pass jQuery variable to PHP variable, so I made simple code to test and it doesn't work.
It's only a testing files. Finally, I have to do something more advanced but i can't make it works!
I have 3 files
In character.html I have:
SAVE
and in character.js (it's external javascript for character.html)
$(document).ready(function() {
$('.saved').click( function () {
var avatarID = 123;
$ajax({
url :'character-save.php',
data:{"avatarID":avatarID},
type: 'post',
dataType: 'json',
});
});
});
in character-save.php i try this:
<?php
header('Content-type: application/json');
$result = $_POST['avatarID'];
$result = htmlentities($result, UTF-8);
echo json_encode($result);
exit();
?>
And it doesn't print 123
In your php file, you have a mistaks with UTF-8, it should be included with parentheses.
<?php
header('Content-type: application/json');
$result = $_POST['avatarID'];
$result = htmlentities($result, 'UTF-8'); // It should be 'UTF-8'
echo json_encode($result);
exit();
?>
Your syntax is wrong its not $ajax its $.ajax don't forget the . dot.
Also you need some way of checking response so either update your html by adding ajax callback and necessary jquery, use alert or log reponse to console. Something like this should give you a good indication.
$.ajax({
url :'character-save.php',
data:{"avatarID":avatarID},
type: 'post',
dataType: 'json'
}).done(function(response) {
alert(response.data);
});
In your PHP change $result = htmlentities($result, UTF-8); to $result = htmlentities($result); also validate your json by putting result in an array then encode that array as json and echo it like this:
<?php
header('Content-type: application/json');
$result = $_POST['avatarID'];
$result = htmlentities($result);
$return["data"] = $result;
echo json_encode($return);
exit();
?>
In your javascript you have to add e.preventDefault(); to prevent the page redirecting to character-save.php
And inside the click function add e
see the updated javascript section below
$(document).ready(function() {
$('.saved').click( function (e) {
e.preventDefault();
var avatarID = 123;
$.ajax({
url :'character-save.php',
data:{"avatarID":avatarID},
type: 'post',
dataType: 'json',
success: function(msg){
alert(msg);
}
});
});
});
Try this,
$(document).ready(function() {
$('.saved').click( function () {
var avatarID = 123;
$ajax({
type:"POST",
url: 'character-save.php&avatarID='+avatarID ,
success:function(response){
alert(response);
});
});
});
In character-save.php try this:
<?php echo $_GET['avatarID'];
?>
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.
I am new in codeigniter. I am writing a code. AJAX response is not returning.
Here is my controller:
public function getValue()
{
$this->load->helper('url');
$data = array(
'username' => $this->input->post('username'),
'email'=>$this->input->post('email'),
'address'=>$this->input->post('address')
);
echo json_encode($data);
die;
}
and it is view code:
$( document ).ready(function() {
$('#btn_submit').on("click", function(event){
event.preventDefault();
var username = $('#username').val();
var email = $('#email').val();
var address = $('#address').val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/MyApp/getValue",
dataType: 'json',
async:true,
crossDomain:true,
data: {username: username, email: email, address: address},
success: function ( data) {
console.log(data);
},
error: function ( data ) {
console.log('error');
}
});
});
});
I am new with codeigniter, so I don't know how to return response and work with AJAX. I have coded with the help of web but still getting errors. Please guide me how to fix this. Thanks
Simple answer remove die; from the getValue() function.
Codeigniter does not actually output anything until after the controller finishes execution. The call to die; short circuits the normal operation of the framework and so nothing gets output. In other words, echo json_encode($data); never actually happens.
Please try after setting content-type for the response like below.
header('Content-Type: application/json');
echo json_encode($data);
die;
Ajax response expects json data since your code set dataType: 'json'
array_push returns only last value that has been currently pushed into the array in php. Please help. Here is the link where I am working http://dev.optimizebusinessgrowth.com/gopaperboy/members/
Its an jquery ajax. I call ajax with
jQuery(function(){
jQuery('.icon-heart').click(function(){
var user_IDs = jQuery(this).attr('id');
var current_IDs = <?php echo $cui ?>;
jQuery.ajax({
url: '<?php bloginfo('url') ?>/',
type: 'POST',
data: 'ajaxreturn=101&id='+user_IDs+'&myid='+current_IDs,
success: function(result){
jQuery('.testres').html(result);
}
});//ajax ends here
});
});
and here is the code in function.php which gives response
function my_ajaxreturn_101() {
$current_fav = array();
if($_POST['ajaxreturn']==101) {
$userID = $_POST['id'];
$loggedID = $_POST['myid'];
array_push($current_fav,$userID);
print_r($current_fav);
exit;
}
}
Try to use append() instead of html(), so you can do:
jQuery('.testres').append(result);
instead of:
jQuery('.testres').html(result);
Just starting to learn about ajax although I am running into trouble trying to return a success message in an array.
<script type="text/javascript">
$(function () {
$('#delete').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
}).done(function (response) {
if (response.success) {
alert('Saved!');
} else {
alert('Some error occurred.');
}
});
});
});
</script>
<?php
$array = array();
$array['success'] = TRUE;
echo $array;
?>
response.success should refer to $array['success'] correct?
You are trying to echo your array, which will just spit out "Array".
Instead you need to encode your array as JSON and echo that out.
Change this:
echo $array;
To this:
echo json_encode($array);
Also you probably need to add your dataType in your ajax params so jQuery auto-parses the response:
dataType : 'json' // stick this after "data: $form.serialize()" for example
Also, here's a good post to read on how to properly handle success/errors with your ajax calls (thanks #Shawn):
Jquery checking success of ajax post
How can I load my php on my domain using my javascript that was loaded dynamically.
my sample code
sample.html(Client-side)
<div onClick = "getThis()"></div>
my.js(Client-side)
function getThis(){
var url = "http://www.sampledomain.com/test.js"
var script = document.createElement('script');
script.src = url;
document.head.appendChild(script);
}
test.js(Server-side)
$.get("index.php", function(data) {
alert(data);
});
index.php(Server-side)
<?php
$_SESSION['user'] = "rob098";
?>
<script>
var data = '<?php echo json_encode($_SESSION['user']) ?>';
</script>
but it doesn't alert any.
Use ajax and json:
sample.html
<div onClick = "getThis()"></div>
my.js (inside sample.html)
function getThis() {
$.ajax({
url: '/test.php',
dataType: 'json',
success: function(data){
alert(data.user); //should alert rob098
},
});
}
test.php
header('Content-type: application/json');
echo json_encode(array("user" => "rob098"));
you have to append your js file to this
$(document).ready(function(){
$.get("index.php", function(data) {
alert(data);
});
});
so when script file loaded it will execute code inside jQuery ready function
I think you are using jquery $.get() the wrong way. Well I've never seen used that way at least, so you need to change your index.php to this:
<?php
$_SESSION['user'] = "rob098";
echo json_encode($_SESSION['user']);
header('Content-type: application/json');
?>
Let me know if I helped.