I want to make a php ajax post.(post value without refresh the page) here is my code. It can return the value and show in <div id="msg"></div>, But I also want to use this value.
In #benhowdle89 's help, I made $name= "<div id='msg'></div>". 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. Still waiting for help...
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"];
?>
This is what I want. 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. I want use them in other php part.
You can put the ajax response into a javascript variable, then you can manipulate it from there:
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
alert( myPhpVariable );
Here is a working javascript example (full code):
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 );
}
}
}
The PHP file would look like:
$postVar = $_POST["user_name"];
$postVarArr = explode('|', $postVar);
// will show abc
//echo $postVarArr['0'];
// will show def
echo $postVarArr['1'];
by including $name= "<div id='msg'></div>" and calling echo $name, you're just telling the program to store "" in the $name variable and then print what is stored in that variable. That's why you're getting the unwanted output.
not sure if you're having problems posting the value or showing it in the value, but you need to echo the variable where the userName is stored, may need to send that from the ajax to the php and set it to $name.
Related
Right now I have a program that uses AJAX to read in a XML file and a json file. The problem is once the user clicks one of these buttons the text stays on the page forever. I was wondering if there was a way to make a button that would delete the text and sort of start over. I tried making a reset button but it didn't work. Here is the code that I have. Thanks for the help in advance.
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml")
xmlHttp.send();
}
function getJSON() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>" + responseObject[i].name
+ " lived during the " + responseObject[i].pet
+ " period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<form>
<h3>Dinosaur Web Services</h3>
<div id="home"></div>
<button type="reset" value="Reset">Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();">JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();">XML Dinos</button>
</form>
</body>
</html>
You can empty the div before inserting the new value in it. Like below i have done for one of the div, and with same you can do to other.
Add this to your script
<script>
function reset() {
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = ""; // empty the div here
divObj.innerHTML = output;
}
</script>
and add this button in your HTML
RESET
Here you go:
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
document.getElementById('msg').style.display = "none";
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml");
xmlHttp.send();
}
function getJSON() {
document.getElementById('msg').style.display = "none";
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>"+responseObject[i].name + " lived during the " + responseObject[i].pet + " period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
function resetDivs(){
document.getElementById('msg').style.display = "block";
document.getElementById('dinoJSON').innerHTML = "";
document.getElementById('dinoXML').innerHTML = "";
}
</script>
</head>
<body>
<form>
<h3> Dinosaur Web Services </h3>
<div id="home"></div>
<div id="msg">Select a button</div>
<button type="reset" value="Reset" onclick="resetDivs();"> Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();"> JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();"> XML Dinos</button>
</form>
</body>
</html>
I would need some advice/assistance here. I'm trying to pass 2 variable to other page from a link using ajax but when i click the link, there is no response. Seem like my ajax is not working, would appreciate if anyone can assist here. Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="productshow.js"></script>
</head>
<body>
<?php
$sql = mysql_query ("SELECT * FROM espaceproduct WHERE email = 'jaychou#hotmail.com' ");
?>
<?php
$result1 = array();
$result2 = array();
$loopCount1 = 0;
$loopCount2 = 0;
while($row = mysql_fetch_array($sql))
{
$result1[] = $row['thumbnail'];
$result2[] = $row['id'];
$_SESSION['thumbnail'] = $result1;
//$url = "profileview.php?email=".$result1[$loopCount1].'&'. "id=".$result2[$loopCount2];
$loopproduct = $result1[$loopCount1];
$loopid = $result2[$loopCount2];
echo"<br/>"."<br/>";
echo '<a href="#" onClick="ajax_post($loopproduct,$loopid)" >'. $_SESSION['thumbnail'][$loopCount1] .'</a>'."<br/>" ;
$loopCount1++;
$loopCount2++;
}
?>
</body>
</html>
This my ajax page
function list_chats(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
document.getElementById("showbox").innerHTML = hr.responseText;
}
}
hr.open("GET", "productshow.php?t=" + Math.random(),true);
hr.send();
}
setInterval(list_chats, 500);
function ajax_post(la,ka){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "espaceproductinsert.php";
var kn = "add="+la+"&csg="+ka;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status1").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(kn); // Actually execute the request
document.getElementById("csg").value = "";
}
This is the page where the variables should be insert
<?php
$add = $_POST['add'];
$csg = $_POST['csg'];
$sql2 = mysql_query ("INSERT INTO espaceproduct ( storename,productname ) VALUES ('$add','$csg') ");
?>
Smiply Try this
function ajax_post(la,ka){
$.post("espaceproductinsert.php", { add:la, csg:ka},
function(data) {
alert(data);
});
}
In page 1 add this script appropriately
<script language="javascript" type="text/javascript">
var httpObject=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
}
function tranferData(){
var data1= document.getElementById('div1').value;
var data2= document.getElementById('div2').value;
var queryString = "?data1=" + data1;
queryString += "&data2=" + data2;
httpObject.onreadystatechange = function(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var error = document.getElementById('error');
var response = httpObject.responseText;
alert(response);
}
}
httpObject.open("GET", "page2.php"+queryString ,true);
httpObject.send(null);
}
</script>
You send the data using above script and recieve from another page
page 2
<?php
echo $_GET['data1'];
echo $_GET['data2'];
?>
and on the serverside do this
<?php
header('Content-Type: application/json');
echo json_encode($_GET); //for testing replace with array('key'=>$value);
?>
am trying to generate report through dynamically generated form. Through XMLHttpRequest the form loads well but the validation against the form fields wont work. I have tried eval() it works only during load time ( like eval(alert("hi")) but not on dom objects , think some scope problem. The form fields are dynamically generated and so its validation based on selection and availability role in database.
The code of two files is attached below
<script>
function showUser(str)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var s= xmlhttp.responseText;
parseScript1(s);
parseScript(s);
}
}
xmlhttp.open("GET","test2.php",true);
xmlhttp.send();
}
function parseScript1(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
var k = "<script> "+ scripts +"<\/script>";
document.getElementById("txtHint1").innerHTML=k ;
// Return the cleaned source
return source;
}
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
document.getElementById("txtHint").innerHTML=source;
// Return the cleaned source
return source;
}
function valid()
{
eval(validate());
}
</script>
<div id="txtHint1"><b>javascript will appear here</b></div>
<form>
<div id="nons1" >
<select id="nope1" name="users" onchange="showUser(this)">
<option value="">Select a option:</option>
<option value="1">not working here</option>
</select>
</div>
</form>
<div id="txtHint"><b>Select the value .</b></div>
test2.php
echo "<p>This form works fine singly not with xmlhttprequest";
echo'<form name="frm" method="post" action="test2.php" onsubmit="return(eval(validate()));">';
echo '<input value="" name="kfrm19" type="text">';
echo '<input name="save" value="submit" type="submit"></form>';
echo '<script>
function validate(){
if( document.frm.kfrm19.value.trim()=="")
{
alert( "If you can see this message .its working..." );
document.frm.kfrm19.focus() ;
return false;
}
}
</script>';
?>
try this:
function validate(){
if(document.frm.kfrm19.value.length == 0)
{
alert("If you can see this message .its working...");
document.frm.kfrm19.focus();
return false;
}
}
Hi I'm trying to pass a javascript variable called $url to a function in php all located in the same html file. The logic here is that there is a text box and the user inputs a species and we call the wikipedia api to check if the input has a wikipedia page if it does I parse the page and bring the species info up, everything works independently 100% but I cant seem to connect them. However I cant get javascript to pass the url to the php function below. and innerHTML the php function with the url which is suppose to render the parsed species info. The error I get is that from the get go I just get the php function spit out with nothing.
Enter a species here : [text box here]
find('table.infobox'); foreach($html->find('img') as $element) { $image[]= $element; } Print $image[1]; $data = array(); foreach($table[0]->find('tr') as $row) { $td = $row->find('> td'); if (count($td) == 2) { $name = $td[0]->innertext; $td = $td[1]->find('a'); $text = $td[0]->innertext; $data[$name] = $text; } } print ""; foreach($data as $value => $before ) { print ""; } print "
$value $before
"; } ?>
Here is my attempt so far, I call the javascript and check if a link is found and call the parse function to innerthml out in the result div
<?php
//call the javascript
//if link found
//send ajax url variable to php function
//ajax call the function innerhtml in the result div
//We check if we have the param within the page call
$theDeletenode = false;
if(isset($_POST['deletenode']))
$theDeletenode = $_POST['deletenode'];
if($theDeletenode)
{
//The param 'deletenode' is given, so we juste have to call the php function "parse", to return the value
parse($theDeletenode);
}else
{
// No parametre, so we echo the javascript, and the form (without the quote and \n, it's much better)
?>
Here is the start of my html, the text box is connected to javascript which called the wikipedia api to check if the input has a wikipedia page.
<html><head>
<script type="text/javascript">
// create and return an XMLHttpRequest object
function createRequest() {
var ajaxRequest; // the xmlrequest object
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
return ajaxRequest;
}; // end of createRequest
var spellcheck = function(data){
var found=false;var url='';
var text=data[0];
if(text!=document.getElementById('spellcheckinput').value) return;
for(i=0;i<data[1].length;i++)
{
if(text.toLowerCase()==data[1][i].toLowerCase())
{found=true;
url='http://en.wikipedia.org/wiki/'+text;
document.getElementById('spellcheckresult').innerHTML='<b style=\"color:green\">Correct</b> - <a target=\"_top\" href=\"'+url+'\">link</a>';
}
}
if(!found)
document.getElementById('spellcheckresult').innerHTML='<b style=\"color:red\">Incorrect</b>';
};
var requestone = createRequest();
var getjs= function(value)
{
if(!value) return;
var url='http://en.wikipedia.org/w/api.php?action=opensearch&search='+value+'&format=json&callback=spellcheck'; // this is the variable I want to pass
document.getElementById('spellcheckresult').innerHTML='Checking ...';
var elem=document.createElement('script');
elem.setAttribute('src',url);
elem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(elem);
// Ajax call to this page, this time with the 'deletenode' parameter
var vars = "url=" + encodeURIComponent(url);
requestone.open("POST", "parser.php", true); // parser.php : the name of this current page
requestone.onreadystatechange = handleRequest; // function to handle the response
requestone.send(vars);
};
function handleRequest()
{
//here we handle the php page response by echoing de result of the php page (normally the result of the parse function)
try{
if(requestone.readyState == 4 && requestone.status == 200)
document.getElementById('resultdiv').innerHTML= requestone.responseText;
} catch (e) {
//Wrong server answer...
}
};
</script>
</head>
<body>
<form action="#" method="get" onsubmit="return false">
<p>Enter a species here : <input id="spellcheckinput" onkeyup="getjs (this.value);" type="text">
<span id="spellcheckresult"></span></p>
</form>
<div id=resultdiv></div>
</body>
</html>
Here is my parse function which recieves a variable called url which is the validated wikipedia page and then it parses it for species info, this tested and it works but I cant get it to innerhtml this function along with the validated wikipedia url.
<?php
}
function parse($url){
print $url;
$html = file_get_html('http://en.wikipedia.org/wiki/Beaver');
$table = $html->find('table.infobox');
foreach($html->find('img') as $element)
{
$image[]= $element;
}
Print $image[1];
$data = array();
foreach($table[0]->find('tr') as $row)
{
$td = $row->find('> td');
if (count($td) == 2)
{
$name = $td[0]->innertext;
$td = $td[1]->find('a');
$text = $td[0]->innertext;
$data[$name] = $text;
}
}
print "<table class='infobox' style='text-align: left; width: 200px; font-size: 100%'>";
foreach($data as $value => $before )
{
print "<tr><td>$value</td><td>$before</td></tr>";
}
print "</table>";
}
?>
This question has many related answers 1234
If it helps, here is some JavaScript:
var form = document.createElement("form");
var input = document.createElement("input");
form.method="{post/get}";
form.action="{page}";
input.name="{name}";
input.value="{value}";
form.appendChild(input);
form.submit();
I've the following input text box and a button.
<div id="sender" onKeyUp="keypressed(event);">
Your message: <input type="text" name="msg" size="70" id="msg" />
<button onClick="doWork();">Send</button>
</div>
The keypressed(event) function actually detects if the key being pressed is "Enter" and calls the doWork() function.
function keypressed(e){
if(e.keyCode=='13'){
doWork();
}
}
This code seems to work fine in Chrome & Firefox. But in IE, the function seems to called twice.
Can anyone help me tweak the code so that it works properly in IE also.
Thanks
EDITED:
Whole ajax codes
<!--
var httpObject = null;
var link = "";
var timerID = 0;
var nickName = "Unname"; //"<?php echo $nickname; ?>";
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Change the value of the outputText field
function setOutput(){
if(httpObject.readyState == 4){
var response = httpObject.responseText;
var objDiv = document.getElementById("result");
objDiv.innerHTML += response;
objDiv.scrollTop = objDiv.scrollHeight;
var inpObj = document.getElementById("msg");
inpObj.value = "";
inpObj.focus();
}
}
// Change the value of the outputText field
function setAll(){
if(httpObject.readyState == 4){
var response = httpObject.responseText;
var objDiv = document.getElementById("result");
objDiv.innerHTML = response;
objDiv.scrollTop = objDiv.scrollHeight;
}
}
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
link = "message.php?nick="+nickName+"&msg="+encodeURIComponent(document.getElementById('msg').value);
httpObject.open("GET", link , true);
httpObject.onreadystatechange = setOutput;
httpObject.send(null);
}
}
// Implement business logic
function doReload(){
httpObject = getHTTPObject();
var randomnumber=Math.floor(Math.random()*10000);
if (httpObject != null) {
link = "message.php?all=1&rnd="+randomnumber;
httpObject.open("GET", link , true);
httpObject.onreadystatechange = setAll;
httpObject.send(null);
}
}
function UpdateTimer() {
doReload();
timerID = setTimeout("UpdateTimer()", 5000);
}
function keypressed(e){
if(e.keyCode=='13'){
doWork();
}
}
//-->
If someone is facing a similar problem, this could be useful.
I solved the problem by detecting IE browser using PHP script and discarding the onKeyUp() function while rendering HTML for IE.
IE Detection PHP script
//Detect IE function
function detectIE() {
if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
return true;
else
return false;
}
And this is how i changed the event handling.
<div id="sender" <?php if (detectIE()) { /*do nothing */ } else { echo "onKeyUp=\"keypressed(event);\""; } ?> >
Your message: <input type="text" name="msg" size="70" id="msg" />
<button onClick="doWork();">Send</button>
</div>