On click button, it suppose to execute a query in the php file either update or delete depending on the button clicked. But I think there's no value passed to the variable $status inside php file when buttons are clicked, thus not executing sql queries.
PHP
<?php
$status = $_GET["status"];
if ($status == "update") {
$conn = mysqli_connect('localhost', 'root','root', 'realestate');
$id=$_GET["id"];
$first=$_GET["firstname"];
$mid=$_GET["middlename"];
$last=$_GET["lastname"];
$add=$_GET["address"];
$gend=$_GET["gender"];
$cont=$_GET["contact"];
$first=trim($first);
$mid=trim($mid);
$last=trim($last);
$add=trim($add);
$gend=trim($gend);
$cont=trim($cont);
$result=mysqli_query($conn, "UPDATE agents SET firstname='$first', middlename='$mid', lastname='$last', address='$add', gender='$gend', contact='$cont' WHERE id=$id");
}
if ($status == "delete") {
$conn = mysqli_connect('localhost', 'root','root', 'realestate');
$id=$_GET["id"];
$result=mysqli_query($conn, "DELETE FROM agents WHERE id=$id");
}
?>
JavaScript
<script type="text/javascript">
data();
function data() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","update.php?status=disp", false);
xmlhttp.send(null);
document.getElementById("data").innerHTML = xmlhttp.responseText;
}
function bb(b) {
var firstid="txtfirst"+b;
var firstname = document.getElementById(firstid).value;
var midid="txtmid"+b;
var middlename = document.getElementById(midid).value;
var lastid="txtlast"+b;
var lastname = document.getElementById(lastid).value;
var addid="txtadd"+b;
var address = document.getElementById(addid).value;
var gendid="txtgend"+b;
var gender = document.getElementById(gendid).value;
var contid="txtcont"+b;
var contact = document.getElementById(contid).value;
update_value(b,firstname,middlename,lastname,address,gender,contact);
document.getElementById(b).style.visibility="visible";
document.getElementById("update"+b).style.visibility="hidden";
document.getElementById("firstname"+b).innerHTML=firstname;
document.getElementById("middlename"+b).innerHTML=middlename;
document.getElementById("lastname"+b).innerHTML=lastname;
document.getElementById("address"+b).innerHTML=address;
document.getElementById("gender"+b).innerHTML=gender;
document.getElementById("contact"+b).innerHTML=contact;
}
function update_value(id,firstname,middlename,lastname,address,gender,contact) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","update.php?id="+id+"&firstname="+firstname+"&middlename="+middlename+"&lastname="+lastname+"&address="+address+"&gender="+gender+"&contact="+contact+"&status=update",false);
xmlhttp.send(null);
}
function delete1(id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","update.php?id="+id+"&status=delete", false);
xmlhttp.send(null);
data();
}
</script>
You have a few issues here. First, I would advise you look into the DRY principle to help you avoid easy to miss problems like not including a status variable in your request.
If you look at your JavaScript you will notice that you are making several requests to the same page, and using copy-paste code to do so. This is a great place to further abstract your code. I would probably use something similar to the following.
Secondly, your PHP script is vulnerable to SQL Injection. How to combat this is well explained here. I can't say for sure that this is your problem, but if you are using a name like O'Reilly it would prevent your script from working. I don't see any other obvious place where your script would go wrong. If anything shows up in your PHP error log, I might be able to help more.
<script>
//Type isn't needed, browsers assume javascript
function httpRequest(method, url, parameters) {
// Build a query string, this could be improved but it works for your current use case.
// It assumes that parameters is an object and does not work for arrays
var query = "";
Object.keys(parameters).forEach(function(key) {
query += encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]) + "&";
});
var xmlhttp = new XMLHttpRequest();
//If possible you should switch to async requests as well.
xmlhttp.open(method, url + "?" + query, false);
xmlhttp.send(); //No need to pass null
return xmlhttp.responseText;
}
function updateRequest(parameters) {
return httpRequest("GET", "update.php", parameters);
}
function data() {
document.getElementById("data").innerHTML = updateRequest({status: "disp"});
}
//bb function removed as it isn't relevant to my point here
function update_value(id,firstname,middlename,lastname,address,gender,contact) {
updateRequest({
status: "update",
id: id, //If you are using a recent browser this can be changed to just id, firstname, ...
firstname: firstname,
middlename: middlename,
lastname: lastname,
address: address,
gender: gender,
contact: contact,
});
}
function delete1(id) {
updateRequest({
status: "delete",
id: id,
});
data();
}
</script>
Related
I have been trying to insert data into a table in a mysql database. This data was sent with ajax using the POST method. However, when I try to insert it into the database nothing happens.
So here is the javascript function the sends the data to the php file.
addToCart: function(itemId,userId){
let request = new XMLHttpRequest();
request.open("POST", "../E-CommerceCore/addToCart.php?
itemId="+ itemId + "?userId=" + userId, true);
request.send();
},
Here is where it is being used. This is nested in a bigger function so thats where the book[i].Id comes from.
document.getElementById('add-to-cart').onclick = function(){
cartFunctions.addToCart(book[i].Id, '1');
};
So this takes an item id and a user id and stores them in a php variables here.
class Cart
{
public function addToCart($item,$user){
include 'connect.php';
$query = $bookStore->prepare("INSERT INTO cart SET item_Id=?, user_Id=?");
$query->execute([$item,$user]);
}
}
$cartManager = Cart();
$itemId = $_REQUEST["itemId"];
$userId = $_REQUEST["userId"];
$cartManager->addToCart("$itemId","$userId");
This php file then runs the addToCart function which should insert it into the table. This is where I run into the problem because not data is inserted to the database when the user clicks the button. I use the connect.php file for another controller that selects from a different table in the same database, if that is an issue, and yes I have checked to make sure that the connection to the database is good. Any insight would be immensely appreciated. Please no jQuery solutions. Thank you for you time and effort.
request.open("POST", "../E-CommerceCore/addToCart.php? itemId="+ itemId + "?userId=" + userId, true); You are sending the parameters as GET with the url and you have another mistake since you used another ? to separate the 2 parameters . Please follow this link to send your data: Send POST data using XMLHttpRequest
var http = new XMLHttpRequest();
var url = "path_to_file.php";
var params = "itemId="+ itemId + "&userId=" + userId; //Please note that the 2 params are separated by an **&** not a **?** as in your question
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
Also the quotes here are unnecessary when passing parameters:
$cartManager->addToCart("$itemId","$userId");
If it is possible try to var_dump($_REQUEST) before calling the addToCart method to make sure that parameters have been successfully sent through the javascript request.
Now regarding the sql query you have to update the class and use bindParam and afterwards call the execute. I have updated your php code as follows:
class Cart{
public function addToCart($item,$user){
include 'connect.php';
$query = $bookStore->prepare("INSERT INTO cart SET item_Id=:item_id, user_Id=:user_id");
$query->bindParam(':item_id', $item);
$query->bindParam(':user_id', $user);
$query->execute();
}
}
$cartManager = new Cart();
$itemId = $_REQUEST["itemId"];
$userId = $_REQUEST["userId"];
$cartManager->addToCart($itemId, $userId);
For more reference regarding prepared statements you can have a look at this: http://php.net/manual/en/pdo.prepared-statements.php
I need a help with a singleton class. I`m creating a wordpress plugin, and need to have live notifications from server. For that I used AJAX long polling and my code looks like this.
This is a php code used for serving AJAX request and for LOG class which is singleton and called from many different places in project
if (isset($_GET['log']) && $_GET['log'] == 'true')
{
$response = array();
$response['msg'] = SI_log::get_instance()->get_message();
$response['type'] = 'something';
echo json_encode($response);
}
class SI_log{
private $log_messages = array();
private static $instance = NULL;
private $log_file;
public static function get_instance()
{
if (static::$instance === NULL) {
static::$instance = new static();
}
return static::$instance;
}
public function add_message( $message, $type )
{
array_push($this -> log_messages, $message);
}
public function get_message()
{
return end($this->log_messages);
}}?>
This is javascript for retrieving notifications and its a part of admin section in the wordpress.
<script type="text/javascript" charset="utf-8">
function waitForMsg(){
setTimeout(waitForMsg,5000);
document.getElementById("alerts").childNodes = new Array();
var request = new XMLHttpRequest();
request.open('GET', '<?php echo get_site_url() . '/wp-content/plugins/si/admin/c-si-log.php?log=true'?>', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
alert(resp);
var json = eval('('+resp+ ')');
document.getElementById("alerts").innerHTML= json['type'] +"<hr>";
if (json['type'] == 'WARNING'){
var html_element = '<div class="alert-message warning" id = "alert_warning"><div class="box-icon"></div><p>'+json['msg']+'</p></div>';
}
if (json['type'] == 'INFO'){
var html_element = '<div class="alert-message info" id = "alert_info"><div class="box-icon"></div><p>'+json['msg']+'</p></div>';
}
if (json['type'] == 'ERROR'){
var html_element = '<div class="alert-message errorr" id = "alert_error"><div class="box-icon"></div><p>'+json['msg']+'</p></div>';
}
document.getElementById("alerts") . innerHTML= html_element;
}else{
alert('<?php echo get_site_url() . '/wp-content/plugins/si/admin/c-si-log.php?log=true' ?>');
}
};
request.onerror = function() {
// There was a connection error of some sort
alert("request isnt good");
};
request.send();
}
window.onload = function (){
if (document.readyState != 'loading'){
waitForMsg();
} else {
document.addEventListener('DOMContentLoaded', waitForMsg);
}
}
</script>
This is how is singleton class called from another class for notification input
SI_log::get_instance()->add_message("action triggered", 'INFO');
I assume the problem is singleton pattern implementation in SI_log class, so there is not only one instance of that class but many more, and when i try to retrieve the notification ie. when I trigger some action, notification isn`t stored in the same object. I used alert(resp); in cilent page to display response and response looks like this
{
"msg":false,
"type":"something"
}
and in log.php you can see that the type value is fine, so it's not communication problem. Can anyone help me please?
NOTE: I must use Javascript because versioning problems so don't ask me why i didn't use JQuery
The singleton pattern is useful when we need to make sure we only have a single instance of a class for the entire request lifecycle in a web application.
So, you can't do the thing you want to achieve in this way.
Instead, use it as a base/parent class and extend it on other classes when you need it.
I'm trying to insert a new user into mysql. I have tried to use jQuery, but it doesn't seem to be working. I tried to use pure javascript, but it's the same. It has no response after I click on the button. What's wrong?
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var shop = document.getElementById("shop");
var http = new XMLHttpRequest();
http.open("POST", "http://xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
http.send(params);
http.onload = function() {
alert(http.responseText);
};
}
There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php, so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var http = new XMLHttpRequest();
// removed the http:// protocol, assuming you're going for a local AJAX call
http.open("POST", "xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// get values of the form fields, don't submit the full element
// also added the plus (+) character before the final pw1
var params = "ac=" + acR.value + "&pw1=" + pw1.value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests
Try to use a JQuery post.
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
alert( "Data inserted: " + data );
});
Backend handles this post and then implement the insert action for example in NodeJs(express)
app.post("/xyz", function(req, res, next) {
var obj = {};
obj[acR] = body.ac;
obj[pw1] = body.pw1;
mysql.insert(obj);
});
I want to display a form with a script I adapted from this question. The script is in a file I wrote called queries.js, and its purpose is to print the content of a php form called "dbMinAlert.php" in a div like this <div id="recentExits" name="recentExits"></div> located in my project's index, I tried invoking getNewData(); in my index.php file using this tag <body onLoad="getNewData()"> but it doesn't seem to do anything at all.
var data_array = ''; // this is a global variable
function getNewData() {
$.ajax({
url: "dbMinAlert.php",
})
.done(function(res) {
data_array = res; // the global variable is updated here and accessible elsewhere
getNewDataSuccess();
})
.fail(function() {
// handle errors here
})
.always(function() {
// we've completed the call and updated the global variable, so set a timeout to make the call again
setTimeout(getNewData, 2000);
});
}
function getNewDataSuccess() {
//console.log(data_array);
document.getElementById("recentExits").innerHTML=data_array;
}
getNewData();`
---This php code works and it actually does what I expect it to do. The real problem is the javascript, for all I care the next php form could print a "Hello world" message, but I want it displayed inside the div I placed in my index, without having to post a thing to dbMinAlert.php.
define("HOST", "localhost");
define("DBUSER", "root");
define("PASS", "password");
define("DB", "mydb");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM outputs, products
WHERE products.idProduct=outputs.idProduct
ORDER BY Date DESC, Time DESC limit 5
");
echo '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
echo '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';
}
echo '</ul>';
You have to execute the function for the first time.
getNewData();
It could be the way you are returning the result from php. Instead of doing multiple echo, could you first assign your result in single php variable and finally do single echo.
$result = '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
$result = $result + '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';}
$result = $result + '</ul>';
echo $result;
I found a solution in this question and my code ended up Like this.
I just had to invoke the function in my index by typing <body onload="return getOutput();">
JavaScript
//Min-Max Alerts
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'dbMinAlert.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('recentExits');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('recentExits');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
This is my code where I call the Request for Ajax, than a simple input button which on onClick event send some data to a function called setValue();
This is the code (JS):
//request for ajax XML
<script type='text/javascript'>
function callAjax(){
var XMLObj = false;
if(window.XMLHttpRequest)
XMLObj = new XMLHttpRequest();
else if(window.ActiveXObject)
XMLObj = new ActiveXObject('Microsoft.XMLHTTP');
if(!XMLObj)
return false;
return XMLObj;
}
//var for ajaxobject handle;
var objAjax = callAjax();
function setValue(value, id, num, item){
if(objAjax){
if(objAjax.readyState == 4 || objAjax.readyState == 0){
objAjax.open('POST', 'addview.php', true);
objAjax.send('value=' + val + '&id='+id+'&num='+num+'&item='+item);
}
}
}
//input for sending value to function setValue();
<input type='button' onClick='setValue(1, 2, 3, 4)' />
//and this is where I handle the sent data via php
<?php
if(!$_POST['value'] || !$_POST['id'] || !$_POST['num'] || !$_POST['item'])
exit();
include('config.php');
$value = mysql_real_escape_string($_POST['value']);
$id = mysql_real_escape_string($_POST['id']);
$num = mysql_real_escape_string($_POST['num']);
$item = mysql_real_escape_string($_POST['item']);
mysql_query("UPDATE `window` SET window_val = window_val + ".$value." WHERE window_id = '".$id."' AND window_num = '".$num."' AND window_item = '".$item."' ") or die(mysql_error() );
mysql_close($con);
?>
The php script is working, I tried it with sending data manually ($_GET['']) and it's working. Also I checked the URL with alert('value='+value+'&id='+id...) and all variables are Ok, but the database won't be queried.
If you see, I don't add any function for response, reply from the server. I just only want to send those data and query the data base.
Thank you !
You may be missing
objAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Consider improving your function names: callAjax doesn't call Ajax, it returns a reference to the XHR object. Call it getXhr or something more like what it's actually doing.
If you're ok with jQuery, just call
function setValue(value, id, num, item){
$.post('addview.php', 'value=' + val + '&id='+id+'&num='+num+'&item='+item);
// or the cleaner version
$.post('addview.php', {value: val, id: id, num: num, item:item});
}