In my external JavaScript file, I have the following jQuery code:
$(function(){
$('#follow').on('click',function(){
$.ajax({
type: 'POST',
url : 'functions/follow.php',
data: {follower : session_id,
user : p_id,
success: function(result) {
if(result == 'followed'){
$('#follow').attr('id','unfollow').text('-Unfollow');
}
}
});
});
});
On my normal page, I have this:
var session_id = '<?php echo $_SESSION['id']; ?>',
p_id = '<?php echo $p_id; ?>';
but this is not passing the variables into the jQuery function. I have these two variables being set before the JavaScript file is being called, also.
EDIT: I have tested this with the function on the same page as where the button is, and I passed in the PHP values with an echo, and it worked then.
You can create a namespace in the jquery object allowing access to it even inside events. Like so:
$.mynamespace = {
session_id: '<?php echo $_SESSION['id']; ?>',
p_id: '<?php echo $p_id; ?>'
};
Then reference those namespace vars in your code like so:
$(function(){
$('#follow').on('click',function(){
$.ajax({
type: 'POST',
url : 'functions/follow.php',
data: {follower : $.mynamespace.session_id,
user : $.mynamespace.p_id,
success: function(result) {
if(result == 'followed'){
$('#follow').attr('id','unfollow').text('-Unfollow');
}
}
});
});
});
This will also make them available for any other jQuery events/callbacks etc
(NB: Make sure your variables are being set before you try to use them, i.e. higher in the script)
Related
My AJAX call previously returned an array of data as JSON using "echo jason_encode(array)" in my PHP code and I then looped through the result in my script and built the HTML using the returned data before displaying.
Now I changed the code to build the HTML in my PHP code and I want to return the HTML string to my script and display the HTML but I have no idea how to get it working and I have looked at over a dozen examples on this site and others but no luck.
PHP
$html = '<tr><td><div class="dummy">This is some text.</div></td></tr>';
$arr[] = array('html' => $html);
echo json_encode($arr);
Script
<script type="text/javascript">
$('.mashed_row a').click(function () {
var link_id = $(this).attr('link_id');
$.ajax({
type: 'POST',
url: 'explode',
data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', link_id},
dataType: 'json',
success : function(data) {
if(data)
{
var txt = data['html'];
$("#xarticletab").html("");
$("#xarticletab").append(txt).removeClass("hidden");
$("#comments").removeClass("hidden");
}
}
});
return false;
});
</script>
First of all, I think there is an error on your JS code: link_id alone.
on JS, you should define key: value. So, maybe 'link_id': link_id ?
Correct typo: {key1: 'value1', 'key2': 'value2'}
After, use console editor of your browser to know if there is any Javascript error.
Alternatively, you can play with javascript functions: console.log(data); or event alert(data)
I'm currently trying to use the return value of a PHP script to do a refresh action with jQuery. My PHP script is doing what it should do, return the value "reload" when a certain requirement is met; jQuery then however displays "reload" briefly and doesn't act on the refresh action that I've required it to do.
$.ajax({
url: '/bidstatus.php',
data: {
sale_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
dataType: 'json',
type: 'get',
success: function(output) {
if (output == "reload") {
location.reload();
}
}
});
The PHP that returns the value, when a requirement has been met, looks like this:
echo json_encode("reload");
Also, to make it even more confusing, it sometimes does what it has to do, but it's not consistent at all.
So, am I missing something?
Since I saw this was still open and I managed to fix it myself, I'll post the code so it can/may help others with similar problems.
This was the code that fixed it.
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function()
{
$.post('/bidstatus.php',
{
auction_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
function(data)
{
if(data == "reload"){
location.reload();
}
else{
$('#shop-balance').html(data);
}
}
);
}, 1000);
});
Well, try this:
function do_ajax(callback)
{
$.ajax({
url: '/bidstatus.php',
data: {
sale_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
dataType: 'json',
type: 'get',
success: function(data){
callback(data);
},
});
}
Just check it again and if you use any global scope variable then pass it through function's parameters.
And call it like this::
do_ajax(function(data) {
if (data == "reload") {
location.reload();
}
}
);
What I have done is to set a callback for your .success state, rather than direct code execution. Since Javascript executes the code asynchronously, it just passes the .success before the AJAX is finished, and thus, the data will not be "output" and it is "null" probably. You shoul add a callback there and execute it through a callback to allow the Javascript Interpreter to accomplish the task.
I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});
I have 2 selects on my HTML, the options are loaded via my database and the user can switch the options between the boxes, like so:
<select id="column1" multiple size="10" name="FromLB" style="width:150px">
<?php foreach ($result->result() as $row) { ?>
<option value="<?php echo $row->id ?>"><?php echo $row->title ?></option>
<?php } ?>
</select>
So far so good, the final plan is for the the user to click Submit and to have access to the data on these two selects in PHP (via an array).
After digging around for a bit, it seems like JSON is the way to go.
I import json.js to my project and get to work:
function sort_cols(){
var i=0;
var p=0;
var column1 = new Array();
var column2 = new Array();
$("#column1 option").each(function()
{
column1[i]=$(this).val();
i=i+1;
});
$("#column2 option").each(function()
{
column2[p]=$(this).val();
p=p+1;
});
JSON = JSON.stringify(column1);
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: JSON,
success: function(){
alert("Success!")
}
});
}
So far I'm only passing one array (for the first select column), but I'm getting an error:
Uncaught TypeError: Object ["15","14","1"] has no method 'stringify'
I've been following this answer:
How exactly do you use json_decode to pass a javascript array to php?
I'm wondering what am I doing wrong here, and how can I pass my second array (column2) as well?
In this line
JSON = JSON.stringify(column1);
you redefine the native JSON object. Use another name for your variable and you should be fine.
And as for submitting both arrays, just use an encapsulating object:
data2send = JSON.stringify( { 'column1': column1, 'column2': column2 } );
Besides instead of using an incrementing index to insert your data into the arrays, just use the native push() method.
There's some strange behaviour happening here, most likely caused by the fact your JSON variable is overwriting the browser's native JSON object (or the one provided by json.js in older browsers).
You can actually pass an object directly to $.ajax, so the following will work:
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: column1,
success: function(){
alert("Success!")
}
});
If you want to pass both columns as separate parameters, change it to:
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: {
first_column: column1,
second_column: column2
},
success: function(){
alert("Success!")
}
});
They will now be available in your PHP script as $_POST['first_column'] and $_POST['second_column'].
This way, you leave the heavy lifting of converting your objects to JSON to jQuery, so you don't need to include the json.js library at all.
Your full code, rewritten:
function sort_cols(){
var column1 = [],
column2 = [];
$("#column1 option").each(function() {
column1.push($(this).val());
});
$("#column2 option").each(function() {
column2.push($(this).val());
});
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: {
first_column: column1,
second_column: column2
},
success: function(){
alert("Success!")
}
});
}
Make jQuery do the heavy lifting:
function sort_cols(){
var col1 = [], col2 = [];
$("#column1 option").each(function() {
col1.push($(this).val());
});
$("#column2 option").each(function() {
col2.push($(this).val());
});
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
contentType: "application/json",
data: JSON.stringify({
column1: col1,
column2: col2
}),
success: function(){
alert("Success!")
}
});
}
I am trying to make a like button on a page and cant seem to get it to work right. Basically there are three function that use ajax to send the data to a php page that updates the database. Ive checked the db and all three update correctly. If the user doesnt originally like and clicks, it correctly shows the unlike button but then, if you click unlike it doesnt switch back (although it does update the database).
Is this the correct way to set this up? Im pretty new to ajax and am not sure if this is the right approach. THanks in advance
Steve
public function likesScript($p){?>
<script>
//display list of people who like this
function getLikes(){
$.ajax({
type: "POST",
url: "likelist.php",
data: { p: "<?php echo $_GET['p']?>"}
}).success(function(res) {
//check to see if current user likes this
if($('li#<?PHP echo $_SESSION['userId']; ?>').length){
$(".Like").addClass('hidden');
$(".UnLike").removeClass('hidden');
}
else{
$(".UnLike").addClass('hidden');
$(".Like").removeClass('hidden');
}
$("#likedBy").append(res);
console.log(res);
});
}
function removeLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "0" }
})
getLikes();
return false;
}
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" }
})
getLikes();
return false;
}
$(document).ready(function() { getLikes();
$(".UnLike").live('click',removeLike);
$(".Like").live('click',addLike);
});
</script>
likelist.php:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/view.class.php';
$view = new view();
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$p = $_POST['p'];
$view->printLikes($profile->getLikes($p));
}
likedata.php:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$liker = $_POST['arg1'];
$likee = $_POST['arg2'];
$likeYesNo = $_POST['arg3'];
$profile->insertLikes($liker, $likee, $likeYesNo);
}
?>
AJAX is ayshcronous so the getLikes functions will fire before the AJAX is completed in both addLike and removeLike. You definitely need to put getLikes into the success callback of $.ajax so it doesn't retrieve data that may not have been updated
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" },
success: getLikes
})
}
Ok... this is what I have learned from using ajax repeat calls...
IE hates them and sometimes they just don't work the way they should.
Try this
function addLike() {
var randnum = Math.floor(Math.random()*1001); //Add This Here on all Ajax Calls
$.ajax({
type: "POST",
url: "likedata.php",
cache: false, //Add This Here - Assists in helping Browsers not to cache the Ajax call
data: yourdata + '&random=' + randnum, // Add this to the end of your data you are passing along *'&random=' + randnum,*
success: function() {
getLikes();
}
})
}
Adding a random piece of data causes the browsers to think its a new call.
Also, the random=randnum wont effect anything on the php side.