AJAX in codeigniter doesn't find base URL - javascript

And my other question is that, is the code correct, will my AJAX request get to my controller ?
Here is the relevant parts on the code:
My view (I have this on a POST form cause I want to send the data on another table) :
<script> var base_url = <?php echo base_url(); ?> </script>
<label for="exampleInputEmail1">Apartament</label>
<select onchange="showUser(this.value)" name ="txtApartament1" class="form-control">
<?php foreach($getEntry as $value) { ?>
<option><?php echo $value->apartament ?></option>
<?php }?>
</select>
In the same view this is my AJAX part:
function showUser(str) {
if (str == "") {
document.getElementById("txtApartament1").innerHTML = "";
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtApartament1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", base_url + "usercontroller/ajaxp?q="+str,true);
xmlhttp.send();
}
}
And this is my controller - usercontroller.php function:
public function ajaxp(){
echo "received";
}
I will get this error:
(index):257 Uncaught ReferenceError: base_url is not defined
at showUser (localhost/adminigniter1/:257:29)
at HTMLSelectElement.onchange (localhost/adminigniter1/:205:89)
My project filename is codeigniter1!
I did not set any config file on codeigniter. should I ? Anything else?

Try like this..
1.Load url helper using $this->load->helper('url') or in applicaiton/config/autoload.php.
2.Set base_url config item in application/config/config.php
$config['base_url'] = 'your_url';
3.In your script.Remove var.Because it creates variable as local.So you can not use inside function.
base_url = <?php echo base_url();
OR put it var base_url = <?php echo base_url(); ?> inside showUser() function.
UPDATE
var url = base_url + "usercontroller/ajaxp?q="+str; //OR var url = <?php base_url();?>+"usercontroller/ajaxp?q="+str;
console.log(url);
xmlhttp.open("GET",url,true);
xmlhttp.send();

Related

Cannot get data passed to a php file using AJAX

I am trying to pass data back to the server and then use the reply to update the browser page.
My code for a SELECT input is as follows;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
The script code is as follows;
<script>
function findTeleNo(that){
alert("I am an alert box!" + that);
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TeleNo").value = this.responseText;
}
}
};
xhttp.open("GET", "findTeleNo.php?q=" + that, true);
xhttp.send();
</script>
The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.
And the PHP file is as follows;
<?php
$MatchCaptain = $_REQUEST["q"];
$teleNo = "";
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$teleNo = $db_field['TeleNo'];
break;
}
}
}
echo $teleNo;
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
$ufullName = $first_name." ".$last_name;
return $ufullName;
}
?>
The php file requests the q variable from the url and makes it $MatchCaptain.
This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script.
The field id I am trying to update is;
<p><b>Telephone Number: </b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>
The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that.
Any help as to how I get this working would be grateful.
I have changed my script to
<script>
function findTeleNo(that){
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
// OK
alert('response:'+xhttp.responseText);
document.getElementById("TeleNo").innerHTML = this.responseText;
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
};
</script>
The response shown by alert('response:'+xhttp.responseText); is correct and the line of code
document.getElementById("TeleNo").innerHTML = this.responseText;
does print the response to the web page.

Use Ajax to update data on page which is read from text file with PHP

I want to update data on my webpage using Ajax. This data is read using PHP script
and I want this function to carry out EVERY 5 seconds. For some reason, this is not happening at all.
My JavaScript:
<script>
function refresh(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementClassName("scroll").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gm.php?q=" + "<?php echo $mf[0]."-".$mf[1].".txt" ?>", true);
// The PHP variables refer to a specific file
xmlhttp.send();
}
setInterval(refresh,5000);
</script>
My gm.php file:
<?php
$q = $_REQUEST["q"];
$mr=fopen($q, "a+");
$line = fgets($mr);
while (!feof($mr)) {
$line = $line.fgets($mr);
} # while ends
fclose($mr);
echo $line. "<br />";
?>
I figured out that my element selector was wrong as I was using get ElementClassName instead of getElementsByClassName. Also, I hadn't given the element index in the class, due to which the element could not be selected.
Another reason was my usage of quotes within the JavaScript string which included the PHP script.
My JavaScript:
<script>
function refresh(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementsByClassName("scroll")[1].innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gm.php?q=" + '<?php echo $mf[0]."-".$mf[1].".txt" ?>', true);
// The PHP variables refer to a specific file
xmlhttp.send();
}
setInterval(refresh,5000);
</script>
My gm.php file:
<?php
$q = $_REQUEST["q"];
$mr=fopen($q, "a+");
$line = fgets($mr);
while (!feof($mr)) {
$line = $line.fgets($mr);
} # while ends
fclose($mr);
echo $line. "<br />";
?>

Live Search Using Ajax and PHP mysql

I created a Live Search using AJAX,PHP and mysql.here when I click on search result ,redirecting me to a particular page it works perfectly. Now I need a small change.
All I need is:
When I click on the search result, that particular result should be display in the input field.
Here is my AJAX code:
<script type="text/javascript">
END OF AJAX CODE
PHP CODE
<?php
ob_start();
session_start();
include("Base.php");
$dbase=new Base();
#$userID=$_SESSION['userID'];
$createdDate=date("Y-m-d");
$createdTime=date("h:i:s A");
$partialStates=mysql_escape_string($_REQUEST['q']);
$qryy="SELECT * from `gon_pro` WHERE `pro_name` LIKE
'%$partialStates%' ";
$pser=$dbase->execute($qryy);
$ser_nums=mysqli_num_rows($pser);
while($co[]=mysqli_fetch_array($pser)){
}
?>
<?php
foreach ($co as $key => $namo) {
$cv=$namo['pro_name'];
$cv_id=$namo['id'];
$cv_p=$namo['price'];
?>
<a href="pro_det.php?prolod=<?php echo $cv_id; ?>"><p class="res
col-md-6"><?php echo $cv; ?></p></a>
<?php
}
?>
END OF PHP CODE
function getStates(str) {
if (str.length == 0) {
document.getElementById("row").innerHTML = "";
document.getElementById("results").innerHTML =""
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML =
xmlhttp.responseText;
}
};
xmlhttp.open("GET", "support/getStates.php?q=" + str, true);
xmlhttp.send();
}
}
</script>

xmlhttp response Text

I am trying to update a particular div of my web page without reloading the complete page. Instead on response complete web page gets inserted in the targetid. I am using a javascript function to do so. Here are my code of php from where javascript function is called.
if($check_like==0)
{
// if user has not liked this post
$divid_like = $postid.'like';
echo "<div id='$divid_like'><a href='#' onClick=\"ajax_post('Ajax.php?action=Like-Status','postid=$postid','$divid_like',0);\" name='Like'> Like </a> </div>";
//echo "<a href='action.php?action=Like-Status&postid=$postid' name='Unlike'> Like </a>";
echo "<a href='#' onClick='' > Comment </a>";
echo "<a href='#' onClick='' > Share </a>";
}
Here is my javascript function :
<script language="JavaScript">
function ajax_post(url , args , targetid, add)
{
var xmlhttp;
if(window.XMLHttpRequest)
{
// works for all browser abve IE7, chrome and firefox
xmlhttp = new XMLHttpRequest();
}
else
{
//for IE5 and IE6 which i don't think i nedd to handle still
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(!xmlhttp)
document.getElementById(targetid).innerHTML = "somesdlkvnoisnvoanfvnfnerroor";
xmlhttp.open("POST",url, false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-length", args.length);
//xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
var xhr = event.target;
if(xhr.readyState==4 && xhr.status==200)
{
if(add==0)
{
document.getElementById(targetid).innerHTML = xhr.responseText;
}
else
{
document.getElementById(targetid).innerHTML+= xhr.responseText;
}
}
else
{
document.getElementById(targetid).innerHTML = "somebigbigbigrroor";
}
};
xmlhttp.send(args);
}
Ajax.php file being called to process data:
<?php
include_once("Includes/master_login.inc");
include_once("Includes/connect_to_database.php");
include_once("Includes/Users.php");
include_once("Includes/Friends.php");
include_once("Includes/current_page_url.php");
include_once("JavaScript/XML.js");
include_once("profile_display.php");
include_once("Includes/Status_Likes_Comment.php");
include_once("Includes/message.php");
include_once("Includes/NewsFeed.php");
include_once("sendmessage.php");
$action = $_GET["action"];
$uid = $_SESSION['uid'];
//if(!user_online($uid)){$action=0;}
if($action=="Add-Friend") { add_friend($uid,$_POST["uid"]); if($_POST["refresh"]="profile") echo display_profile($_POST["uid"]); }
if($action=="Respond-Friend-Request") {friend_accept($_POST["uid"],$uid); if($_POST["refresh"]="profile") echo display_profile($_POST["uid"]); }
if($action=="Like-Status") { like_status($uid,$_POST["postid"]); echo "Unlike"; }
if($action=="Chat-Send") {add_message($uid,$_POST["to"],$_POST["message"]); echo display_message($uid,$_POST["to"]);}
//if($action=="Chat-Send") {echo $_POST["message"]; delay(1000);}
?>
On liking the status instead of being replaced by Unlike complete page gets loaded in this div.

passing parameters from php to javascript on same page

I have the following code wherein I'm trying to get values of the xml element 'point' from an RSS feed using PHP. When I display the value of point using 'echo', it gives me the correct data. However, when I pass the same parameter to a javascript function, it calls the function very randomly. The alert in the javascript function gives me the sum of the points of either 2 or 3 point values from each iteration. How do I resolve this problem?
<!DOCTYPE html>
<html>
<head>
<title>Natural Disasters</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js? sensor=false&libraries=places"></script>
<script type="text/javascript">
var i=0;
function getPoint(point) {
alert("Value of i : "+i+" Value of point : "+point);
++i;
}
</script>
<script>
function showRSS(str) {
if (str.length === 0) {
document.getElementById("rssOutput").innerHTML = "";
return;
}
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) {
document.getElementById("rssOutput").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "getrss.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$xml2 = ("http://www.volcano.si.edu/news/WeeklyVolcanoRSS.xml?");
$xmlDoc2 = new DOMDocument();
$xmlDoc2->load($xml2);
$x2 = $xmlDoc2->getElementsByTagName('item');
$i2 = 0;
foreach ($x2 as $y) {
$geo_rss = $y->getElementsByTagNameNS("http://www.georss.org/georss", 'point');
$title = $y->getElementsByTagName('title')->item(0)->nodeValue;
$point = $geo_rss->item(0)->nodeValue;
echo ("<h3>" . $title . "</h3>" );
echo ($point);
echo '<script type="text/javascript">'
, 'getPoint(' . $point . ');'
, '</script>'
;
++$i2;
}
?>
</body>
</html>
P.S. :I have followed the same procedure for another set of parameters, and it works perfectly fine. I do not know why this one is not working.
Change your php code to write script as below :
echo '<script type="text/javascript"> getPoint("' . $point . '");</script>';
You just need to wrap $point into double quotes.

Categories