Ajax request with OOP PHP - php

It is a simple application which shows an image based on the input result as well as its occupation and name when hovered. I am receving the following errors:
Notice: Undefined index: src in C:\xampp\htdocs\Ajax\Ajax_image\PHP_AJAX.php and Notice: Undefined index: name in C:\xampp\htdocs\Ajax\Ajax_image\PHP_AJAX.php
I am farely new to Ajax so any help is appreciated.
$(document).ready(function() {
$('#view').click(function() {
var namevalue = $('#name').val();
$.post("PHP_AJAX.php", {
name: namevalue
}, function(data) {
$('#bar').html(data);
$("img").hover(function(e) {
var s1 = "<img src=";
var s2 = " width='110px' height='120px' />";
var srcval = s1.concat($(this).attr('src'), s2);
$.post("PHP_AJAX.php", {
src: srcval
}, function(data1) {
$('#info').css({
top: e.clientY,
left: e.clientX,
backgroundColor: 'yellow'
}).fadeIn().html(data1);
});
}, function() {
$('#info').fadeOut();
});
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="PHP_AJAX.js"></script>
<style>
#info {color:black; border:5px blue solid; width:150px; height:100px;display:none;position:absolute;}
</style>
</head>
<body>
<p id='bar'>Please enter name to view image! </p>
<p id='info'>info</p>
<form>
<p>Name : <input type='text' name='name'id ='name'/></p>
</form>
<button id='view' name ='view'>View</button>
</body>
</html>
class Person
{
// some properties
private $name;
private $occupation;
private $image;
// constructor
public function __construct($nameval, $occuval, $imgval)
{
$this->name = $nameval;
$this->occupation = $occuval;
$this->image = "<img src=" . $imgval . " width='110px' height='120px' />";
}
// get name property
public function getname()
{
return $this->name;
}
// get occupation property
public function getoccupation()
{
return $this->occupation;
}
// get image property
public function getimage()
{
return $this->image;
}
}
$obj1 = new Person("Picasso", "Painter", "pi1.jpg");
$obj2 = new Person("Ronaldo", "Football Player", "ronaldo.jpg");
$obj3 = new Person("Picasso", "Teacher", "pi2.jpg");
$obj4 = new Person("Madonna", "Singer", "madonna.jpg");
// storing objects in an array
$arr = array($obj1, $obj2, $obj3, $obj4);
$count = 0;
for ($i = 0; $i < 4; $i++) {
// if name already exist
if ($arr[$i]->getname() == $_POST['name']) {
echo "<p>Image of " . $arr[$i]->getname() . "</p>";
echo "<p>" . $arr[$i]->getimage() . "</p>";
$count++;
}
if ($arr[$i]->getimage() == $_POST['src']) {
echo "<p>Name: " . $arr[$i]->getname() . "</p>";
echo "<p> Occupation:" . $arr[$i]->getoccupation() . "</p>";
$count++;
}
}
// if name doesn't exist
if ($count == 0) {
echo "<h3> NOT FOUND! </h3>";
}

you should check isset() before compare ex. $arr[$i]->getname() == $_POST['name']
so:
if (isset($_POST['name']) && $arr[$i]->getname() == $_POST['name']) {
...
}
if (isset($_POST['src']) && $arr[$i]->getimage() == $_POST['src']) {
...
}

Related

Get a return from JQuery to a PHP variable in a simple HTML PHP Form

so I have a very simple html form (form.php) and use php to inserted into a SQL DB.
The problem is that I have a dynamic add names feature (get_names.html), which I want to have the return from the javascript function "post()" to my PHP variable $name, so I can submit all the form at once.
For the field name, I use AJAX with PHP (return_names.php) to retrieve the 'name' as a string, and it works with $_POST.
How to pass the return from return_names.php to $name in the form?
form.php
<meta http-equiv="Content-type" content="text/html; charset=UTF-
8" />
<html>
<body>
<head>
<script type="text/javascript" src="myjquery.js"></script>
</head>
<?php
include("connect-db.php");
function renderForm($id = '', $place = '', $name ='') { ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<form action="" method="post">
<div>
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>ID: <?php echo $id; ?></p>
<?php } ?>
<br/>
<strong>Place: </strong> <input type="text" name="place"
value="<?php echo $place; ?>"/><br/>
<br/>
<strong>Name: </strong> <input type="text" name="name"
value="<?php echo $name; ?>"/><br/>
<br/>
<?php
if (isset($_POST['submit']))
{
$id = htmlentities($_POST['id'], ENT_QUOTES);
$place = htmlspecialchars($_POST['place'], ENT_QUOTES);
$name = htmlspecialchars($_POST['name'], ENT_QUOTES);
($stmt = $mysqli->prepare("INSERT mydb (id, place, name)
VALUES (?, ?, ?)"));
{
$stmt->bind_param("iss", $id, $place, $name);
$stmt->execute();
$stmt->close();
}
}
}
?>
<br/>
</div>
</form>
</body>
</html>
get_names.html
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
<script type='text/javascript'>
const optionsSelect = [{
id: 1,
title: 'Mr'
},
{
id: 2,
title: 'Mrs'
}
];
function getResults() {
const { selects, inputs } = getInputs();
return selects.reduce((acc, select, i) => {
const { title, name } = getValuesFromElements(select,
inputs[i]);
msg = (title && name) ? `${acc} ${title}. ${name}` : acc;
document.getElementById("asservat").innerHTML = msg;
var msgs = msg;
//return (title && name) ? `${acc} ${title}. ${name}` : acc;
return msgs;
}, '');
}
function getResultsAsArray() {
const { selects, inputs } = getInputs();
const getFieldValues = (select, i) => {
const { title, name } = getValuesFromElements(select,
inputs[i]);
return (title && name) ? `${title}. ${name}` : '';
};
return selects.map(getFieldValues).filter(Boolean);
}
function getValuesFromElements(select, {value: name}) {
const { title } = optionsSelect[select.value - 1];
return {title, name};
}
function getContainerElements(query) {
return Array.from(document.querySelectorAll(`#container >
${query}`));
}
function getInputs() {
const selects = getContainerElements('select');
const inputs = getContainerElements('input');
return {
selects,
inputs
}
}
function addFields() {
const { value: number } = document.getElementById('member');
const container = document.getElementById('container');
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (let i = 0; i < number; i++) {
const select = document.createElement('select');
for (let j = 0; j < optionsSelect.length; j++) {
const options = document.createElement('option');
options.value = optionsSelect[j].id;
options.text = optionsSelect[j].title;
select.appendChild(options);
}
container.appendChild(select);
container.appendChild(document.createTextNode(' -> Name ' + (i + 1)));
const input = document.createElement('input');
input.type = 'text';
container.appendChild(input);
container.appendChild(document.createElement('br'));
}
}
</script>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
Log results
<p id="container"></p>
<div id="asservat"></div>
<input type="button" value="Submit" onclick="post();">ajax<br />
<script type="text/javascript">
function post(){
var name = getResults();
$.post('return_names.php',{postname:name},
function(data){
$('#name').html(data);
});
return $('#name').html(data);
}
</script>
return_names.php
<?php
function data() {
$name = $_POST['postname'];
echo "Name as string ->", $name, " <- here";
return $name;
}
data();
?>
I expect to echo $name in the form.php and get the strings returned by "return_names.php" for example "Mr. Ann Mrs. Anna"
So updating this in case someone stumbles upon similar.
I managed using JQuery as following:
get_names.html
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
<script type='text/javascript'>
const optionsSelect = [{
id: 1,
title: 'Mr'
},
{
id: 2,
title: 'Mrs'
}
];
function getResults() {
const { selects, inputs } = getInputs();
return selects.reduce((acc, select, i) => {
const { title, name } = getValuesFromElements(select, inputs[i]);
msg = (title && name) ? `${acc} ${title}. ${name}` : acc;
document.getElementById("name").innerHTML = msg;
var msgs = msg ;
//return (title && name) ? `${acc} ${title}. ${name}` : acc;
return msgs;
}, '');
}
function getResultsAsArray() {
const { selects, inputs } = getInputs();
const getFieldValues = (select, i) => {
const { title, name } = getValuesFromElements(select, inputs[i]);
return (title && name) ? `${title}. ${name}` : '';
};
return selects.map(getFieldValues).filter(Boolean);
}
function getValuesFromElements(select, {value: name}) {
const { title } = optionsSelect[select.value - 1];
return {title, name};
}
function getContainerElements(query) {
return Array.from(document.querySelectorAll(`#container > ${query}`));
}
function getInputs() {
const selects = getContainerElements('select');
const inputs = getContainerElements('input');
return {
selects,
inputs
}
}
function addFields() {
const { value: number } = document.getElementById('member');
const container = document.getElementById('container');
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (let i = 0; i < number; i++) {
const select = document.createElement('select');
for (let j = 0; j < optionsSelect.length; j++) {
const options = document.createElement('option');
options.value = optionsSelect[j].id;
options.text = optionsSelect[j].title;
select.appendChild(options);
}
container.appendChild(select);
container.appendChild(document.createTextNode(' -> Name ' + (i + 1)));
const input = document.createElement('input');
input.type = 'text';
container.appendChild(input);
container.appendChild(document.createElement('br'));
}
}
</script>
<script type="text/javascript">
function post(){
var name = getResults();
$.post('return_names.php',{postname:name},
function(data){
var result = $('#name').html(data);
return result;
});
}
</script>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<p id="container"></p>
<div id="name"></div>
<?php $return_var = '<input type="button" value="Submit" onclick="post();">Post <br />';
echo $return_var;
?>
return_names.php
<?php
function returnString() {
$name = $_POST['postname'];
echo "the name entered ->", $name, " <- hier";
return $name;
}
returnString();

Undefined variables in PHP after sending data via Ajax

I am trying to send data via Ajax to my php file and process it, I don't know where is the error Ajax seems to be Okay but after receiving data via $_POST in php file but when I am trying to echo my variables I am getting errors.
I am sending data using a POST;
here is my frontend code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- <form id="ArticleEnterForm" method="POST" action="ProcessFormData.php"> -->
<div id="warningsDiv">
wowowo
</div>
<label id="ArticleTitleLabel">Article title: </label>
<input id="ArticleTitleInputField" type="text" name="">
<div>
</div>
<iframe id="ArticleiFrame"></iframe>
<label>Enter article: </label>
<textarea id="ArticleContentTextArea"></textarea>
<label id="ArticleFileNameLabel">Enter file name(save as):</label>
<input id="ArticleFileNameInputField" type="text">
<button id="SubmitButton" name="submitButton">Submit</button>
<!-- </form> -->
<script>
function SubmitForm() {
function CheckFields() {
var warningsDiv = document.getElementById('warningsDiv');
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
if (CheckFields == true) {
var articleTitle = ArticleTitle.value;
var articleContent = ArticleContent.value;
var articleFileName = ArticleFileName.value;
}
//submitting using POST method
var sendDataRequest = new XMLHttpRequest();
sendDataRequest.open("POST", "ProcessFormData.php", true);
sendDataRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendDataRequest.onreadystatechange = function () {
if (sendDataRequest.readyState === 2) {
warningsDiv.innerHTML = "<strong>Loading...</strong>";
}
if (sendDataRequest.readyState === 4 && sendDataRequest.status === 200) {
console.log("dtatus: " + sendDataRequest.readyState);
warningsDiv.innerHTML = sendDataRequest.responseText;
}
}
var dataToSend = "ArticleTitleData=" + articleTitle + "&ArticleContentData=" + articleContent + "&ArticleFileNameData=" + articleFileName;
sendDataRequest.send(dataToSend);
}
var submitButton = document.getElementById('SubmitButton');
submitButton.addEventListener("click", SubmitForm);
</script>
</body>
</html>
and here is my PHP code:
<?php
ini_set('display_errors', 'On'); //to get errors displayed
$ArticleTitle = "";
$ArticleContent = "";
$ArticleFileName = "";
if(isset($_POST['ArticleTitleData'])){
$ArticleTitle = $_POST['ArticleTitleData'];
}else {
echo("no var artn ");
}
echo("data was entered successfully following data was entered: Title: " . $ArticleTitle );
?>
where is the error in this script.
the response text I am seeing on browser screen is:
data was entered successfully following data was entered: Title: undefined
The problem is that some of the variables you are using, are undefined in the scope you are trying to use them in:
function CheckFields() {
// The variables defined with `var` exist in the scope of this function
var warningsDiv = document.getElementById('warningsDiv');
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
if (CheckFields == true) {
// No `ArticleTitle`, etc. here...
var articleTitle = ArticleTitle.value;
var articleContent = ArticleContent.value;
var articleFileName = ArticleFileName.value;
}
Note that you are defining your variables using var in the CheckFields() function. So the scope of these variables is that function and anything in it, they will not be available outside of the CheckFields() function.
To solve that, you can return them from or define them before the function.
For example:
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
function CheckFields() {
var warningsDiv = document.getElementById('warningsDiv');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
// etc.
Note that if you need the warningsDiv outside of the function as well, you would need to treat it the same.
Yes, I figured out what was the problem
short answer:
when I was not calling the CheckFields(); properly
long answer:
Instead of if(CheckFields() == true){ //something } I was doing if(CheckFields == true){ //something }
I came to know this because when I was submitting the input field empty there was no change in warningsDiv as it was supposed to be when CheckFields(); function is called.
Thanks everyone for helping me...

PHP return uploaded filename for verification

I just need someone to point me into a direction to do the following.
Once I successfully upload a file to /uploads on my server; the PHP iteratively changes the filename by adding a number if the same file exists (basic override protection). After the file is successfully uploaded, I need a PHP function that can return that filename AND THEN (this is the hard part) to the very page that triggered the PHP uploader script. I will then capture the filename as a variable and pass it to the next page via a cookie (this latter 2 things I already know how to do).
code PHP script:
<?php
$allowedExts = array("zip", "rar"/*, "bmp", "jpg", "png", "tiff"*/);
$temp = explode(".", $_FILES["file"]["name"]);
$name = pathinfo($_FILES["file"]["name"], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$i = '';
if ((($_FILES["file"]["type"] == "application/zip")
|| ($_FILES["file"]["type"] == "application/x-zip")
|| ($_FILES["file"]["type"] == "application/octet-stream")
|| ($_FILES["file"]["type"] == "application/x-zip-compressed")
|| ($_FILES["file"]["type"] == "application/x-rar-compressed")
/*|| ($_FILES["file"]["type"] == "image/bmp")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/tiff")*/)
&& ($_FILES["file"]["size"] < 50000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else
{
if (file_exists("upload/" . $name . $i . '.' . $extension))
{
while(file_exists("upload/" . $name . $i . '.' . $extension)) {
$i++;
}
$basename = $name . $i . '.' . $extension;
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $basename);
} else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
}
} else
{
echo "Invalid file";
}
?>
HTML5 Upload:
<!DOCTYPE html>
<!-- saved from url=(0044)http://html5demos.com/dnd-upload#view-source -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>HTML5 Demo: Drag and drop, automatic upload</title>
<body>
<section id="wrapper">
<header>
<h4>Drag and drop</h4>
</header>
<style>
#holder { border: 1px dashed lightgrey; width: 300px; min-height: 300px; margin: 20px auto;}
#holder.hover { border: 1px dashed #FFCC00; }
#holder img { display: block; margin: 10px auto; }
#holder p { margin: 10px; font-size: 14px; }
progress { width: 50%; }
progress:after { content: ''; }
.fail { background: #c00; padding: 2px; color: #fff; }
.hidden { display: none !important;}
</style>
<article>
<div id="holder">
</div>
<p id="upload" class="hidden"><label>Drag & drop not supported, but you can still upload via this input field:<br><input type="file"></label></p>
<p id="filereader" class="hidden">File API & FileReader API not supported</p>
<p id="formdata" class="hidden">XHR2's FormData is not supported</p>
<p id="progress" class="hidden">XHR2's upload progress isn't supported</p>
<p>Upload progress: <progress id="uploadprogress" min="0" max="100" value="0">0</progress></p>
</article>
<script>
var holder = document.getElementById('holder'),
tests = {
filereader: typeof FileReader != 'undefined',
dnd: 'draggable' in document.createElement('span'),
formdata: !!window.FormData,
progress: "upload" in new XMLHttpRequest
},
support = {
filereader: document.getElementById('filereader'),
formdata: document.getElementById('formdata'),
progress: document.getElementById('progress')
},
acceptedTypes = {
//'image/bmp': true
//'image/jpg': true,
//'image/png': true,
},
progress = document.getElementById('uploadprogress'),
fileupload = document.getElementById('upload');
"filereader formdata progress".split(' ').forEach(function (api) {
if (tests[api] === false) {
support[api].className = 'fail';
} else {
// FFS. I could have done el.hidden = true, but IE doesn't support
// hidden, so I tried to create a polyfill that would extend the
// Element.prototype, but then IE10 doesn't even give me access
// to the Element object. Brilliant.
support[api].className = 'hidden';
}
});
function previewfile(file) {
/*if (tests.filereader === true && acceptedTypes[file.type] === true) {
var reader = new FileReader();
reader.onload = function (event) {
var image = new Image();
image.src = event.target.result;
image.width = 250; // a fake resize
holder.appendChild(image);
};
reader.readAsDataURL(file);
} else {*/
holder.innerHTML += '<p>Uploaded ' + file.name + ' ' + (file.size ? (file.size/1024|0) + 'K' : '');
console.log(file);
/*}*/
}
function readfiles(files) {
//debugger;
var formData = tests.formdata ? new FormData() : null;
for (var i = 0; i < files.length; i++) {
if (tests.formdata) formData.append('file', files[i]);
previewfile(files[i]);
}
// now post a new XHR request
if (tests.formdata) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload_artwork.php');
xhr.onload = function() {
progress.value = progress.innerHTML = 100;
};
if (tests.progress) {
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
progress.value = progress.innerHTML = complete;
}
}
}
xhr.send(formData);
}
}
if (tests.dnd) {
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
readfiles(e.dataTransfer.files);
}
} else {
fileupload.className = 'hidden';
fileupload.querySelector('input').onchange = function () {
readfiles(this.files);
};
}
</script>
</body></html>
Submit the form with ajax form submit which will return the values of the file path . Hope this help's you..
<?php
if($_FILES["file"]["name"] != '')
{
$output_dir="uploads/";
if(move_uploaded_file($_FILES["file"]["tmp_name"],$output_dir.$_FILES["file"]["name"]))
{
chmod($output_dir.$_FILES["file"]["name"],0777);
echo $_FILES["file"]["name"];
exit;
}
}
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
var jvar="";
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm({
clearForm: 'true',
success: function(data){
if(data != '')
{
jvar=data;
window.location.href="test.php?path="+jvar;
//Assign the to a variable and pass to another file
}
}
});
});
</script>
</head>
<form id="myForm" action="test.php" method="post">
<input type="file" name="file">
<input type="submit" value="Submit Comment" />
</form>
Create two fields in database 1st name and 2nd server name to access it later
$name = $_FILES['file']['name'];
//Insert this in first field
//Insert it in server name field
$stored_name = $_FILES['file']['name'].rand(10, 50);
// name generated by you not automatically added if file already exists
move_uploaded_file($_FILES["file"]["tmp_name"], $stored_name);
Check out rand function here
http://php.net/manual/en/function.rand.php

codeigniter : passing data from view to controller not working

I have this code in my view file (searchV.php):
<html>
<head>
<title>Search Domains</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function noTextVal(){
$("#domaintxt").val("");
}
function searchDom(){
var searchTxt = $("#searchTxt").val();
var sUrl = $("#url").val();
$.ajax({
url : sUrl + "/searchC",
type : "POST",
dataType : "json",
data : { action : "searchDomain", searchTxt : searchTxt },
success : function(dataresponse){
if(dataresponse == "found"){
alert("found");
}
else{
alert("none");
}
}
});
}
</script>
</head>
<body>
<form id="searchForm">
<input type="text" id="searchTxt" name="searchTxt" onclick="noTextVal()" >
<input type="submit" id="searchBtn" name="searchBtn" value="Search" onclick="searchDom()" />
<input type="hidden" id="url" name="url" value="<?php echo site_url(); ?>" />
</form>
<?php
var_dump($domains);
if($domains!= NULL){
foreach ($domains->result_array() as $row){
echo $row['domain'] . " " . $row['phrase1'];
echo "<br/>";
}
}
?>
</body>
</html>
and below is my controller (searchC.php):
<?php
class SearchC extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('searchM');
}
public function index()
{
$data['domains'] = $this->searchM->getDomains();
$this->load->view('pages/searchV', $data);
switch(#$_POST['action']){
case "searchDomain":
echo "test";
$this->searchDomains($_POST['searchTxt']);
break;
default:
echo "test2";
echo "<br/>action:" . ($_POST['action']);
echo "<br/>text:" . $_POST['searchTxt'];
}
}
public function searchDomains($searchInput)
{
$data['domains'] = $this->searchM->getDomains($searchInput);
$res = "";
if($data['domains']!=NULL){ $res = "found"; }
else{ $res = "none"; }
echo json_encode($res);
}
} //end of class SearchC
?>
Now I've done a test on the controller using switch to check if the json data passed was successful but it's always showing undefined.. What's wrong here? Can someone explain why the data is not recognized in the controller??
You aren't passing the data in via the url, so you need to use $this->input->post() to retrieve the data.
For example,
public function searchDomains()
{
$data['domains'] = $this->searchM->getDomains($this->input->post('searchTxt'));
$res = "";
if($data['domains']!=NULL){ $res = "found"; }
else{ $res = "none"; }
echo $res;
}
I believe that the data is being correctly returned, but the problem is with your code check. The $.ajax function parses the JSON and transforms it into a JavaScript object. Therefore you would need to modify your code as follows:
if(dataresponse.res == "found"){ // Changed from dataresponse to dataresponse.res
alert("found");
}
else{
alert("none");
}
This should work for you.

chat app using jquery/ajax/php/oop codeigniter

Hi this question relates to a recent question I had posted that I'm trying to find at least some help with in general that leads to solve the entire problem.
The following code is not mine and I had to fix it just to get it working to the extent it is now but the problem the algorithm within _get_chat_messages continues to execute the else condition. This doesn't make sense because there's chat message data in Mysql. I'm trying to make this source code work hoping it will lead me in the right direction with refreshing chat message content automatically without forcing browser client refreshes or redirecting headers.
What's causing _get_chat_messages to execute the else condition disregarding the if condition. The if conditions seems to evaluate to TRUE which doesn't make sense.
Any help much appreciated. Thanks.
//JQUERY/AJAX:
$(document).ready(function() {
setInterval(function() { get_chat_messages(); } , 2500);
$("input#chat_message").keypress(function(e) {
if (e.which == 13) {
$("a#submit_message").click();
return false;
}
});
$("#submit_message").click(function() {
var chat_message_content = $("input#chat_message").val();
//this if condition seems to be ignored not sure why?
if (chat_message_content == "") { return false; }
$.post(base_url + "chat/ajax_add_chat_message", { chat_message_content : chat_message_content, chat_id : chat_id, user_id : user_id }, function(data) {
if (data.status == 'ok')
{
var current_content = $("div#chat_viewport").html();
$("div#chat_viewport").html(current_content + data.message_content);
}
else
{
// there was an error do something
}
}, "json");
$("input#chat_message").val("");
return false;
});
function get_chat_messages()
{
$.post(base_url + "chat/ajax_get_chat_messages", { chat_id : chat_id }, function(data) {
if (data.status == 'ok')
{
var current_content = $("div#chat_viewport").html();
$("div#chat_viewport").html(current_content + data.message_content);
}
else
{
// there was an error do something
}
}, "json");
}
get_chat_messages();
});
//CONTROLLER:
class Chat extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->model('chat_model');
}
public function index()
{
/* send in chat id and user id */
$this->view_data['chat_id'] = 1;
// check they are logged in
if (! $this->session->userdata('logged_in')) {
redirect('user/login');
}
$this->view_data['user_id'] = $this->session->userdata('user_id');
$this->session->set_userdata('last_chat_message_id_' . $this->view_data['chat_id'], 0);
$this->view_data['page_title'] = 'web based chat app :)';
$this->view_data['page_content'] = 'view_chat';
$this->load->view('view_main', $this->view_data);
}
public function ajax_add_chat_message()
{
/* Scalar Variable data that needs to be POST'ed to this function
*
* chat_id
* user_id
* chat_message_content
* *
*/
$chat_id = $this->input->post('chat_id');
$user_id = $this->input->post('user_id');
$chat_message_content = $this->input->post('chat_message', TRUE);
$this->chat_model->add_chat_message($chat_id, $user_id, $chat_message_content);
// grab and return all messages
$this->ajax_get_chat_messages($chat_id);
}
public function ajax_get_chat_messages($chat_id)
{
$chat_id = $this->input->post('chat_id');
echo $this->_get_chat_messages($chat_id);
}
private function _get_chat_messages($chat_id)
{
$last_chat_message_id = (int)$this->session->userdata('last_chat_message_id_' . $chat_id);
$chat_messages = $this->chat_model->get_chat_messages($chat_id, $last_chat_message_id);
if ($chat_messages->num_rows() > 0)
{
// store the last chat message id
$last_chat_message_id = $chat_messages->row($chat_messages->num_rows() - 1)->chat_message_id;
$this->session->set_userdata('last_chat_message_id_' . $chat_id, $last_chat_message_id);
// we have some chat let's return it
$chat_messages_html = '<ul>';
foreach ($chat_messages->result() as $chat_message)
{
$li_class = ($this->session->userdata('user_id') == $chat_message->user_id) ? 'class="by_current_user"' : '';
$chat_messages_html .= '<li ' . $li_class . '>' . '<span class="chat_message_header">' . $chat_message->chat_message_timestamp . ' by ' . $chat_message->name . '</span><p class="message_content">' . $chat_message->chat_message_content . '</p></li>';
}
$chat_messages_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $chat_messages_html);
//header('Content-Type: application/json',true);
return json_encode($result);
exit();
}
else
{
// we have no chat yet
$result = array('status' => 'no chat', 'content' => '');
//header('Content-Type: application/json',true);
return json_encode($result);
exit();
}
}
}
//MODEL:
class chat_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function add_chat_message($chat_id, $user_id, $chat_message_content)
{
$query_str = "INSERT INTO chat_messages (chat_id, user_id, chat_message_content) VALUES (?, ?, ?)";
$this->db->query($query_str, array($chat_id, $user_id, $chat_message_content));
}
public function get_chat_messages($chat_id, $last_chat_message_id = 0)
{
$query_str = "SELECT
cm.chat_message_id,
cm.user_id,
cm.chat_message_content,
DATE_FORMAT(cm.create_date, '%D of %M %Y at %H:%i:%s') AS chat_message_timestamp,
u.name
FROM chat_messages cm
JOIN users u ON cm.user_id = u.user_id
WHERE cm.chat_id = ?
and cm.chat_message_id > ?
ORDER BY cm.chat_message_id ASC";
$result = $this->db->query($query_str, array($chat_id, $last_chat_message_id));
return $result;
}
}
//VIEW FILE HENCE VIEW_CHAT.PHP
<html>
<head>
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<?php echo base_url() . 'public/';?>chat.js">
</script>
<script type="text/javascript">
var base_url = "<?php echo base_url();?>";
var chat_id = "<?php echo $chat_id; ?>";
var user_id = "<?php echo $user_id; ?>";
</script>
</head>
<body>
<style type="text/css">
div#chat_viewport {
font-family:Verdana, Arial, sans-serif;
padding:5px;
border-top:2px dashed #585858;
min-height:300px;
color:black;
max-height:650px;
overflow:auto;
margin-bottom:10px;
width:750px;
}
div#chat_viewport ul {
list-style-type:none;
padding-left:10px;
}
div#chat_viewport ul li {
margin-top:10px;
width:85%;
}
span.chat_message_header {
font-size:0.7em;
font-family:"MS Trebuchet", Arial, sans-serif;
color:#547980;
}
p.message_content {
margin-top:0px;
margin-bottom:5px;
padding-left:10px;
margin-right:0px;
}
input#chat_message {
margin-top:5px;
border:1px solid #585858;
width:70%;
font-size:1.2em;
margin-right:10px;
}
input#submit_message {
font-size:2em;
padding:5px 10px;
vertical-align:top;
margin-top:5px;
}
div#chat_input { margin-bottom:10px; }
div#chat_viewport ul li.by_current_user span.chat_message_header {
color:#e9561b;
}
</style>
<h1>Let's do some chatting :D</h1>
<div id="chat_viewport">
</div>
<div id="chat_input">
<?php echo form_open('chat/ajax_add_chat_message'); ?>
<input id="chat_message" name="chat_message" type="text" value="" tabindex="1" />
<?php echo form_submit('submit_message','submit_message'); ?>
<?php echo anchor('#', 'Say it', array('title' => 'Send this chat message', 'id' => 'submit_message'));?>
<div class="clearer"></div>
<?php echo form_close(); ?>
</div>
</body>
</html>
I am not sure but I have a feeling that the json that you receive from the server is not formatted properly. See this: jQuery won't parse my JSON from AJAX query

Categories