AJAX search doesn't work with spaces - php

I have problem when user types with spaces into live Ajax search it doesn't show any results. When user types only half of word without spaces it works fine. I think its something with Ajax, but can't find any solution here.. Maybe you can suggest something.. Thanks.
Ajax:
function ajaxFunction(str)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if (httpxml.readyState == 4)
{
document.getElementById("displayDiv").innerHTML = httpxml.responseText;
document.getElementById("msg").style.display = 'none';
}
}
var url = "search-ajax.php";
url = url + "?txt=" + str;
url = url + "&sid=" + Math.random();
httpxml.onreadystatechange = stateChanged;
httpxml.open("GET", url, true);
httpxml.send(null);
document.getElementById("msg").innerHTML = "Please Wait ...";
document.getElementById("msg").style.display = 'inline';
}
search-ajax.php:
error_reporting(0);
require "search_con.php";
$in = $_GET['txt'];
if (!ctype_alnum($in)) {
echo "";
exit;
}
$msg = "";
$msg = "<div id=results style=position:absolute;z-index: 10;right:0px;background-color:#302b2b;>";
if (strlen($in) > 0 and strlen($in) < 20) {
$sql = "SELECT * FROM products WHERE name LIKE '%$in%' LIMIT 17";
foreach ($dbo->query($sql) as $nt) {
$name = $nt['name'];
$msg .='<div>' . $name . '<div>';
}
}
$msg .='</div>';
echo $msg;
What could it be? Thanks for all your suggestions :)

The function ctype_alnum will return false if the text contains a space. So maybe your script stops there ?
$in = $_GET['txt'];
//always occurs when a space is in the $in variable.
if (!ctype_alnum($in))
{
echo "";
exit;
}
Make sure you use trim() BEFORE you make that check. That check will also stop any search for a text which as space inside the text like "New year".

You have to remove leading and trailing spaces of txt in your PHP script:
$in = trim($_GET['txt']);

Solved it, I realised that I don't need this block of code.
if (!ctype_alnum($in)) {
echo "";
exit;
}

Related

How to pass javascript variable to php in html? (wikipedia parsing)

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();

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.

ajax json decode mysql fetch array

$result = mysql_query ("SELECT * FROM order_list");
$test = array();
$i=0;
$myjsons = array();
while($row = mysql_fetch_assoc($result)){
echo $myjsons[] = json_encode(array($row));
}
and a AJAX javascript
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
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 is too old to run me!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
document.getElementById("resultTXT").value = eval(" (" + ajaxRequest.responseText + ")");
}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}​
the javascript function wont store the array into the textbox
can anyone tell me whats the problem here?
Thanks
try:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo json_encode($myjsons);
instead of
while($row = mysql_fetch_assoc($result)){
echo $myjsons[] = json_encode(array($row));
}
you can use jquery library for tha ajax call http://api.jquery.com/jQuery.post/
$.post('userfind.php', function(data) {
$("#resultTXT").val(data);// ==document.getElementById("resultTXT").value =data;
},'json'
);
JSON output would be invalid in your example, build the array and out put a single json encoded array like so:
$myjsons = array();
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo json_encode($myjsons);

How to use AJAX in IE

i'm using IE and I need to do a simple AJAX that will display a table with values from the database once a dropdown has been changed.
Here is my script:
<script type="text/javascript">
function getXML()
{
var req;
try {
req = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
req = null;
}
}
}
if (!req){
return null;
} else {
return req;
}
}
function filter(month, year)
{
if(getXML()){
var xmlhttp = getXML();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mandayTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/filterMandays.php?m="+month+"&y="+year,true);
xmlhttp.send();
} else {
alert("Error initializing XMLHttpRequest!");
}
}
</script>
and here is my ajax php
<?php
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';"; //employee_details WHERE approver = 0"
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
/while($rows = $res->FetchRow())
for($i=0;$i<5;$i++)
{
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows[5];
$lastname = $rows[6];
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
THe problem is that on the first "ONCHANGE" it does not do anything.
on the 2nd "ONCHANGE" the headers of the table in the php code is the only one that's being echoed.
I alsoi tried doing it without the query and changing the loop into for($i=0;$i<5;$i++) and changed the qvalues to be displayed into "1" but still it does noty go into the loo[ and display it.
what seems to be the problem? :(
Start here : https://developer.mozilla.org/en/AJAX/Getting_Started , Mozilla explains the correct way to do this across browsers. Later, you may consider jQuery for cross-browser compatibility once you've learned the basics
Download and use jQuery for your website: http://docs.jquery.com/Downloading_jQuery#Download_jQuery
And then your code will be something like this:
$('.mydropdown').change(function(){
//get values for month, year
$.ajax({
url: "ajax/filterMandays.php?m="+month+"&y="+year,
type: "GET",
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});

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