xmlhttp response Text - javascript

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.

Related

AJAX in codeigniter doesn't find base URL

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

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>

AJAX call the PHP script not outputting any results

I am trying to update my list of tweets via AJAX. I have ran the script on the page and know that script works, and I have a console.log line in my ajax call so I know that is getting hit as well.
setInterval(function () {sendRequest()}, 5000);
function sendRequest(){
var xmlhttp;
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){
console.log("yay");
}
}
xmlhttp.open("GET","getTweets.php",true);
xmlhttp.send();
}
My AJAX should run every 5 seconds, and the hit the PHP script to return new results that have been stored in the database. My PHP looks like:
$conn = mysqli_connect("localhost", "*", "*", "*");
if (!$conn) {
echo("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM tweets;";
$results = mysqli_query($conn, $query);
while($list = mysqli_fetch_assoc($results)){
echo '<div class="tweet-containter">';
echo '<img class="user-img" alt="user-img" src="images/gb.png">';
echo '<h3 class="tweet-username">#'.$list['username'].'</h3>';
echo '<p class="tweet-body">'.$list['tweetBody'].'</p>';
echo '<p class="tweet-body">Tweeted: '.$list['datePosted'].'Retweet: <i class="fa fa-retweet" id="retweet4" onclick="retweetAJAX()"></i> Like: <i class="fa fa-thumbs-up" id="likes4" onclick="likeAJAX()"></i> Dislike: <i class="fa fa-thumbs-down" id="dislikes4" onclick="dislikeAJAX()"></i></p>';
echo '</div>';
}
This goes for those that do not understand ReadyState codes. You should know the following codes for ReadyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
And Status Code
200: "OK"
404: Page not found
with that said, try doing this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
} else if(xmlhttp.status == 400) {
alert('There was an error 400')
} else {
alert('something else other than 200')
}
}
}
ryandonohue,
PHP is a Hyper-Text Processor. PHP runs on your server & the results are generated before the page is loaded. You should not be using PHP to output results like HTML elements, it is much more appreciated if you use JavaScript to manipulate the Document Object Model (DOM).
Though, for your intermediate purposes you might not notice an immediate difference.
For PHP5 you should look into the usage of PHP-PDO http://php.net/manual/en/class.pdo.php to prevent SQL injection.
Modification:
function getall($table, $values, $conditions = null, $limit = null, $ascdesc = null){
$values_str = "";
foreach($values as $key => $value){
$values_str .= $value . ", ";
}
$cond_str = "";
$hascond = false;
if($conditions != null){
$hascond = true;
foreach($conditions as $key => $value){
$cond_str .= $key . "='" . $value . "' AND ";
}
$cond_str = rtrim($cond_str, " AND ");
}
$values_str = rtrim($values_str, ", ");
$cond_str = " WHERE (" . $cond_str . ")";
$orderby = "";
$hasorder = false;
if($ascdesc != null){
$hasorder = true;
foreach($ascdesc as $key => $value){
$orderby = " ORDER BY " . $value . " " . $key;
break;
}
}
$sql = "SELECT " . $values_str . " FROM " . $table . " " . (($hascond)? $cond_str: "") . (($hasorder)? $orderby: "") . (($limit)? " LIMIT " . $limit: "");
//echo $sql;
$sql_prep = (new PDO('mysql:host=localhost;dbname=' . 'database', 'username', 'Password'))->prepare($sql);
$sql_prep->execute();
return $result = $sql_prep->fetchAll(PDO::FETCH_ASSOC);
}
initialization: ( returns an array so you need to json encode)
getall('table',
Array(
'*'
),
null, 5, null);
AJAX:
function ajax(file,type, params, func){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//xmlhttp.responseText
func(xmlhttp.responseText);
}
}
if(type.toLowerCase() != "post"){
xmlhttp.open(
type, file + "?" + params_to_get(params),
true
);
xmlhttp.send();
}else{
xmlhttp.open(
type, file,
true
);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params_to_get(params));
Since you have an error code of readystate of 4 with a status of 500 i would say the issue is more with the compatibility of MYSQLi or the way your table is set up with your database.
check out this POST for more information about headers:
Ajax call to PHP is returning nothing

I am trying to fetch image from database using ajax in php

here's my code i am trying to fetch image from Data Base using ajax but its not working please hep me out . image uploading working properly when i am trying to fetch image using anchor tag but it show my image on another page . but i want on same page at window load time.
getImage.php
if(filter_has_var(INPUT_GET, "image_id") !== false && filter_input(INPUT_GET, 'image_id', FILTER_VALIDATE_INT) !== false)
{
$image_id = filter_input(INPUT_GET, "image_id", FILTER_SANITIZE_NUMBER_INT);
try {
$dbh = new PDO("mysql:host=localhost;dbname=flipbook", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT image, image_type FROM testblob WHERE user_id=$image_id";
/*** prepare the sql ***/
$stmt = $dbh->prepare($sql);
$stmt->execute();
/*** set the fetch mode to associative array ***/
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$array = $stmt->fetch();
if(sizeof($array) == 2)
{
header("Content-type: ".$array['image_type']);
echo $array['image'];
}
else
{
throw new Exception("Out of bounds Error");
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
else
{
echo 'Please use a real id number';
}
}
index.php
<body onload="showUserProfilePic(<?php echo $_SESSION['current_user_id'];?>)">
<div id="txtHint">Child Picture will be listed here.</div>
<script>
function showUserProfilePic(str) {
//alert(str);
if (str == "") {
document.getElementById("txtHint").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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getImage.php?image_id="+str,true);
xmlhttp.send();
}
}
Try using
$sql = "SELECT image, image_type FROM testblob WHERE user_id='" . $image_id . "';
and where is your tag?

AJAX Silent Update from database

I am trying to update a paragraph from my html document using ajax but its not working and there is not error.
It simply does not change the value of the paragraph.
Is there an error in my code?
Thank you.
PHP/XML:
<?php
header('Content-Type :text/xml');
echo '<?xml version="1.0"encoding="UTF-8"standalone="yes"?>';
echo '<response>';
$connect = mysql_connect("****","***","****");
mysql_select_db("****");
$query = mysql_query("SELECT * FROM questions WHERE number=1");
$query2 = mysql_fetch_array($query);
echo $query2['q1'];
echo '</response>';
?>
javascript
<script>
var xmlHttp = createXmlHttpRequstObject();
function createXmlHttpRequstObject() {
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest();
} catch(e) {
xmlHttp=false;
}
if(!xmlHttp)
alert("NOPE");
else
return xmlHttp;
}
function refresh() {
if(xmlHttp.readyState==4||xmlHttp.readyState==0){
xmlHttp.open("GET","ref.php",true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
setTimeout('refresh()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
var xmlResponse = xmlHttp.responseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message= xmlDocumentElement.firstChild.data;
document.getElementById("choice1").innerHTML=message;
setTimeout('refresh()', 1000);
}
}
</script>
HTML:

Categories