how to call name onkey up using ajax? - php

i am new to ajax. I want to get name from the database according to onkey up but i am getting this error in console "Invalid left-hand side in assignment". and when i type its showing "showname function is not defined".?
This is my code.
Search:
This is myscript
function showname(d) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp= new XMLHttpRequest();
}else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "ajax2.php?name"=+d, true);
xhttp.send();
}
this ajax2.php code
$name = $_GET["name"];
$db = new mysqli("localhost", "root", "", "customername");
$conn = $db->query("select customerName from customers like '".$name."%'");
$fetch = $conn->fetch_array();
?>
<?php foreach ($fetch as $key => $value) :?>
<p><?php echo $value ?></p>
<?php endforeach; ?>
Thanks you in advance.

xhttp.open("POST", "ajax2.php?name"=+d, true);
I think you got a typo there, put the = into the quote marks.
xhttp.open("POST", "ajax2.php?name=" + d, true);

Related

Why is my xmlhtpp request is returning an empty array?

I'm requesting data from my data.php file with the following request:
xmlhttp.send('request=getchartdata&'+'chart='+chart+'&'+'key='+key);
Here's the content of data.php:
if ($_POST["request"] == "getchartdata") {
/*Removing dash from key*/
$key = str_replace("-", "", $_POST["key"]);
if ($_POST["chart"] == "associationEvolutionSubventions") {
$result = $conn->prepare("SELECT grantYear, grantAmount FROM granttoassociation WHERE HEX(grantReceiver) = ? ");
/*grantReceiver is in binary*/
}
$result->execute(["{$key}"]);
while($rs = $result->fetch()) {
if ($outp != "") {
array_push($outp,$rs);
}
}
}
$outp = json_encode($outp);
echo($outp);
However, I'm getting an empty array in xmlhttp.responseText.
The connexion to the MySQL Database isn't the issue (another xmlhtpp request is returning data correctly). There's a few point where I'm unsure about my code though:
$result->execute(["{$key}"]); Is the syntax correct here?
HEX(grantReceiver) Is it correct to do this, given grantReceiver is in binary?
$key = str_replace("-", "", $_POST["key"]); Is it the correct syntax for removing dash?
Edit: here's the full AJAX code as requested.
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("POST", "wp-content/plugins/mygaloochart/data.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('request=getchartdata&'+'chart='+chart+'&'+'key='+key);
Rearrange your code. You should listen to onreadystate after Opening the request and setting request headers(The following is your revised code):
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "wp-content/plugins/mygaloochart/data.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.send('request=getchartdata&'+'chart='+chart+'&'+'key='+key);

Suggestion list won't be displayed

Let's say it looks like this:
<input type='text' name='customer' onkeyup='searchFor(this.value);' list='customers'>
And I have a datalist (which is embedded in PHP code which will be returned somewhere on the page)
<datalist id='customers'>
<option>$customer[0]['name']</option>
</datalist>
I want to enter a customer id and then it should return the name of the customer as a suggestion list below my text field.
That's my MySQL Query which works (var_dump() returns the correct value if entered a number)
$customer = $database->query("SELECT * FROM customers WHERE customerID LIKE ('%".$_POST["searchterm"]."%')")->fetchAll(PDO::FETCH_ASSOC);
But it doesn't show a suggestion list with my names.
In my opinion it's not working because I enter a number.
edited:
function searchFor(suchbegriff){
var xmlHttp = null;
if (typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xmlHttp = null;
}
}
}
if (xmlHttp) {
var url = "includes/search/search.php";
var params = "suchbegriff="+suchbegriff;
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("ergebnis").innerHTML = xmlHttp.responseText;
}
};
xmlHttp.send(params);
}
}
edited2
search.php
<?php
include_once("../Dbo.class.inc");
if (isset($_POST["searchterm"])){
$customer = $database->query("SELECT * FROM customers WHERE customerID LIKE ('%".$_POST["searchterm"]."%')")->fetchAll(PDO::FETCH_ASSOC);
echo "<datalist id='customers'>";
foreach($customer as $key => $value){
foreach($value as $key2 => $value2){
if($key2 == "Name" || $key2 == "name"){
echo "<option>" . $value2 . "</option>";
}
}
}
echo "</datalist>";
} ?>

form validation in codeigniter with ajax

I want to validate groupname.
I am using ajax but it is not working
This is my view
<?php echo form_input(['name'=>'groupname','class'=>'form-control','placeholder'=>'Enter group name','value'=>'','ng-model'=>'myWelcome[0].groupname','onkeyup'=>'loadValid(this.value)']) ?>
Javascript function
<script type="text/javascript">
function loadValid(v) {
if(v)
{
var url= window.location.href;
var res = url.split("/");
var groupid = res[res.length-1];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", site_url + "admin/Usergroup_controller/store_edit_group_name_ajax/" + groupid + "/" + v, true);
xhttp.send();
}
else
{
document.getElementById("demo").innerHTML = "Group name is required field.";
}
}
</script>
Controller function
public function store_edit_group_name_ajax($groupid,$groupname)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('groupname', 'Group name', 'trim|required|alpha|is_unique[group.groupname]|min_length[3]');
if( $this->form_validation->run() )
{
echo form_error('groupname','<p class="text-danger">','</p>');
}
}
Please help...
Make sure you are creating a response object first.
$response = new stdClass();
if ($this->form_validation->run() == false)
{
$response->status = 'failure';
$response->error = validation_errors('<p class="text-danger">', '</p>');
}
...
return $response;
In Javascript after getting response;
document.getElementById("demo").innerHTML = xhttp.responseText.error;
Just echo-ing ajax results is something you need to leave immediately. Please take it as a friendly advise.

PHP and AJAX onclick redirection

I am using Ajax to populate a drop down menu from the database, my question is how do I onclick redirect it to a page along with the CARD_ID i got back from the database?
right now when I click on it it's displaying the card name in the search bar which is part of what I want but now I need the other half the redirection. How can I achieve this?
<?php
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$str = $_GET['content'];
if(strlen($str))
{
$sel = mysqli_query($mysqli, "select CARD_NAME, CARD_ID,CARD_TYPE from cards where CARD_NAME like '".trim($str)."%'");
if(mysqli_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysqli_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysqli_fetch_array($sel))
{
$card_info = str_ireplace($str,"<b>".$str."</b>",($row['CARD_NAME']));
$card_type = str_ireplace($str,"<b>".$str."</b>",($row['CARD_TYPE']));
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\" onClick=\"display('".$row['CARD_NAME']."');\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
the javascript.
subject_id = '';
function handleHttpResponse() {
if (http.readyState == 4) {
if (subject_id != '') {
document.getElementById(subject_id).innerHTML = http.responseText;
}
}
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
function getScriptPage(div_id,content_id)
{
subject_id = div_id;
content = document.getElementById(content_id).value;
http.open("GET", "script_page.php?content=" + escape(content), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
if(content.length>0)
box('1');
else
box('0');
}
function highlight(action,id)
{
if(action)
document.getElementById('word'+id).bgColor = "#C2B8F5";
else
document.getElementById('word'+id).bgColor = "#F8F8F8";
}
function display(word)
{
document.getElementById('text_content').value = word;
document.getElementById('box').style.display = 'none';
document.getElementById('text_content').focus();
}
function box(act)
{
if(act=='0')
{
document.getElementById('box').style.display = 'none';
}
else
document.getElementById('box').style.display = 'block';
}
the html
<div class="ajax-div">
<div class="searchbar">
<input type="text" onKeyUp="getScriptPage('box','text_content')" id="text_content">
</div>
<div id="box"></div>
</div>
I'm not sure what you are trying to do, but it seems you want something like this:
1- Change the way you display your rows so that the ID gets sent to your function as well:
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\"
onClick=\"display('".$row['CARD_NAME']."', " . $row['CARD_ID'] . ");\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
^^^^^^^^^^^^^^^^^^^^^^^^^
2- Change your display function to redirect
function display(word, id)
{
// document.getElementById('text_content').value = word;
// document.getElementById('box').style.display = 'none';
// document.getElementById('text_content').focus();
window.location.href = "some_page.php?card_id=" + id;
}
I have commented out the original lines because there doesn't seem much point in doing stuff on a page you are leaving anyway. You could also completely remove the word parameter if this is the solution you are looking for.

Problem in php ajax post value

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.

Categories