I have a function called function getContactsToForm();
This function runs on a div row called results that holds the values from my sql. On click each row is supposed to load this function grab the data from li[0] and pass it on to the rest of the function.
I seem to be getting it to work all right, however the Li's show up empty on my console log even though the table is populated. I assume that means that the sequencing is wrong.
Previously I had a working sample that had everything it table rows. The original function commented out would use the Tr tags and grab the value. The function was called within the getContacts() function and it all worked well, with the LI I am having trouble. Any thoughts?
functions.js
// JavaScript Document
//formoverlay
function formSubmit() {
$.ajax({
type: 'POST',
url: 'contactsinsert.php',
data: $('#frmBox').serialize(),
success: function(response) {
$('#success').html(response);
}
});
var form = document.getElementById('frmBox').reset();
window.location.reload();
return false;
}
$(document).ready(function() {
$('#srchbtn').click(function start() {
getContacts();
});
});
function getContacts() {
var txtsearch = $('#txtsearch').val();
$.ajax({
url: 'contactstable.php',
type: "POST",
//dataType: "json",
data: ({
txtsearch: txtsearch
}),
success: function(response) {
$('#displayContacts').html(response);
//addRowHandlers();
//getContactsToForm();
}
});
}
window.onload = getContacts();
/*function addRowHandlers() {
console.log("hi");
var table = document.getElementById("resultstable");
var rows = table.getElementsByTagName("li");
console.log(rows[0]);
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
console.log(currentRow);
var createClickHandler = function(row) {
return function() {
*/
function getContactsToForm() {
var table = document.getElementById("resultstable");
var rows = table.getElementsByTagName("ul")['results'];
console.log(rows);
var lis = table.getElementsByTagName('li')[0];
console.log(lis);
var id = lis.innerHTML;
console.log(id);
//alert("id:" +id);
document.getElementById("id").value = id;
$.ajax({
url: "inputtest.php",
success: function(result) {
var frm = document.getElementById("frmBox2");
var ID = document.getElementById("id").value;
if (/\S/.test(ID)) {
ajax_request(this.action, {
"action": "fetch",
"ID": ID
}, process_response);
} else {
alert("No ID supplied");
}
function ajax_request(url, data, callback) {
var i, parts, xhr;
// if data is an object, unroll as HTTP post data (a=1&b=2&c=3 etc.)
if (typeof data == "object") {
parts = [];
for (i in data) {
parts.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
data = parts.join("&");
}
// create an XML HTTP Request object
xhr = new XMLHttpRequest();
if (xhr) {
// set a handler for changes in ready state
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// check for HTTP status of OK
if (xhr.status == 200) {
try {
callback(JSON.parse(xhr.responseText));
} catch (e) {
console.log(xhr.responseText); // for debug
alert("AJAX request incomplete:\n" + e.toString());
}
} else {
alert("AJAX request failed: " + xhr.status);
}
}
};
// open connection and send payload
xhr.open("GET", "inputtest.php" + "?" + data, true);
xhr.send(null);
}
}
/**
* process the response, populating the form fields from the JSON data
* #param {Object} response the JSON data parsed into an object
*/
function process_response(response) {
var frm = document.getElementById("frmBox2");
var i;
console.dir(response); // for debug
for (i in response) {
if (i in frm.elements) {
frm.elements[i].value = response[i];
}
}
}
}
});
};
// currentRow.onclick = createClickHandler(currentRow);
// }
// }
//window.onload = addRowHandlers();
function openNav() {
document.getElementById("myNav").style.width = "100%";
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
window.location.reload();
}
function openCon() {
document.getElementById("conNav").style.width = "100%";
}
function closeCon() {
document.getElementById("conNav").style.width = "0%";
var form = document.getElementById('frmBox').reset();
}
function enablebuttons() {
document.getElementById("insert").disabled = false;
}
contactstable.php (calls the mysql and receives contacts)
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<?php
include_once "iud.php";
$arrayval = array();
$search=$_POST['txtsearch'];
$search1 = explode(" ", $search);
array_push($arrayval, $search1);
foreach ($arrayval as $val){
$orIndex = checkOr($val);
if(empty($orIndex)){
$resultstable = getResults($val);
$resultstable1 = buildTable($resultstable);
print($resultstable1);
}else{
print"there is an or here";
$resultstable = getResults($orIndex);
$resultstable1 = buildTable($resultstable);
print($resultstable1);
}
}
buildTable($resultstable);
/*if (empty($orIndex)){
print "no or";
$resultstable = getResults($val);
$resultstable1 = buildTable($resultstable);
print $resultstable1;
function getResults($array){
include_once "iud.php";
$db = connectDatabase();
$totalResults = array();
$length = count($array);
for ($i = 0; $i < $length; $i++){
$outputDisplay = "";
$myrowcount = 0;
$sql_statement = "SELECT id, firstname, lastname, pcat, position, state ";
//, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes ";
$sql_statement .= "FROM contacts ";
$sql_statement .= "WHERE (firstname LIKE '%$array[$i]%' or lastname LIKE '%$array[$i]%')";
$sql_statement .= "ORDER BY lastname, firstname";
$sqlResults = selectResults($db, $sql_statement);
$error_or_rows = $sqlResults[0];
if (substr($error_or_rows, 0 , 5) == 'ERROR')
{
$outputDisplay .= "<br />Error on DB";
$outputDisplay .= $error_or_rows;
} else {
$totalResults = array_merge($totalResults, $sqlResults);
//$totalResults = array_map("unserialize", array_unique(array_map("serialize", $totalResults)));
$arraySize = $error_or_rows;
}
}
//return $totalResults;
//print $arraySize;
//print_r($error_or_rows);
return $totalResults;
}
function buildTable($totalResults){
include_once "iud.php";
$outputDisplay = "";
//$outputDisplay .= '<table id="resultstable" style="overflow-x:auto;">';
//$outputDisplay .= '<tr><th align="left">ID</th><th align="left" width="30%">First Name</th><th align="left" width="30%">Last Name</th><th align="left" width="30%">Pages Category</th><th align="left" width="30%">Position</th><th align="left" width="30%">state</th></tr>';
$outputDisplay .= '<div id="resultstable">';
$outputDisplay .= '<div id="headers">';
$outputDisplay .= '<ul id="headers">';
$myrowcount = 0;
for ($i=0; $i < count($totalResults); $i++)
{
$myrowcount++;
$contactid = $totalResults[$i]['id'];
$firstname = $totalResults[$i]['firstname'];
$lastname = $totalResults[$i]['lastname'];
$pcat = $totalResults[$i]['pcat'];
$position = $totalResults[$i]['position'];
$state = $totalResults[$i]['state'];
$outputDisplay .= '<ul id="results">';
$outputDisplay .='<li>'.$contactid.'</li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon();getContactsToForm();">'.$firstname.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$lastname.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$pcat.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$position.'</span></li>';
$outputDisplay .= '<li><span style="font-size:10px;cursor:pointer" onclick="openCon()">'.$state.'</span></li>';
$outputDisplay .= '</ul>';
//echo $myrowcount;
}
$outputDisplay .= "</div>";
return $outputDisplay;
}
function checkOr($searchArray){
if (in_array("OR",$searchArray)){
$orPos = array_search("OR", $searchArray);
//$surrVal =array();
//$surrVal = array(--$orPos, ++$orPos);
if (!empty($orPos)){
$surrVal = "";
$surrVal = --$orPos;
$orValArray = array();
array_push($orValArray,$searchArray[$surrVal]);
$surrVal = $orPos+2;
array_push($orValArray,$searchArray[$surrVal]);
return $orValArray;
}
}
}
The results I get are:
209AnisBakerDC
but from the console side:
Related
Before you judge me please know that I am not a big pro and just trying to learn how to do things here.
I am trying to create a mailing form with multiple attachments
form code
<div class="file-upload-wrapper">
<label class="file-field" data-max-files="6">
<input type="file" name="photos[]" multiple>
<span>Drag your files here or click to select your files <span>.jpg, .png and .pdf</span></span>
</label>
<div class="uploaded-files"></div>
</div>
js/jQuery code
var photos = [];
var data;
$(document).ready ( function() {
//Documnet Upload Script//
function fileUpload(obj){
var dropZone = obj.find('.file-field');
var fileInput = dropZone.find('input[type="file"]');
var filesBeen = obj.find('.uploaded-files');
var maxFiles = Number(dropZone.attr('data-max-files'));
function highlightDropZone(e){
if(e.type == 'dragover') dropZone.addClass('highlighted');
else dropZone.removeClass('highlighted');
e.preventDefault();
return false;
}
function filesDropped(e){
highlightDropZone(e);
var files = e.target.files || e.dataTransfer.files;
for(var i = 0, file; file = files[i]; i++) {
if(file.size <= 3000000 && (file.type == "application/pdf" || file.type == "image/jpg" || file.type == "image/jpeg" ||file.type == "image/png")) {
photos.push(file);
if (file.type == "application/pdf") {
var uploaded = filesBeen.prepend('<div><div><img src="images/adobe-acrobat-pdf-file-512.png"></div><span></span></div>');
uploaded.find('span').click(function () {
$(this).closest('div').animate({width: 0, height: 0}, 200, function () {
$(this).remove()
});
});
} else {
var fReader = new FileReader();
fReader.onloadend = (function(f){
return function() {
if (maxFiles > Number(filesBeen.children('div').length)) {
var uploaded = filesBeen.prepend('<div><div><img src="' + this.result + '"></div><p><span>' + f.name + '</span></p><span></span></div>');
uploaded.find('span').click(function () {
var me = $(this);
$(this).closest('div').animate({width: 0, height: 0}, 200, function () {
$(this).remove();
me.unbind('click');
});
});
}
}
})(file);
fReader.readAsDataURL(file);
}
}else {
window.alert("The size of the file is more than 3Mb or format is not supported.");
}
}
console.log(photos);
}
dropZone.get(0).addEventListener('dragover', highlightDropZone);
dropZone.get(0).addEventListener('dragleave', highlightDropZone);
dropZone.get(0).addEventListener('drop', filesDropped);
fileInput.get(0).addEventListener('change', filesDropped);
}
$('.file-upload-wrapper').each(function(){
new fileUpload($(this));
});
$('.submit-form').click(function(e) {
e.preventDefault();
// Store values in variables
var form = $('form[name="contact-form"]');
var ip = form.find('input[name=ip]');
var httpref = form.find('input[name=httpref]');
var httpagent = form.find('input[name=httpagent]');
var name = form.find('input[name=name]');
var email = form.find('input[name=email]');
var phone = form.find('input[name=phone]');
var message = form.find('textarea[name=message]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
var emails = form.find('input[name=email]').val();
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
if (validateEmail(emails)) {
// Organize data
data = new FormData();
data.append('ip', ip.val());
data.append('httpref', httpref.val());
data.append('httpagent', httpagent.val());
data.append('name', name.val());
data.append('email', email.val());
data.append('phone', phone.val());
data.append('message', message.val());
data.append('submitted', submitted.val());
data.append('visitor', visitor.val());
for(var i = 0; i < photos.length; i++){
data.append('file'+i, photos[i]);
}
var request = $.ajax({
type: "POST",
dataType: 'script',
url: "/includes/sendConatctform.php",
data: data,
cache: false,
contentType: false,
processData: false,
success: function (html) {
if (html == "true") {
form.find('.email-sent').fadeIn(500).delay(4000).fadeOut(500);
} else {
form.find('.email-error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function (jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
} else {
form.find('.email-results').fadeIn(500).delay(4000).fadeOut(500);
}
return false;
});
});
What I am trying to do is to receive the attachments in my PHP file for further proceedings.
php code
$message = "Date: $todayis \r\n";
$message .= "From: $name ($email) \r\n";
$message .= "Phone: $phone \r\n";
$message .= "Subject: $subject \r\n";
$message .= "Message: $userMessage \r\n";
$message .= "IP Address: $ip \r\n";
$message .= "Browser Info: $httpagent \r\n";
$message .= "Referral: $httpref \r\n";
foreach($_FILES['photos']['name'] as $file){
$message .= "Attachments:" .$file['filename'];
}
I have tried the suggestion that I have found here Send multiple file attachments to php file using ajax
but it did not help with my situation.
can you please advise?
All help is appreciated
Thank you in advance
Since in your php code you are iterating over $_FILES['photos'], then you should change in your js code this:
data.append('file'+i, photos[i]);
to
data.append('photos[]', photos[i]);
Update:
Also, in your php code change $file['filename'] here:
foreach($_FILES['photos']['name'] as $file){
$message .= "Attachments:" .$file['filename'];
}
to just $file:
foreach($_FILES['photos']['name'] as $file){
$message .= "Attachments:" . $file;
}
Here is my JavaScript and my PHP for a dynamic ajax search. I am trying to get data from the database and display it in my DOM as a string.
javascript
var searchBox = document.getElementById("searchBox");
var searchButton = document.getElementById("searchButton");
var search = getXmlHttpRequestObject();
searchBox.addEventListener("keyup", ajaxSearch);
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support our dynamic search");
}
}
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
function displaySuggestions(){
var ss = document.getElementById("searchSuggestion");
ss.innerHTML = '';
string = search.responseText;
ss.innerHTML = string;
}
function delay(functionName){
setTimeout(functionName, 100);
}
function setSearch(x){
document.getElementById("searchBox").value = x;
document.getElementById("searchSuggestion").innerHTML = "";
}
searchBox.addEventListener('click', ajaxSearch);
window.addEventListener('click', function(){
document.getElementById('searchSuggestion').innerHTML = '';
});
php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Products";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$searchValue = $_GET['search'];
if(isset($searchValue) && $searchValue != ''){
$search = addslashes($searchValue);
$statement = $conn->prepare("SELECT Name FROM Product WHERE Name LIKE('%" . $search . "%') ORDER BY
CASE WHEN Name like '" . $search . " %' THEN 0
WHEN Name like '" . $search . "%' THEN 1
WHEN Name like '% " . $search . "%' THEN 2
ELSE 3
END, Name");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($result);
echo $json;
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
What i want to know i how to get specific values from my response.
[{"Name":"iMac"},{"Name":"iPad 2"},{"Name":"iPhone 5"},{"Name":"iPhone 6"},{"Name":"iPod Touch"},{"Name":"iWatch"}]
For my search to work effectively i need it to display just the string of the product name and not the whole object.
Using a delay rather than the ajax callback is just shockingly prone to failure. Suppose your ajax call takes more than 100ms? It can totally happen. Similarly, why wait 100ms if your server is nice and fast and it finishes in 25?
Ditch the global search object, and change this:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
to
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject();
if (search) {
search.onreadystatechange = function() {
if (search.readyState == 4 && search.status == 200) {
displaySuggestions(JSON.parse(search.responseText));
}
};
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}
Then displaySuggestions receives an array:
function displaySuggestions(results) {
// Use standard array techniques on `results`, e.g., `results[0]` is the first,
// maybe loop while `index < results.length`, maybe use `results.forEach(...)`...
}
Or taking it further, let's add a level of convenience there:
var failed = false;
function getXmlHttpRequestObject(done, failed){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
if (!failed) {
alert("Your browser does not support our dynamic search");
failed = true;
}
return null;
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 {
if (done) {
done(xhr);
}
} else {
if (failed) {
failed(xhr);
}
}
}
};
return xhr;
}
Then:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject(function(xhr) {
displaySuggestions(JSON.parse(xhr.responseText));
});
if (search) {
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}
I'm trying to create a gameserver query for my website, and I want it to load the content, save it, and echo it later. However, it doesn't seem to be echoing. It selects the element by ID and is supposed to echo the content of the VAR.
Here's my HTML code:
<center><div id="cstrike-map"><i class="fa fa-refresh fa-spin"></i> <b>Please wait ...</b><br /></div>
JavaScript:
<script type="text/javascript">
var map = "";
var hostname = "";
var game = "";
var players = "";
$.post( "serverstats-cstrike/cstrike.php", { func: "getStats" }, function( data ) {
map = ( data.map );
hostname = ( data.hostname );
game = ( data.game );
players = ( data.players );
}, "json");
function echoMap(){
document.getElementByID("cstrike-map");
document.write("<h5>Map: " + map + "</h5>");
}
</script>
PHP files:
query.php
/* SOURCE ENGINE QUERY FUNCTION, requires the server ip:port */
function source_query($ip)
{
$cut = explode(":", $ip);
$HL2_address = $cut[0];
$HL2_port = $cut[1];
$HL2_command = "\377\377\377\377TSource Engine Query\0";
$HL2_socket = fsockopen("udp://".$HL2_address, $HL2_port, $errno, $errstr,3);
fwrite($HL2_socket, $HL2_command); $JunkHead = fread($HL2_socket,4);
$CheckStatus = socket_get_status($HL2_socket);
if($CheckStatus["unread_bytes"] == 0)
{
return 0;
}
$do = 1;
while($do)
{
$str = fread($HL2_socket,1);
$HL2_stats.= $str;
$status = socket_get_status($HL2_socket);
if($status["unread_bytes"] == 0)
{
$do = 0;
}
}
fclose($HL2_socket);
$x = 0;
while ($x <= strlen($HL2_stats))
{
$x++;
$result.= substr($HL2_stats, $x, 1);
}
$result = urlencode($result); // the output
return $result;
}
/* FORMAT SOURCE ENGINE QUERY (assumes the query's results were urlencode()'ed!) */
function format_source_query($string)
{
$string = str_replace('%07','',$string);
$string = str_replace("%00","|||",$string);
$sinfo = urldecode($string);
$sinfo = explode('|||',$sinfo);
$info['hostname'] = $sinfo[0];
$info['map'] = $sinfo[1];
$info['game'] = $sinfo[2];
if ($info['game'] == 'garrysmod') { $info['game'] = "Garry's Mod"; }
elseif ($info['game'] == 'cstrike') { $info['game'] = "Counter-Strike: Source"; }
elseif ($info['game'] == 'dod') { $info['game'] = "Day of Defeat: Source"; }
elseif ($info['game'] == 'tf') { $info['game'] = "Team Fortress 2"; }
$info['gamemode'] = $sinfo[3];
return $info;
}
cstrike.php
include('query.php');
$ip = 'play1.darkvoidsclan.com:27015';
$query = source_query($ip); // $ip MUST contain IP:PORT
$q = format_source_query($query);
$host = "<h5>Hostname: ".$q['hostname']."</h5>";
$map = "<h5>Map: ".$q['map']."</h5>";
$game = "<h5>Game: ".$q['game']."</h5>";
$players = "Unknown";
$stats = json_encode(array(
"map" => $map,
"game" => $game,
"hostname" => $host,
"players" => $players
));
You need to display the response in the $.post callback:
$.post( "serverstats-cstrike/cstrike.php", { func: "getStats" }, function( data ) {
$("#map").html(data.map);
$("#hostname").html(data.hostname);
$("#game").html(data.game);
$("#players").html(data.players);
}, "json");
You haven't shown your HTML, so I'm just making up IDs for the places where you want each of these things to show.
There are some things that I can't understand from your code, and echoMap() is a bit messed up... but assuming that your php is ok it seems you are not calling the echomap function when the post request is completed.
Add echoMap() right after players = ( data.players );
If the div id you want to modify is 'cstrike-map' you could use jQuery:
Change the JS echoMap to this
function echoMap(){
$("#cstrike-map").html("<h5>Map: " + map + "</h5>");
}
So what I did was I had to echo the content that I needed into the PHP file, then grab the HTML content and use it.
That seemed to be the most powerful and easiest way to do what I wanted to do in the OP.
<script type="text/javascript">
$(document).ready(function(){
$.post("stats/query.cstrike.php", {},
function (data) {
$('#serverstats-wrapper-cstrike').html (data);
$('#serverstats-loading-cstrike').hide();
$('#serverstats-wrapper-cstrike').show ("slow");
});
});
</script>
PHP
<?php
include 'query.php';
$query = new query;
$address = "play1.darkvoidsclan.com";
$port = 27015;
if(fsockopen($address, $port, $num, $error, 5)) {
$server = $query->query_source($address . ":" . $port);
echo '<strong><h4 style="color:green">Server is online.</h4></strong>';
if ($server['vac'] = 1){
$server['vac'] = '<img src="../../images/famfamfam/icons/tick.png">';
} else {
$server['vac'] = '<img src="../../images/famfamfam/icons/cross.png">';
}
echo '<b>Map: </b>'.$server['map'].'<br />';
echo '<b>Players: </b>'.$server['players'].'/'.$server['playersmax'].' with '.$server['bots'].' bot(s)<br />';
echo '<b>VAC Secure: </b> '.$server['vac'].'<br />';
echo '<br />';
} else {
echo '<strong><h4 style="color:red">Server is offline.</h4></strong>';
die();
}
?>
what i am trying to do is getting data from database and tick the checkbox according to that but i did not success any idea?
i am not sure what is the problem
JS code
function editPer(role_pk) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4) {
var jsonObj = JSON.parse(xmlHttp.responseText);
document.getElementById("role_pk1").value = jsonObj.pk;
document.getElementById("role_name1").value = jsonObj.name;
for (var i = 1; i < 29; i++){
if (jsonObj.permission_fk+i != null)
document.getElementById("per"+i).checked = true;
else
document.getElementById("per"+i).checked = false;
}
}
};
xmlHttp.open("GET", "classes/controller/RoleController.php?action=getp&pk=" + role_pk, true);
xmlHttp.send();
/*
* Reset error message
* Show update role button
*/
resetErrorMessage("roleMessage");
showUpdateRoleButton();
$("#perModalDetail").modal('show');
};
PHP code RoleController.php
}else if ($action == "getp") {
if (isset($pk)) {
/*
* Select single Role value
*/
$itemArray = $roleDao->getp($pk);
if (count($itemArray) == 0) {
echo NULL;
} else {
echo json_encode($itemArray[0]);
}
}
PHP code in the class roleDao
public function getp($pk) {
$query = "SELECT pk, name FROM roles WHERE pk=".$pk.";";
$result = mysql_query($query, $this->dbconn);
$itemArray = array();
while ($row = mysql_fetch_row($result)) {
$item = array("pk" => $row[0], "name" => $row[1]);
array_push($itemArray, $item);
}
$query = "SELECT permission_fk FROM role_permission WHERE role_fk=".$pk.";";
$result = mysql_query($query, $this->dbconn);
$i=1;
while ($row = mysql_fetch_row($result)) {
$item = array("permission_fk$i" => $row[0]);
$i++;
array_push($itemArray, $item);
}
//print $itemArray;
return $itemArray;
}
I m trying to save popup windows data in to database.but its throw error when i m trying pass data in queryString.Its just write "error".I dont know why its not call the update_clientstatus.php
Javscript :
function SaveNotes()
{
var notecontent = $("#txtPopNotes").val();
lookup(notecontent, globalNoteId);
overlay.appendTo(document.body).remove();
return false;
}
function lookup(inputstr, eleid) {
var inputString = inputstr;
// var row = parseFloat(eleId.substring(eleId.indexOf('_') + 1))+1;
var noteId = '#noteContent_' + eleid;
var editLinkId = '#editlink_' + eleid;
var saveLinkId = '#savelink_' + eleid;
var cancelLinkId = '#cancellink_' + eleid;
var txtBoxId = '#txt_' + eleid;
// var eleId = ele.id;
$.post("update_clientstatus.php", {queryString: ""+inputString+"", id: ""+eleid+"" }, function(data){
if(data=="success") {
alert("Status updated successfully");
$('.popup').hide();
var noteId = '#noteContent_' + globalNoteId;
$(noteId).html(inputstr);
$('.message').html('Status Updated successfully');
}
else
{
**document.write('error');**
}
});
} // lookup
PHP code(update_clientstatus.php)
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
}
try this
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
if ($query ) {
echo "success";
} else {
echo "error";
}
} else {
echo "error";
}