Problem in php ajax post value

I want to post value from index.php, then get the value by self without refresh the page. one botton with two values, I want explode them and finally get $namea and $nameb. then use them in other php part.
but when I use echo $name, in the source code, I can see <div id=‘msg’></div>(html tag), this is not a pure value, so I tried to use strip_tags, but the value lost. it seems the left the ajax pointed div tag, the value also gone.

index.php

<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<script language="javascript">  
function saveUserInfo() {  
    var msg = document.getElementById("msg");  
    var f = document.user_info;  
    var userName = f.user_name.value;  
    var url = "value.php";  
    var postStr   = "user_name="+ userName;  
    var ajax = false;  
 
    if(window.XMLHttpRequest) {  
        ajax = new XMLHttpRequest();  
        if (ajax.overrideMimeType) {  
            ajax.overrideMimeType("text/xml");  
        }  
    } else if (window.ActiveXObject) {  
        try {  
            ajax = new ActiveXObject("Msxml2.XMLHTTP");  
        } catch (e) {  
            try {  
                ajax = new ActiveXObject("Microsoft.XMLHTTP");  
            } catch (e) {  
            }  
        }  
    }  
 
    if (!ajax) {  
        window.alert("wrong");  
        return false;  
    }  
 
    ajax.open("POST", url, true);  
    ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    ajax.send(postStr);  
    ajax.onreadystatechange = function() {  
        if (ajax.readyState == 4 && ajax.status == 200) {  
            var myPhpVariable = ajax.responseText;  
            msg.innerHTML = myPhpVariable;  
            // myPhpVariable is now a variable which you can use 
            alert( myPhpVariable );  
        }  
    }  
}  
</script>  
</head>  
<body> 
<?php 
echo $name="<div id='msg'></div>"; 
$name1=strip_tags($name); 
$name2 = explode("|",$name1); 
$namea=$name2[0]; 
$nameb=$name2[1]; 
?> 
<form name="user_info" id="user_info" method="post">  
<input name="user_name" type="hidden" value="abc|def" /><br />  
<input type="button" value="abc|def" onClick="saveUserInfo()">  
</form>  
</body>  

value.php

<?php  
echo $_POST["user_name"];  
?>  

Your following PHP code does does not run after AJAX call.


echo $name="<div id='msg'></div>";  
$name1=strip_tags($name);  
$name2 = explode("|",$name1);  
$namea=$name2[0];  
$nameb=$name2[1];

Rather it runs when the page is loaded first time hence it just echos a DIV (<div id=‘msg’></div>). That’s it.

What AJAX can do for you is, runs value.php script/file and then gives you the output (printed/echoed in value.php) to repaint within an element. But exploding the name with pipe line “|” is needed to do in value.php.

See a simple example done with jQuery. I am jQuery lover so I would do your task like this:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <script type="text/javascript" src="jquery.js"></script>   
    <script type="text/javascript">
        $(document).ready(function(){
            $('#btnclick').click(function(e){
                var userName = $("#user_name").val();
                if(userName.length > 0){
                    $.post('value.php', {username : userName}, function(data){
                        $("#msg").html(data);
                    });
                }
                else{
                    alert('Enter username');
                }
            });
        });
    </script>
</head>
<body>  
    <div id="msg"></div>  
    <form name="user_info" id="user_info" method="post">   
        <input name="user_name" id="user_name" type="hidden" value="abc|def" /><br />   
        <input type="button" name="btnclick" id="btnclick" value="Save User Info" />   
    </form>
</body>
</html>

And your value.php file should look like this:


$username = $_POST['username'];
list($namea, $nameb) = explode("|", $username);
echo "Name A = $namea<br />";
echo "Name B = $nameb";

This will output:


Name A = abc
Name B = def

Inside the <div id=“msg”>.

Hope this is clear.

Thanks, but this just explode and show each one for a independent line in the <div id=“msg”>.
And I want $namea and $nameb can de manipulated in index.php. I want return two php variables.

What do you mean by ‘I want return two php variables.’? You want to return the variables from AJAX call? If you just want to split the entered name and show in the index.php itself then you can just do that only with JavaScript without AJAX call. I am confused what you want to do actually. Can you describe what you want to do actually?

I want to use $namea and $nameb in many section of my code. In fact, I have a group of buttons like abc|def, I want click each of them, without refresh the page(the page is base on a thickbox iframe child page, if refresh, the page will be closed and all the values will be lsot), output different values for php database process.
like


<ul>
        <?php
        $result = mysql_query("SELECT * FROM yokohama WHERE tag='".$namea.""); 
			while ($row = mysql_fetch_array($result))
			{
			echo '<li><span>'.$row['title'].'</span></li>';
			}
       ?>
</ul>


You should have this query in value.php itself and then assign the output of value.php to an element (div id=“msg” in your case I assume). Like your value.php should look like this:


<?php
<?php
// include your mysql connection file or connect directly from here

$username = mysql_real_escape_string($_POST['username']);
list($namea, $nameb) = explode("|", $username);
if(empty($namea)){
    die('Name not found');
}
$result = mysql_query("SELECT * FROM yokohama WHERE tag='".$namea."") or die(mysql_error());
if(mysql_num_rows($result) >= 1):
?>
<ul>
    <?php while ($row = mysql_fetch_array($result)): ?>
        <li><span><?php echo $row['title']; ?></span></li>
    <?php endwhile; ?>
</ul>
<?php else: ?>
No records found.
<?php endif; ?>

Now the output will be shown in your DIV.

Edit:
I haven’t tested it here but should work :slight_smile:

hi, rajug, this is a method, do all the thing move index.php from value.php then echo the value back to the div in index.php.
But it is not convenient, for example, if I use $namea to 3 database require, I should write 3 ajax js code that appoint 3 value show divs.

<div id=“msg1”></div>.
<div id=“msg2”></div>.
<div id=“msg3”></div>.

I don’t know what you are trying to do. But this is the way of working with AJAX.

right, maybe this is the only way. thanks again.