My problem now when I click on the picture on my page, for the first time it will display. But for the second time it will display fail. This process will start by sending the data to ajax, then ajax(prosess.js) will send it to the php page(process1.php).
When I remove the code in blockquote ($query = "SELECT ...") it will run, but if not, it will display fail.
process1.php
<?php
include 'session.php';
include 'connection.php';
if(isset($_POST['dataS'])) {
$table = $_POST['table'];
$concat = "";
$serial = $_POST['dataS'];
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if($row) {
$prodName = $row['prodName'];
$quanProd = 1;
$priceProd = $_POST['total'] + $row['salePrice'];
if($table == "") {
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
}
else{
$DOM = new DOMDocument;
$DOM->loadHTML($table);
$items = $DOM->getElementsByTagName('tr');
$check = 0;
$check_one = 0;
$y=0;
function tdrows($elements,$check,$serial,$prodName,$y) {
$quantity="";
$item = "";
$price = "";
$delete = "";
$x = 0;
foreach($elements as $element) {
if($x == 0)
$delete = $element->nodeValue;
else if($x == 1)
$item = $element->nodeValue;
else if($x == 2)
$quantity = $element->nodeValue;
else if($x == 3)
$price = $element->nodeValue;
$x++;
}
**$query = 'SELECT prodName FROM product WHERE prodName = "$item"';
$search = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($search);
$s = $row['prodName'];**
if($prodName == $s) {
$quantity++;
$check = 1;
}
else {
$check = 0;
}
return $check;
}
foreach ($items as $node) {
$check = tdrows($node->childNodes,$check,$serial,$prodName,$y);
$y++;
}
}
$priceProd = number_format((float)$priceProd, 2, '.', '');
echo json_encode (
array ( //this array is used to send the data back to ajax.
"success" => "1",
"concat" => $concat,
"quantity" => $quanProd,
"price" => $priceProd,
)
);
}
else {
echo json_encode (
array ( //this array is used to send the data back to ajax.
"success" => "0",
)
);
}
}
?>
process.js
$(document).ready(
function() {
$("body").on("click","#product .add",
function(e) {
var total = document.getElementById("total").value;
var table = document.getElementById('table-list').innerHTML;
table = (table.trim) ? table.trim() : table.replace(/^\s+/,'');
var serial = $(this).attr('id');
var totalQ = document.getElementById("totalQ").value;
if(total == "")
total = 0;
else
total = parseFloat(total);
if(totalQ == "")
totalQ = 0;
else
totalQ = parseInt(totalQ);
var dataS = serial;
e.preventDefault();
$.ajax({
type : "POST",
url : "process1.php",
crossDomain: true,
data : {dataS : dataS, table : table, total : total},
dataType : 'json',
})
.done(function(html) {
if(html.success == 1) {
console.log('done: %o', html);
$("#table-list").html(html.concat).show();
document.getElementById('totalQuantity').innerHTML = html.quantity;
document.getElementById("total").value = html.price;
document.getElementById("payment").value = html.price;
document.getElementById('totalQ').value = html.quantity;
document.getElementById('title').innerHTML = html.price;
document.getElementById('input').value='';
$("#input").focus();
}
else {
alert("Wrong serial number!");
document.getElementById('input').value='';
$("#input").focus();
}
})
.fail(function(html) {
console.info('fail: %o', html);
alert("fail");
});
return false;
});
});
connection.php
<?php
$conn = mysqli_connect('localhost','root','','rds');
?>
your query is wrong:try this
$query = "SELECT prodName FROM product WHERE prodName = '".$item."'";
According to your pictures, your problem is that your database connection isn't correct. When you execute the first request it won't do any database interaction (because off the blocknotes). The second request you will send table data, which will perform a query. So the first request will succeed, while the second request will give you an error on your mysqli ($conn) object.
if($table == "") {
//Database interaction
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
}
else{
//No database interaction because of the blocknotes
$DOM = new DOMDocument;
$DOM->loadHTML($table);
$items = $DOM->getElementsByTagName('tr');
$check = 0;
$check_one = 0;
$y=0;
function tdrows($elements,$check,$serial,$prodName,$y) {
$quantity="";
$item = "";
$price = "";
$delete = "";
$x = 0;
foreach($elements as $element) {
if($x == 0)
$delete = $element->nodeValue;
else if($x == 1)
$item = $element->nodeValue;
else if($x == 2)
$quantity = $element->nodeValue;
else if($x == 3)
$price = $element->nodeValue;
$x++;
}
**$query = 'SELECT prodName FROM product WHERE prodName = "$item"';
$search = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($search);
$s = $row['prodName'];**
if($prodName == $s) {
$quantity++;
$check = 1;
}
else {
$check = 0;
}
return $check;
}
foreach ($items as $node) {
$check = tdrows($node->childNodes,$check,$serial,$prodName,$y);
$y++;
}
}
Check your the username, password and database name. I'm pretty sure you used something wrong here. As mentioned in your connection.php file you don't use a password. Are you sure the user root doens't have a password? Can you access the database with a MySQL administration tool like phpMyAdmin?
Related
I'm trying to display a json array with contents from my database but when their is accents in the database the json array doesn't want to be displayed, their is my code:
<?php
include 'connect.php';
header('Content-Type: text/plain; charset=UTF-8') ;
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = $by;
$response["type"] = $type;
$response["lesson"] = $lesson;
$response["description"] = $description;
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = $question;
}
}
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
Thank you for your answers
I found a good code but thank you for your help,
<?php
include 'connect.php';
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
function utf8_encode_all(&$value)
{
if (is_string($value)) return utf8_encode($value);
if (!is_array($value)) return $value;
$ret = array();
foreach($dat as $i=>$d) $ret[$i] = utf8_encode_all($d);
return $ret;
}
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = utf8_encode_all($by);
$response["type"] = utf8_encode_all($type);
$response["lesson"] = utf8_encode_all($lesson);
$response["description"] = utf8_encode_all($description);
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = utf8_encode_all($question);
}
}
}
$array = array_map('htmlentities',$response);
$json = html_entity_decode(json_encode($array));
echo $json;
?>
How come autocomplete doesnt work when I got json data that has items in it? I can se that it is becoming a list, but it is not filling with names.
Example of my json data: http://nettport.com/no/stram/search.php?term=e
<script>
$(function() {
$( "#inp_meal_a_0" ).autocomplete({
source: 'search.php'
});
$('#inp_meal_a_0').on('autocompleteselect', function (e, ui) {
var val = $('#inp_size_a_0').val();
var energy = ui.item.energy;
var proteins = ui.item.proteins;
var carbohydrates = ui.item.carbohydrates;
var fat = ui.item.fat;
$("#inp_energy_a_0").val((energy*val)/100);
$("#inp_proteins_a_0").val((proteins*val)/100);
$("#inp_carbs_a_0").val((carbohydrates*val)/100);
$("#inp_fat_a_0").val((fat*val)/100);
});
});
</script>
Search.php
<?php
header('Content-type: text/html; charset=windows-1252;');
// Make a MySQL Connection
$host = $_SERVER['HTTP_HOST'];
if($host == "127.1.1.0"){
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("n") or die(mysql_error());
}
// Quote smart
function quote_smart($value){
// Stripslashes
if (get_magic_quotes_gpc() && !is_null($value) ) {
$value = stripslashes($value);
}
//Change decimal values from , to . if applicable
if( is_numeric($value) && strpos($value,',') !== false ){
$value = str_replace(',','.',$value);
}
if( is_null($value) ){
$value = 'NULL';
}
// Quote if not integer or null
elseif (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
if(isset($_GET['term']) && $_GET['term'] != ''){
$term = $_GET['term'];
$term = strip_tags(stripslashes($term));
$term = trim($term);
$term = strtolower($term);
$term = $term . "%";
$part_mysql = quote_smart($term);
//get matched data from skills table
$x = 0;
$query = "SELECT cc_id, cc_food_name, cc_manufactor_name, cc_serving_size, cc_serving_mesurment, cc_energy, cc_proteins, cc_carbohydrates, cc_fat FROM stram_calorie_calculation WHERE cc_food_name LIKE $part_mysql";
$r = mysql_query($query);
while ($row = mysql_fetch_array($r, MYSQL_NUM)) {
$get_cc_id = $row[0];
$get_cc_food_name = $row[1];
$get_cc_manufactor_name = $row[2];
$get_cc_serving_size = $row[3];
$get_cc_serving_mesurment = $row[4];
$get_cc_energy = $row[5];
$get_cc_proteins = $row[6];
$get_cc_carbohydrates = $row[7];
$get_cc_fat = $row[8];
if($get_cc_food_name == ""){
$result = mysql_query("DELETE FROM stram_calorie_calculation WHERE cc_id='$get_cc_id'") or die(mysql_error());
}
$data[$x] = array('food_name' => $get_cc_food_name, 'energy' => $get_cc_energy, 'proteins' => $get_cc_proteins, 'carbohydrates' => $get_cc_carbohydrates, 'fat' => $get_cc_fat);
//$data[$x] = $get_cc_food_name;
$x++;
}
//return json data
echo json_encode($data);
}
?>
I want to make an ajax request on click with jquery, but it's not working:
This is what I have:
The button:
$photos_box .= '<a id="' . $imgID . '" class="like_button">' . $like . '</a>';
Maybe there's an error in the script:
// Like function
$('.like_button').click(function() {
$(this).toggleClass('liked');
var status = '';
if ($(this).hasClass('liked')) {
status = 'like';
$(this).html('Ya no me gusta');
console.log('like_works');
} else {
status = 'unlike';
$(this).html('Me gusta');
console.log('unlike_works');
}
var data = {
img_id : this.id,
sta : status
};
$.ajax({
type : 'POST',
url : '/includes/like.php',
data : data
}).done(function(reslike) {
if (reslike == 1) console.log('ajax_works');
});
});
And this is the like.php file:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
sec_session_start();
// User id
if (login_check($mysqli) == true) {
$user_id = $_SESSION['user_id'];
}
$img_id = $_POST['img_id'];
$status = $_POST['sta'];
$stmt = $mysqli->prepare("SELECT * FROM img_likes WHERE img_id = ? AND user_id = ?");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();
$usr_likes = $result->num_rows;
if ($status == 'like') {
if ($usr_likes == 0) {
$stmt->close();
$stmt = $mysqli->prepare("INSERT INTO img_likes (img_id, user_id) VALUES(?, ?)");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
}
}
else if ($status == 'unlike') {
if ($usr_likes != 0) {
$stmt->close();
$stmt = $mysqli->prepare("DELETE FROM img_likes WHERE img_id = ? AND user_id = ?");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
}
}
}
At last! Thanks to everyone. Hope my code help someone.
Check the URL in your ajax request, I'm not certain but I don't think '../includes/like.php' is a valid URL I think you actually have to give it a valid server URL like "http://example.com/includes/like.php"
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;
}
JS file this deletes by button the Event
buttons: {
save : function() {
calEvent.start = new Date(startField.val());
calEvent.end = new Date(endField.val());
calEvent.title = titleField.val();
calEvent.body = bodyField.val();
$calendar.weekCalendar("updateEvent", calEvent);
$dialogContent.dialog("close");
},
"delete" : function() {
calEvent.id = id;
$.post("events.php?action=del&id="+calEvent.id);
$calendar.weekCalendar("removeEvent", calEvent.id);
$dialogContent.dialog("close");
},
cancel : function() {
$dialogContent.dialog("close");
}
}
}).show();
PHP File
if($action == 'save')
{
$title = $_REQUEST['title'];
$body = $_REQUEST['body'];
$start_time = (int)$_REQUEST['start'];
$start_time = $start_time + 60*60;
$end_time = (int)$_REQUEST['end'];
$end_time = $end_time + 60*60;
$start = date('c',$start_time);
$end = date('c',$end_time);
$sql = "INSERT INTO meeting_rooms_calendar(title,body,start,end) VALUES ('$title','$body','$start','$end')";
$result = mysql_query($sql, $link);
}
elseif ($action == 'del')
{
$del = "DELETE FROM `agenda`.`meeting_rooms_calendar` WHERE `meeting_rooms_calendar`.`id` = VALUES ('$id')";
$result = mysql_query($del, $link);
}
else
{
$sql= "SELECT id, title, body,
DATE_FORMAT(start, '%Y-%m-%dT%H:%i' ) AS startTime, DATE_FORMAT(end, '%Y-%m-%dT%H:%i' ) AS endTime
FROM meeting_rooms_calendar
ORDER BY start DESC";
$result = mysql_query($sql, $link);
This wont delete from database, what am I doing wrong to delete it from database?