Jump to content

Recommended Posts

How could I return a variable from php in the success part of ajax jquery?

 

 

This would be like what my php page would look like (which the ajax code refers to):

 

$id = $_POST['id'];
//code that would run here for whatever

//Then here is where I want to send a value back to the success of the ajax below
$variable_to_return = 'abc';

 

This is what I'm using for ajax:

function post()
{
var id = get('id');
$.ajax({
type: "POST",
url: "add_post.php",
data: "id="+id,
cache: false,
success: function(html){
//I need to have an html function for some code to be returned.
//and I want $variable_to_return to be put into a javascript variable:
var variable_returned_from_php = 'abc';
}

});

}

}

Link to comment
https://forums.phpfreaks.com/topic/224278-jquery-ajax-success-return-variable/
Share on other sites

You can either just simply echo it, or (better still as it allows multiple values to be returned and is handled negatively by js) use json.

 

$id = $_POST['id'];
//code that would run here for whatever

//Then here is where I want to send a value back to the success of the ajax below
echo json_encode(array('returned_val' => 'abc'));

 

function post()
{
  var id = get('id');
  $.ajax({
    type: "POST",
    url: "add_post.php",
    data: "id="+id,
    cache: false,
    dataType: 'json',
    success: function(html) {
      var variable_returned_from_php = html.returned_val;
    }
  });
}

Thank you, however this doesn't seem to be working.

It does output this from php:

 

{"postid":178}

 

however when i try to alert the variable from javascript it says undefined.

 

var post_id = html.postid;
alert(post_id);

mysql_query("INSERT INTO posts SET to_id='$db_uid',from_id='$session',post='$db_post',type='$type',date='$db_date'");
$id = mysql_insert_id();

echo json_encode(array('postid' => $id));

 

 

function profile_post(){
var o_post = $("#profile-post").val();
var id = get('id');
var post = o_post.replace(/^\s+|\s+$/g, '') ;


$('.profile-post-button').attr('id', 'inactive');
$.ajax({
type: "POST",
url: "ajaxpages/add_post.php",
data: "id="+id+"&post="+post,
cache: false,
success: function(html){

var post_id = html.postid;
alert(post_id);
}

});



}

 

 

That's the cut down version.

 

Should be fine. Maybe your query is failing. Try...

 

if (mysql_query("INSERT INTO posts SET to_id='$db_uid',from_id='$session',post='$db_post',type='$type',date='$db_date'")) {
  if (mysql_affected_rows()) {
    echo json_encode(array('msg' => 'success', 'postid' => mysql_insert_id()));
  } else {
    echo json_encode(array('msg' => 'failed'));
  }
}

 

success: function(html) {
  if (html.msg == 'success') {
    var post_id = html.postid;
    alert(post_id);
  } else {
    alert("Query failed");
  }
}

 

You are actually issuing the alert within the success method? The variable 'post_id' will not exist outside of this method.

I know that the code is working because in the ajax success code I have the html return the html from my php page print the json_encode line that returns the array and it prints the correct code in this format:

 

{"postid":178}

 

178 being the id of the post.

Javascript:

function profile_post(){
var o_post = $("#profile-post").val();
var id = get('id');
var post = o_post.replace(/^\s+|\s+$/g, '') ;

if($('.profile-post-button').attr('id')=="active")
{
if(post)
{
$('.profile-post-button').attr('id', 'inactive');
$.ajax({
type: "POST",
url: "ajaxpages/add_post.php",
data: "id="+id+"&post="+post,
cache: false,
success: function(html){

$("#profile-post").val('');	

$("#profile-post").addClass("profile-post");
$(".post-stream").prepend(html);
$(".post-stream li").slideDown("fast");
$("#posterror-1, #posterror-3").fadeOut("fast");
$('.profile-post-button').attr('id', 'active');

$(".last-post").fadeOut("fast", function(){$(".last-post").html(post)});
$(".last-post").fadeIn('fast');

var post_id = html.postid;
alert(post_id);
}

});
}

}

}

 

 

PHP:

 

<?php error_reporting(0); include("../includes.php");
$session = $_COOKIE['id'];
$db_uid = $_POST['id'];
$db_post = mysql_real_escape_string($_POST['post']);
$db_date = mktime();


$check_post = $db_post;
preg_match( "`((http)+(s)?:(//)|(www\.))((\w|\.|\-|_)+)(/)?(\S+)?`i", $check_post, $does_link_exist);
$link_exists = $does_link_exist[0];
if($link_exists)
{
$type = 1;//link
}
else
{
$type = 0;//status	
}

mysql_query("INSERT INTO posts SET to_id='$db_uid',from_id='$session',post='$db_post',type='$type',date='$db_date'");
$id = mysql_insert_id();

print json_encode(array('postid' => $id));

if($db_uid!=$session)
{
mysql_query("INSERT INTO notifications VALUES('','$db_uid','$session','$type','$id','','$db_date')");
}
$get_post = mysql_fetch_assoc(mysql_query("SELECT * FROM posts WHERE id='$id'"));
?>
<li id="<?php print $id?>" style="display:none;"><?php include("post_page.php");?></li>

I see, well I would need a way to be able to print data, and send information back to the jquery. However I did come up with the only solution I could think of, defining the variables in the bottom of the php file and that way it the javascript variables can be used for that. If you have a better way of doing this please let me know, if not thanks for the help you have given.

create an account and sign in.

 

http://www.kithell.com

 

When you sign in go to your profile, and add a post.

 

Now, once you click the "Share" button it prints the data (status, date, photo, everything else)

 

That PHP page, and Ajax code controls the whole process that is done when you click on the Share button.

I'm not sure you read my post properly.

 

The php scripts you use in Ajax must return valid data to Javascript and that is ALL.

 

If you tell Javascript that is is to make a request and that it is going to get json back and you send it json + a bunch of random html its going to get confused.

 

I suggest you organize your code accordingly.

I'm not sure if I understand exactly what you mean. Are you talking about the returning the Json data to ajax from the php page? That it has to JUST return the Json data for ajax to get the data from that?

 

That is exactly what I mean.

 

If you tell your program that it is going to receive a certain data type then give it something else what exactly would you expect to happen?

Okay, yeah I understand that I can only return Jason data back to the Ajax for that to work, however in this case I can't only send the Json data back, I have to send all the other code back for it to output the new post once posted. I have gone away from using the Json method for this, I am just assigned a javascript variable on the php page and when it returns the data to Ajax I can call those variables to get the information I need.

This is how I'm doing it now:

 

Ajax,

function profile_post(){
var o_post = $("#profile-post").val();
var id = get('id');
var post = o_post.replace(/^\s+|\s+$/g, '') ;

if($('.profile-post-button').attr('id')=="active")
{
if(post)
{
$('.profile-post-button').attr('id', 'inactive');
$.ajax({
type: "POST",
url: "ajaxpages/add_post.php",
data: "id="+id+"&post="+post,
cache: false,
success: function(html){

$("#profile-post").val('');	

$("#profile-post").addClass("profile-post");
$(".post-stream").prepend(html);
$(".post-stream li").slideDown("fast");
$("#posterror-1, #posterror-3").fadeOut("fast");
$('.profile-post-button').attr('id', 'active');
if(new_post&&last_post_id)
{
$(".last-post").fadeOut("fast", function(){$(".last-post").html(new_post)});
$(".last-post").fadeIn('fast');
$(".last-post-time").fadeOut("fast", function(){$(".last-post-time").html("a few seconds ago")});
$(".last-post-time").fadeIn('fast');
$(".last-post-time").attr("id", last_post_id);
}

}

});
}

}

}

 

PHP,

<?php error_reporting(0); include("../includes.php");
$session = $_COOKIE['id'];
$db_uid = $_POST['id'];
$db_post = mysql_real_escape_string($_POST['post']);
$db_date = mktime();


$check_post = $db_post;
preg_match( "`((http)+(s)?:(//)|(www\.))((\w|\.|\-|_)+)(/)?(\S+)?`i", $check_post, $does_link_exist);
$link_exists = $does_link_exist[0];
if($link_exists)
{
$type = 1;//link
}
else
{
$type = 0;//status	
}

mysql_query("INSERT INTO posts SET to_id='$db_uid',from_id='$session',post='$db_post',type='$type',date='$db_date'");
$id = mysql_insert_id();

if($db_uid!=$session)
{
mysql_query("INSERT INTO notifications VALUES('','$db_uid','$session','$type','$id','','$db_date')");
}
$get_post = mysql_fetch_assoc(mysql_query("SELECT * FROM posts WHERE id='$id'"));
?>
<li id="post<?php print $id?>" style="display:none;"><?php include("post_page.php");?></li>
<?php if($type==0&&$db_uid==$session)
{
?>
<script>
var last_post_id = <?php print $id?>;
var new_post = "<?php print truncate($db_post, 50);?>";
</script>
<?php }
else
{
?>
<script>
var last_post_id = null;
var new_post = null;
</script>
<?php }?>

  • 2 months later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.