I am trying to work out why my alert in the 'function processResponse(data)' part of the code, is not being displayed. I have tried various return; options, but still, refuses to display.
I would be grateful if someone could point out my error. Many thanks.
PS. I am aware of security issues in the code posted such as mysql_escape_string, but all security issues will be inserted before the site goes live.
jQuery code
<script type="text/javascript">
$(function() {
$('#srcsubmit').click(function(e) {
e.preventDefault();
if ($('#srcBox').val() == '') {
notif({
type: "error",
msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click anywhere to close</p>",
height: 99,
multiline: true,
position: "middle,center",
fade: true,
timeout: 3000
});
return false;
}
$("#submit").prop("disabled", true);
$("#submit2").prop("disabled", true);
$("#submit3").prop("disabled", true);
var value = $('#srcBox').val();
var dept = '<?php echo $_GET['dept ']; ?>';
var qString = 'sub=' + encodeURIComponent(value) + '&dept=' + encodeURIComponent(dept);
$.post('sub_db_handler.php', qString, processResponse);
});
function processResponse(data) {
if (data === 'true') {
alert('That box is not on the system'); <--- this is the problem
return;
}
$('#srcBoxRslt').val(data);
};
});
</script>
PHP backend
<?php session_start(); ?>
<?php
$con = mysql_connect("localhost","root","");
if(!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("sample", $con);
$dept = trim($_POST['dept']);
$custref = trim($_POST['sub']);
$result = mysql_query("SELECT * FROM boxes WHERE custref = '".$custref."'");
$found = mysql_num_rows($result);
if ($found == 0)
{
echo trim('true');
} else {
$query = "SELECT * FROM boxes WHERE department = '".$dept."' AND status = 1 AND custref = '".$custref."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
$r = $row['custref'];
$str = json_encode($r);
echo trim($str, '"');
}
?>
The data value is not equal to true because of extra space to get rid of extra use .trim()
Related
im successfuly inserted data to my db with ajax.. but somehow it does not pop up my success alert message. here is a sample of my jquery code.
$('button[name="submitmsgd"]').click(function(e){
var categorysupAr = [];
var unitsgdAr=[];
var idsgdAr=[];
var idsgdlength= $("input[name='idsgd[]']").val().length;
var namesgdAr= [];
var namesgdlength= $("input[name='namesgd[]']").val().length;
var detailsgdAr = [];
var qtysgdAr = [];
var pricesgdAr = [];
var totalsAr = [];
var datefield= $("input[name='datetime']").val();
$("select[name='categorysup[]']").each(function(){
categorysupAr.push(this.value);
});
$("select[name='unitsgd[]']").each(function(){
unitsgdAr.push(this.value);
});
$("input[name='idsgd[]']").each(function(){
idsgdAr.push(this.value);
});
$("input[name='namesgd[]']").each(function(){
namesgdAr.push(this.value);
});
$("textarea[name='detailsgd[]']").each(function(){
detailsgdAr.push(this.value);
});
$("input[name='qtysgd[]']").each(function(){
qtysgdAr.push(this.value);
});
$("input[name='pricesgd[]']").each(function(){
pricesgdAr.push(this.value);
});
$("input[name='totals[]']").each(function(){
totalsAr.push(this.value);
});
if ($.inArray("defaultc", categorysupAr)>-1){
e.preventDefault();
alert("Please choose the right category in all fields");
}
else if ($.inArray("defaultu", unitsgdAr)>-1){
e.preventDefault();
alert("Please choose the right unit in all fields");
}
else if ($.inArray("", idsgdAr)>-1||idsgdlength<=2){
e.preventDefault();
alert ("ID can't be empty, and must be more than 2 characters in all fields");
}
else if ($.inArray("", namesgdAr)>-1||namesgdlength<=2){
e.preventDefault();
alert ("Name can't be empty, and must be more than 2 characters");
}
else if ($.inArray("", totalsAr)>-1||$.inArray("0", totalsAr)>-1){
e.preventDefault();
alert ("Please make sure all quantity and all prices are filled with correct format(Only number allowed)");
}else{
$.ajax({
url: "include/insertmsgd.php",
method: "POST",
data:{category:categorysupAr, unitsgd:unitsgdAr, idsgd:idsgdAr, namesgd:namesgdAr, detailsgd:detailsgdAr, qtysgd:qtysgdAr, pricesgd:pricesgdAr, totals:totalsAr, datefield:datefield},
success: function (data) {
alert(data);
}
});
}
});
here is my php code:
<?php
include "myconfiguration.php";
if (isset($_POST["idsgd"])) {
$idsgd = $_POST["idsgd"];
$category = $_POST["category"];
$unitsgd = $_POST["unitsgd"];
$namesgd = $_POST["namesgd"];
$detailsgd = $_POST["detailsgd"];
$qtysgd = $_POST["qtysgd"];
$pricesgd = $_POST["pricesgd"];
$totals = $_POST["totals"];
$date = date('Y-m-d H:i:s', strtotime($_POST["datefield"]));
for($index=0; $index<count($idsgd); $index++) {
$idsgd_unstring = mysqli_real_escape_string($conn, $idsgd[$index]);
$category_unstring = mysqli_real_escape_string($conn, $category[$index]);
$unitsgd_unstring = mysqli_real_escape_string($conn, $unitsgd[$index]);
$namesgd_unstring = mysqli_real_escape_string($conn, $namesgd[$index]);
$detailsgd_unstring = mysqli_real_escape_string($conn, $detailsgd[$index]);
$qtysgd_unstring = mysqli_real_escape_string($conn, $qtysgd[$index]);
$pricesgd_unstring = mysqli_real_escape_string($conn, $pricesgd[$index]);
$totals_unstring = mysqli_real_escape_string($conn, $totals[$index]);
$query= '
INSERT INTO msgeneralgoods
VALUES("'.$idsgd_unstring.'", "'.$category_unstring.'", "'.$unitsgd_unstring.'", "'. $namesgd_unstring.'",
"'.$detailsgd_unstring.'", "'.$qtysgd_unstring.'", "'.$pricesgd_unstring.'", "'.$totals_unstring.'", "'.$date.'");
';
mysqli_query($conn, $query);
}
if (mysqli_query($conn, $query)) {
echo '<script language="javascript">';
echo 'alert("Data Inserted")';
echo '</script>';
} else {
echo '<script language="javascript">';
echo 'alert("Error")';
echo '</script>';
}
}
?>
i did try this code for my if condition inside my php page
if (mysqli_query($conn, $query)) {
echo 'Data Saved';
} else {
echo 'Error'
}
but still no alert message.... im very new to ajax, can some1 please tell me what did i do wrong here?
add error to the ajax call to return error if there is one
$.ajax({
url: "include/insertmsgd.php",
method: "POST",
data:{category:categorysupAr, unitsgd:unitsgdAr, idsgd:idsgdAr, namesgd:namesgdAr, detailsgd:detailsgdAr, qtysgd:qtysgdAr, pricesgd:pricesgdAr, totals:totalsAr, datefield:datefield},
success: function (data) {
alert(data);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
after thorough search in console and googling, i found out that my ajax call was canceled because my save button is
button type="submit"
so i change it to
button type="button"
that way i can see my alert pop up..
hope this help to whoever have the same problem as me
I make this jquery to call a php file via post. I put a console.log to see the return of the Ajax. At moment return 00.
I'm not sure what it is the problem?
The code is:
$('input[type="submit"]').click(function(event){
event.preventDefault();
// Get the value of the input fields
var inputvalue = $(this).attr("value");
$.ajax({
url:"updateEstado2.php",
type:"POST",
data:{"codigo": inputvalue},
dataType:"text",
success:function(data){
console.log(data);
alert(inputvalue);
}
});
});
The PHP code:
<?php
session_start();
if(isset($_SESSION['username']) and $_SESSION['username'] != ''){
include("db_tools.php");
$conn = dbConnect("localhost", "5432", "dbname", "dbuser", "dbpass");
$estado = $_POST["estado"];
$codigo = $_POST["codigo"];
$query = "UPDATE produccion.ma_producto SET estado={$estado} WHERE codigo={$codigo}";
$result = pg_query($conn, $query);
if ($result == TRUE) {
header('Location: produccio.php');
} else {
echo "Error updating record: " . pg_last_error($conn);
}
pg_close($conn);
} else{
?><p>La sessió no està activa, si us plau ingresa aquí</p>
The alert window show the value of the variable correctly but the console.log show 0. I do not understand well...
Please Could you help me.
Please edit statement after if condition.
if ($result == TRUE) {
echo 'Done';
} else {
echo "Error updating record: " . pg_last_error($conn);
}
I want to insert a "remove" button in each of these divs, so that the database's row and the div can be deleted using the remove button.
Number of divs vary according to the number of rows in the database.
It should appear as follows,
Showing data works just fine. But, delete (remove button) doesn't work.
PHP
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM users_table ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['user_id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
</div>';
if (isset($_GET['removeButton'])) {
deleteUser($connection, $userID);
}
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
As the discussion from the comment, The following codes given.
Updated HTML:
<input type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
$.post("page.php", { userID : userID}, function(result){
if(result == "Success") window.location.href = "main.php";
else alert(result);
});
});
page.php
//need the database connection
$userID = $_POST['userID'];
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
echo 'Success';
} else {
echo "Error! ";
}
If you want to remove the total div as well with the database field then use:
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
var __this = $(this);
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
If you want to pass your $userID in each input then use:
<input data-userid = <?php echo $userID;?> type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript
$(".removeBtn").on("click", function(){
var __this = $(this);
var userID = __this.attr("data-userid");
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
This is just an answer of your question, but you have to use this as you want. This may help you, try and let me know what happens.
The remove button doesnt work because you never get into deleteUser() method.
You cant just write
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
as it was inside a form. For it to trigger, write it like this:
<form method="GET">
<input type = "submit" name = "removeButton" value = "<?php echo $userID;?>">
</form>
Then, when calling
deleteUser($connection, $_GET['removeButton']);
Hope this helps.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM maps ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
</div>';
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
if (isset($_GET['removeButton']))
{
deleteUser($connection, $_GET['removeButton']);
}
currentUsers($connection);
?>
I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}
I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.
Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.
Index.php
<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");
$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";
$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);
$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn);
?>
Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.
Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
And as final the Javascript
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
note: HTML is being returned from the "page" class called inside Index.php
How do i not let everything get called twice?
Thank you,
EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php
AutoComplete.PHP
Please explain what should be in the file and why. I am clueless.
Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:
if(!isset($_REQUEST['calledByAjax']))
{
$IndexPage = new page();
echo $IndexPage->render();
}
and in your Ajax call:
data: { query: query_value, calledByAjax: 'true' },
Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.
First thing (this is a sample, not tested yet)
autocomplete.php
<?php
$search_string = $_POST['query'];
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
}
echo($output);
?>
autocomplete.js
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "autocomplete.php", //Here change the script for a separated file
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
} else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
search(); // call the function without setTimeout
}
});
});
Have luck :)