AJAX PHP not returning a value - php

I am not sure what I am missing. Is there anything wrong with my syntax on the below? I am trying to request an answer using an HTML form and then check the answer against a value with a PHP script.
<!DOCTYPE html>
<html>
<head>
<title>Verify Identity</title>
</head>
<script>
function verify(e) {
if((e && e.keyCode == 13) || e == 0) {
document.forms.verifyForm.submit();
var golfer = document.getElementById("mgolf").value;
// window.alert("You answered: " + golfer);
//adding the ajax php call attempt 1
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("servRes").innterHTML = this.responseText;
}
};
xmlhttp.open("GET", "checkanswer.php?q=", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
}
</script>
<body>
<h2>Welcome Ben</h2>
<div onKeyPress="return verify(event)">
<form id="verifyForm" onsubmit="return false;">
Question 1 text:</br> <input type="text" id="mgolf">
</form>
</div>
<div id="test">
<p id="servRes">replace</p>
</div>
</body>
</html>
And the PHP
<?php
//create correct answer for test question
$answer = "Ben";
$q = $_REQUEST["q"];
if($q == $answer) {
echo "correct answer";
} else {
echo "incorrect answer";
}
?>

It's not working, because you are calling .submit(); on form element, which in result refreshes a page and you don't see a result of XMLHttpRequest. Removing this line and fixing 'innterHTML' make your code working.
<!DOCTYPE html>
<html>
<head>
<title>Verify Identity</title>
</head>
<script>
function verify(e) {
if((e && e.keyCode == 13) || e == 0) {
// document.forms.verifyForm.submit();
var golfer = document.getElementById("mgolf").value;
// window.alert("You answered: " + golfer);
//adding the ajax php call attempt 1
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("servRes").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "checkanswer.php?q=", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
}
</script>
<body>
<h2>Welcome Ben</h2>
<div onKeyPress="return verify(event)">
<form id="verifyForm" onsubmit="return false;">
Question 1 text:</br> <input type="text" id="mgolf">
</form>
</div>
<div id="test">
<p id="servRes">replace</p>
</div>
</body>
</html>

Related

add php variable into ajax

how to work with php variable without jQuery?
My test.php file:
<?php
session_start();
$language = 'zzz';
?>
<!DOCTYPE html>
<html lang="en">
<body>
<button onclick = "setCookie()">test</button>
<p id="demo"></p>
<script>
function setCookie() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "setCookie.php", true);
xhttp.send();
}
</script>
<?php
echo 'session: ' . $_SESSION['xxx'];
?>
</body>
</html>
and my setCookie.php file is:
<?php
session_start();
$_SESSION['xxx'] = $language;
?>
If I put some simple echo statement in setCookie.php, it works and appears on my website. But why it can`t assign $language value to session['xxx']?
Beacuse ajax will be new request when its call so you have to pass value with it.
try this:
test.php
<?php
session_start();
$language = 'zzz';
?>
<!DOCTYPE html>
<html lang="en">
<body>
<button onclick = "setCookie()">test</button>
<p id="demo"></p>
<script>
function setCookie() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
language = '<?=$language?>'; //get value
xhttp.open("POST", "setCookie.php", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send("language=" + language); //send as post params
xhttp.send();
}
</script>
<?php
echo 'session: ' . $_SESSION['xxx'];
?>
</body>
</html>
setCookie.php
<?php
session_start();
$language = $_POST['language']; //retrive value
$_SESSION['xxx'] = $language; //assign to session
?>
Just Change your setCookie.php file like below.
<?php
session_start();
$_SESSION['xxx'] = $_POST['language'];
?>

PHP setting JSON values to Textboxes

This is the html file.
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var doc = window.document.createElement("doc");
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("stuname").value=a.first;
document.getElementById("branch").value=a.second;
document.getElementById("year").value=a.third;
document.getElementById("category").value=a.four;
}
}
xmlhttp.open("GET","test2.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
Roll Number:<br>
<input type="text" name="rollno" id="rollno" onblur="showUser(this.value)">
<br>
Student Name:<br>
<input type="text" name="stuname" id="stuname" value="">
Branch:<br>
<input type="text" name="branch" id="branch" value="">
Year:<br>
<input type="text" name="year" id="year" value="">
Category:<br>
<input type="text" name="category" id="category" value="">
</form>
<br>
</body>
</html>
test2.php file
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$q = $_GET['q'];
$con=mysqli_connect("localhost","root","neel","sitams");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT rollno,stuname,branch,category FROM studet where rollno='".$q."' and academic='2014-2015'";
if ($result=mysqli_query($con,$sql))
{
while ($obj=mysqli_fetch_object($result))
{
$queryResult[] = $obj->rollno;
$queryResult[] = $obj->stuname;
$queryResult[] = $obj->branch;
$queryResult[] = $obj->category;
}
}
$textboxValue1 = $queryResult[0];
$textboxValue2 = $queryResult[1];
$textboxValue3 = $queryResult[2];
$textboxValue4 = $queryResult[3];
echo json_encode(array('first'=>$textboxValue1,'second'=>$textboxValue2,'third'=>$textboxValue3,'four'=>$textboxValue4));
?>
</body>
</html>
I could not able to load values to the text boxes where is fault. Even I have seen stackoverflow but I could not able to get it. when I type test2.php by passing rollno value to q it will display data but when I pass a value from html it could not able to set the values to the textbox fields.
Remove any html tags from test2.php . An ajax document does not need any html tags.
Hi this one will be helpful to you .
<html>
<head>
</head>
<body>
<input type="button" onclick="showUser('ok');" value="click to ru me" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function showUser(str)
{
if (str=="")
{
return;
}
else
{
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }
else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//var doc = window.document.createElement("doc");
var parsed = JSON.parse(xmlhttp.responseText);
for(var x in parsed)
{
var First=parsed[x].first;
var Second=parsed[x].second;
var Third=parsed[x].third;
var Fourth=parsed[x].fourth;
console.log("first="+First+" second="+Second+" third="+Third+" fourth="+Fourth);
document.getElementById("stuname").value=parsed[x].first;
document.getElementById("branch").value=parsed[x].second;
document.getElementById("year").value=parsed[x].third;
document.getElementById("category").value=parsed[x].fourth;
}
}
}
xmlhttp.open("GET","phpex.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<input type="text" id="stuname" />
<input type="text" id="branch" />
<input type="text" id="year" />
<input type="text" id="category" />
</body>
</html>
Ajax File Name phpex.php . ajax page code is below
<?php
echo '[{"first":"1111","second":"2222","third":"3333","fourth":"4444"}]';
?>

Ajax search not Working whereas the XML already running?

I'm a newbie on Ajax, I have tried the tutorial Book, but it did not work. The code is for searching.
This is the script search.htm
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX + MySQL I</title>
<script type="text/javascript" src="search.js"></script>
</head>
<body onload='process()'>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
</form>
<p><strong>Hasil Pencarian :</strong></p>
<div id="hasil" />
</body>
</html>
and the JS script search.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
if (!xmlHttp) alert("Obyek XMLHttpRequest tidak dapat dibuat");
else
return xmlHttp;
}
function process()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
nama =
encodeURIComponent(document.getElementById("namaMhs").value);
xmlHttp.open("GET", "search.php?namaMhs=" + nama, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
setTimeout('process()', 1000);
}
function handleServerResponse()
{
if (xmlHttp.readyState == 4)
{
if (xmlHttp.status == 200)
{
var xmlResponse = xmlHttp.responseXML;
xmlRoot = xmlResponse.documentElement;
nimArray = xmlRoot.getElementsByTagName("nim");
namaMhsArray = xmlRoot.getElementsByTagName("namamhs");
alamatArray = xmlRoot.getElementsByTagName("alamat");
if (nimArray.length == 0)
{
html = "Data tidak ditemukan";
}
else
{
// membentuk tabel untuk menampilkan hasil pencarian
html = "<table border='1'><tr><th>NIM</th><th>Nama
Mhs</th><th>Alamat</th></tr>";
for (var i=0; i<nimArray.length; i++)
{
html += "<tr><td>" + nimArray.item(i).firstChild.data +
"</td><td>" +
namaMhsArray.item(i).firstChild.data +
"</td><td>" +
alamatArray.item(i).firstChild.data +
"</td></tr>";
}
html = html + "</table>";
}
document.getElementById("hasil").innerHTML = html;
setTimeout('process()', 1000);
}
else
{
alert("Ada masalah dalam mengakses server: " +
xmlHttp.statusText);
}
}
}
and the last script in php search.php
<?php
header('Content-Type: text/xml');
echo '<hasil>';
$namaMhs = $_GET['namaMhs'];
mysql_connect("localhost","root","*******");
mysql_select_db("mahasiswa");
$query = "SELECT * FROM mhs WHERE namamhs LIKE '%$namaMhs%'";
$hasil = mysql_query($query);
while ($data = mysql_fetch_array($hasil))
{
echo "<mhs>";
echo "<nim>".$data['NIM']."</nim>";
echo "<namamhs>".$data['NAMAMHS']."</namamhs>";
echo "<alamat>".$data['ALAMAT']."</alamat>";
echo "</mhs>";
}
echo '</hasil>';
?>
Please help me to fix this script. The XML on search.php is already running but my searching is not. Any help is appreciated.
You are submitting the script on load, before there is even a value in the text field:
<body onload='process()'>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
</form>
You should either add a value to the text field as such:
<input type="text" value="testname" id="namaMhs" />
Or as a better option, add a submit button and don't run the function on load, but rather on submit:
<body>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
<input type="button" value="Search" onclick="process();" />
</form>
There may be more or even many more problems with your code, I am not looking through it all, but this should get you off to a good start.

Unable to receive values sent through post method

I am trying to send ID and sent from ajax_form.php to ajax_test.php()
my ajax_form.php is:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<script type="text/javascript">
function showUser(form, e) {
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var submit = form.getElementsByClassName('submit')[0];
//var sent = document.getElementsByName('sent')[0].value || '';
//var id = document.getElementsByName('id')[0].value || '';
var sent = form.elements['sent'].value;
var id = form.elements['id'].value;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value);
}
</script>
</head>
<body>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<label>Enter the sentence: <input type="text" name="sent"></label><br />
<input type="submit" class="submit" name="insert" value="submit" />
<input type="" name="id" style="display: none"/>
</form>
<h4>UPDATE</h4>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
<label>Enter the ID:</label><input type="text" name="id"><br>
<label>Enter the sentence:<input type="text" name="sent"></label><br />
</pre>
<input type="submit" class="submit" value="submit" name="update"/>
</form>
<br />
<div id="txtHint">
<b>Person info will be listed here.</b>
</div>
</body>
</html>
and ajax_test.php is:
<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head> <body >
<?php
$s = $_POST['sent'];
echo "Entered sentence : $s";
if (isset($_POST['insert']) && $_POST['insert'] !== '') {
echo "Operation: Insert","<br>";
$s = $_POST['sent'];
$flag = 0;
echo "Entered sentence : $s";
//database stuff
mysqli_close($con);
}
// -------------------------------UPDATE --------------------------
if (isset($_POST['update']) && $_POST['update'] !== '') {
echo "Operation: update", "<br>";
// you say update but you are actually inserting below
$s = $_POST['sent'];
$flag = 1;
echo "Entered sentence : $s";
//database stuff
mysqli_close($con);
}
?></html > </body >
Neither content outside if() get executed correctly nor if
I get error:
Notice: Undefined index: sent in /opt/lampp/htdocs/test/ajax_test.php on line 6
Just Entered sentence : get printed.
Where is the problem in post? Ideally I should able fetch id and sent !
You need to set the Content-Type on the request before sending it to application/x-www-form-urlencoded. See documentation.

my Codeigniter form with ajax return all page

In my project I user ajax to process form. Now i want to get Post data to process. I use Javascript when Jquery is not allowed. But Ajax return whole page, how can I fix that.
My controller :
class Form extends Controller {
function __construct() {
parent :: __construct();
$this->load->model('Form_model');
}
function index() {
$this->loadForm();
}
function loadForm() {
$this->load->view('form_view');
}
function ajax_add_form_content() {
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest") {
echo $_POST['fullname'] . '+' . $_POST['subject'];
} else {
echo '0';
}
}
}
And my view :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Form view</title>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "<?php echo base_url().'index.php/form/ajax_add_form_content'?>";
var fn = document.getElementById("txtFullName").value;
var ln = document.getElementById("txtSubject").value;
var vars = "fullname="+fn+"&subject="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
return false;
}
</script>
</head>
<body>
<div id="form">
<span id='status' ></span>
<form class="form" method="post">
<p class="formName">contact</p>
<p class="formDesc">contact us</p>
<div class="form_elements">
<div class="textField">
<label>Full name</label>
<input id="txtFullName" class="inputText required" type="text" maxlength="255" size="28" name="txtFullName">
</div>
<div class="textField">
<label>Subject</label>
<input id="txtSubject" class="inputText required" type="text" maxlength="255" size="28" name="txtSubject">
</div>
</div>
<div class="form_submit">
<input id="btnSubmit" type="submit" value="Send" name="btnSubmit" onClick="javascript:ajax_post();">
</div>
</form>
<div id='display'>
</div>
</div>
</div>
</body>
</html>
Thanks for any help !
Please try this
in your controller
function ajax_add_form_content() {
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest") {
echo $_POST['fullname'] . '+' . $_POST['subject'];
} else {
echo '0';
}
exit;
}
I would recommend You to use ie Chrome inspector to see whether You send request to the proper url.
Additionally instead of using $_SERVER variables You can use method from CI library $this->input->is_ajax_request().

Categories