delete checked table rows with ajax - php

I have checked through numerous questions to find the solution. I know I'm close, but I'm still not getting anything happening with my deleteData.php after confirming to delete.
Status:
Testing the array provides successful result.
Example: I checked rows 1, 2 & 31...then press #btn_del.
First, I get the confirm "Are you sure...?"
Next, I see the correct alert(array) 1,2,31
The next step...ajax is supposed to be sending this array data to deleteData.php for processing.
script
$('a#btn_del').click(function(e) {
e.preventDefault();
page = $(this).attr("href");
ids = new Array()
a = 0;
$(".chk:checked").each(function(){
ids[a] = $(this).val();
a++;
})
// alert(ids);
if (confirm("Are you sure you want to delete these courses?")) {
$.ajax({
url : 'deleteData.php',
data : ids,
type : "POST",
//dataType : 'json',
success : function(res) {
if ( res == 1 ) {
$(".chk:checked").each(function() {
$(this).parent().parent().remove();
}) // end if then remove table row
} // end success response function
} // end ajax
}) // end confirmed
}
return false;
}); // end button click function
}); // end doc ready
deleteData.php
<?php
require_once('config.php'); // Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.'.$dbc);
foreach ($_POST['ids']
as $id) {
$sql = "DELETE FROM unit_genData
WHERE unit_id='" . $id . "'";
$result = mysqli_query($sql)
or die(mysqli_error($dbc));
} // end echo result count
mysqli_close($dbc); // close MySQL
echo json_encode(1);
?>
Edited:
Updated GET to POST.
Updated data: 'ids' to data: ids
Tested:
a) In php...echo $_POST['ids'];
NO RESULT
b) In js...commented out the if(confirm...
NO RESULT
Status:
Looks like the AJAX isn't firing (so to speak)

First of all, I would use POST instead of GET for a delete.
Then you need to send the correct data to your php script. What you have now is just a string, no key-value pairs which is what you expect at the backend.
The easiest way to send your data would be to use something like (assuming you have a form):
data: $('form').serialize(),
but you can also send an array like the one you are building:
data: ids,
The advantage of the first method is that values automatically get escaped / encoded (wouldn't make a difference with just integers obviously...).
At the backend you would need to prevent the sql injection problem you have now. You can do that using a prepared statement with bound parameters or in the case of numeric ID's you can cast them to integers.
Edit: As noted in the comments by #Fred-ii-, additional spaces in a string will cause your condition to fail. I would recommend a prepared statement but if you decide to cast to int and use that, just remove the quotes.
Also note that the procedural mysqli_* functions take the database link as the first parameter, that applies both to the query and to the error handling.

Related

How can i change a SELECT query using AJAX call

I'm very new to php and SQL so i'm really sorry if this is very trivial.
My site has multiple divs with table names inside it. The HTML is of the form:<p class="listname">(table name)</p>
I am trying to write a function so that when a user clicks on a div, the function gets the text using innerHTML and the contents of that particular table are shown.
The jquery function i wrote is:
$(document).ready(function(){
$(".listname").click(function(){
var x=($(this).html()).toLowerCase(); //this assigns the text in the class listname to the variable x
console.log(x);
$.ajax({
url: 'http://localhost/fullcalendar/events.php',
data: {name:x},
type: "GET",
success: function(json) {
}
});
});
});
And my PHP code is:
<?php
include 'ChromePhp.php';
ChromePhp::log('php running');
$json = array();
if($_POST['name']!=null)//check if any value is passed else use default value
{
$table=$_GET['name'];
ChromePhp::log($table);
}
else
{
$table= 'event';
ChromePhp::log($table);
}
$requete = "SELECT * FROM `$table` ORDER BY id";
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
When i first load the website, the default value for $table is used in the query, and data is retrieved. However, when i try clicking on a div, the correct value is passed to php and assigned to $table (i checked in the console) but the data displayed is of the default table i.e 'event' table.
How can i fix this?
PS: all my tables are in the same database.
You're checking the POST data:
if($_POST['name']!=null)
But using GET data:
type: "GET"
So the $_POST array will always be empty and your if condition will always be false. You probably meant to check the GET data:
if($_GET['name']!=null)
Also of note are a couple of other problems in this code:
Your success callback is empty, so this AJAX call isn't going to actually do anything client-side. Whatever you want to do with the returned data needs to be done in that success function.
This code is wide open to SQL injection. It's... very unorthodox to dynamically use table names like that. And this is probably an indication that the design is wrong. But if you must get schema object names from user input then you should at least be taking a white-list approach to validate that the user input is exactly one of the expected values. Never blindly execute user input as code.

JS and Ajax: how to dismantle JSON object consist of multiple DB records

I try to learn JS together with jQuery and Ajax, and until now it was more or less painless, but now I faced myself with some obstacles about getting result from called PHP script, initiated by Ajax. What is my problem here? I have a MySQL table and I wanted to pull some data from JS by Ajax call. I tested my query to check is it correct and make result and with same query I built PHP script. Here is my JS file:
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<script>
callphp(12,14);
//
function callphp(par1, par2) {
$.ajax({
type: "POST",
url: "_ajax2php2.php",
cache: false,
dataType: "json",
data: { "po1": par1, "po2":par2 },
success: function(data, status, jqXHR){
jss=JSON.stringify(data);
alert(jss);
//
var strBuilder = [];
for(key in data){
if (data.hasOwnProperty(key)) {
strBuilder.push("Key is " + key + ", value is " +data[key] + "\n"); }
}
alert(strBuilder.join(""));
},
error: function(data) {
alert( "params error" );
}
});
// end of JS
and here is my PHP script:
<?php
$eol="<br/>";
$uuu= isset($_POST['po1']) ? $_POST['po1'] : '';
$zzz= isset($_POST['po2']) ? $_POST['po2'] : '';
$con=mysqli_connect("localhost","root","some_password","mydbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Fail to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"mydbase");
$query4 = "SELECT * from mytable WHERE uc_id='$uuu' AND pr_id='$zzz' ";
$result4 = mysqli_query($con, $query4);
$row4= mysqli_fetch_assoc($result4);
if(mysqli_num_rows($result4) > 1) {
while($row4[]=mysqli_fetch_assoc($result4)) {
$data = $row4; }
}
else
{$data=$row4;}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
/* free result set */
mysqli_free_result($result4);
mysqli_close($con);
//end of php
?>
and it seems that it works good when PHP query return just one record, if there are 2 or more then I'm unable to "dismantle" JSON object by this JS code, because for example if my query return 3 records, in alert it appears like
Key is 0, value is [object Object]
Key is 1, value is [object Object]
Key is name_of_field1, value is 1
Key is name_of_field2, value is 12
Key is name_of_field3, value is 2
Key is name_of_field4, value is 1
Key is name_of_field5, value is 14
Key is name_of_field6, value is 2015-09-10
and I need to be able to get each particular record fields of each record in order to fill with it some HTML table. How to write this part of code that resolve JSON response consist of two or more records made by PHP? I tried examples I found here but no one met my needs. Thanks.
In your while loop after the DB query, you are just overwriting the value for $data with every iteration. I would suggest not having different logic for cases with one row in result set vs. more than one row, as this does nothing but add complexity to your code. Just return an array every time and you will be better off. Your code around the query might look like this:
$data = array();
$result4 = mysqli_query($con, $query4);
if($result4) {
while($row = mysqli_fetch_assoc($result4) {
$data[] = $row;
}
}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
This simplifies this section of code and will also simplify the client-side code since now you can write it to simply expect to work with an array of objects in all cases.
This means that in javascript your code might look like (ajax success handler code shown):
success: function(data, status, jqXHR){
// data is an array, with each array entry holding
// an object representing one record from DB result set
var recordCount = data.length;
console.log(recordCount+' records returned in response.');
// you can iterate through each row like this
for(i=0;i<recordCount;i++) {
// do something with each record
var record = data[i];
// in this example, I am just logging each to console
console.log(record);
// accessing individual properties could be done like
console.log(record.name_of_field1);
console.log(record.name_of_field2);
// and so on...
}
}
You should get in the habit of using console.log() rather than alert() or similar for debugging your javascript, as alert() actually interrupts your javascript code execution and could introduce problems in debugging more complex javascript (particularly when there are asynchronous activities going on). Using the javascript console functionalty built into your browser should be fundamental practice for any javascript developer.

trying to put api data in database with php?

I'm pulling deals from Groupon's api, and I have no clue how to take the data and put it into a database with php, i know how to show it on in html, but not in the database, I need to pull it into the database so I have more control over the info, if anybody knows how to do this or knows a better way, i'm all eye's, lol, thanks
<script type='text/javascript'>
$(function () {
$.getJSON("https://api.groupon.com/v2/deals.json?callback=?",
{
client_id: "b252ad3634a4ab2985b79d230ccc4e49a3ea9d19",
show: "all",
division_id: "los-angeles"
})
.done(function (data) {
console.log(data);
// do whatever processing you need to do to the data
// right here, then drop it in the div
$.each(data.deals, function (i, v) {
$title = $("<h2/>", {
html: v.title,
class: "heading"
});
$img = $("<img/>", {
src: v.mediumImageUrl
});
$deal = $("<div/>", {
html: v.highlightsHtml + v.pitchHtml
});
$("#main").append($deal);
$deal.prepend($title, $img);
});
});
});
</script>
Theory
Well I'm just gonna start running through the process...
First, know which driver you are dealing with and research how PHP interacts with them. Look at this list and start reading...
http://www.php.net/manual/en/refs.database.php
Sending the data to a PHP script to handle the rest, depends on how you got the data. Here are some basic flows...
Pull it using jQuery, and use AJAX to send it as soon as you get it to the php script to save it. (Requires an additional HTTP request)
Pull it using PHP, save it to the DB, then format and output it on the same page. (Slows down initial page load time)
Pull it with jQuery, format it, and allow the user to press a button that will then ajax that entry to the PHP save script (More flexible, but greatly increases requests)
After you can get a connection to your database you just need to save it to a table using a SQL query (most likely using INSERT or UPDATE). With JSON data, I prefer to save it to a column that has the data type of TEXT. The only real risk here is that you have to be sure that you can validate the data. ESPECIALLY IF THE DATA IS BEING GIVEN TO PHP FROM A JAVASCRIPT /AJAX SOURCE!
Pulling the data from that point is just using a "SELECT" sql statement. PHP's database modules will pull this data and put it into a lovely array for you, making manipulation easy.
Examples
Now thats the theory, heres some actions. I'm going to be choosing the 1st flow idea. Now this one will just save it to the database. I'm not doing any fancy checking or really pulling. But this will show you the idea of how ajaxing and saving to php would work.
view-deals.html
<script type='text/javascript'>
$(function () {
$.getJSON("https://api.groupon.com/v2/deals.json?callback=?",
{
client_id: "b252ad3634a4ab2985b79d230ccc4e49a3ea9d19",
show: "all",
division_id: "los-angeles"
}).done(function (data) {
console.log(data);
// do whatever processing you need to do to the data
$.post('save-deals.php',{dealData: data}, function(finishData) {
//This is an optional function for when it has finished saving
});
// Your formatting comes next
....
});
</script>
Now that will send all the data that you got (intact) from groupon to a seperate php script using an AJAX Post call. I use post, well, because that's what it's for.
save-deals.php
ob_start(); //I like output-buffering because if we need to change headers mid script nothing dies
$DealData = isset( $_POST['dealData'] )?$_POST['dealData']:die("Malformed form data!");
if($DealData!='') {
$DB = new mysqli("example.com", "user", "password", "database");
if ($DB->connect_errno) {
echo "Failed to connect to MySQL: " . $DB->connect_error;
}
$DealData = $DB->real_escape_string($DealData); //Sanitize it for MySQL
if (!$DB->query("INSERT INTO deals(data) VALUES ($DealData)") {
echo "Insert failed: (" . $DB->errno . ") " . $DB->error;
} else {
//AT THIS POINT IT SHOULD HAVE BEEN INSERTED!
//You could return a success string, or whatever you want now.
}
} else {
http_response_code("400");
die("Bad Request, please check your entry and try again");
}
ob_end_flush(); //Close up the output-buffer
Some important things to note about that script is that the ob_* functions are completely optional. The way DealData is set is a VERY shorthand way of checking that the post data contains that value, and setting it properly; if not, then to give an error.
This next script is to show you how to pull the data from the database now, and manipulate it if you want. It will also return the data as JSON information so it can be used with a javascript $.getJSON() call. This is mostly a snippet for reference
manipulate-deals.php
//First connect to the database!
$DB = new mysqli("example.com", "user", "password", "database");
if ($DB->connect_errno) die("Failed to connect to MySQL: " . $DB->connect_error);
//Get ALL the entries!
if(!$results = $DB->query("SELECT * FROM data")) die("Failed to retrieve data! ".$DB->error);
//Decode the datas!
$returnResults = [];
while($entry = $results->fetch_assoc()) {
$JSON = json_decode($entry['data']);
//Manipulate however you wish!
$JSON->whatever->tags[1]->you->want = "whatever value";
//Add it to the results!
$returnResults[] = $JSON;
}
echo json_encode($returnResults);
That very last section is just for fun. It would export a json string containing an array of results. And each of that array's entries would be a valid object just as groupon had given you. Hope that helps!

Putting mySQL Database Information into a JavaScript Array

What I'm trying to do is create a slideshow by grabbing database information and putting it into a javascript array. I am currently using the jquery ajax function to call information from a separate php file. Here is my php code:
mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$i = 0;
$sql = mysql_query("SELECT comicname FROM comics ORDER BY upldate ASC");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
echo "comics[" .$i. "]='comics/" .$row['comicname']. "';";
$i++;
}
What I want is to create the array in php from the mysql query and then be able to reference it with javascript in order to build a simple slideshow script. Please let me know if you have any questions or suggestions.
Ok have your .php echo json_encode('name of your php array');
Then on the javascript side your ajax should look something like this:
$.ajax({
data: "query string to send to your php file if you need it",
url: "youphpfile.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]); //this should tell you if your pulling the right information in
}
});
maybe replace data.length by 3 or something if you have alot of data...if your getting the right data use a yourJSArray.push(data[i]); I'm sure there's a more direct way actually...
You may want to fetch all rows into a large array and then encode it as a JSON:
$ret = array();
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
$ret[] = $row
echo json_encode($ret);
Then, on the client side, call something like this:
function mycallback(data)
{
console.log(data[0].comicname); // outputs the first returned comicname
}
$.ajax
(
{
url: 'myscript.php',
dataType: 'json',
success: mycallback
}
);
Upon successful request completion, mycallback will be called and passed an array of maps, each map representing a record from your resultset.
It's a little hard to tell from your question, but it sounds like:
You are making an AJAX call to your server in JS
Your server (using PHP) responds with the results
When the results come back jQuery invokes the callback you passed to it ...
And you're lost at this point? ie. the point of putting those AJAX results in to an array so that your slideshow can use them?
If so, the solution is very simple: inside your AJAX callback, put the results in to a global variable (eg. window.myResults = resultsFromAjax;) and then reference that variable when you want to start the slideshow.
However, since timing will probably be an issue, what might make more sense is to actually start your slideshow from within your callback instead. As an added bonus, that approach doesn't require a global variable.
If this isn't where you are stuck, please post more info.

Checking multiple fields from mysql with jquery AJAX in one call

I've got a page that seems to be in full working order, but I'm having major performance issues (think 30 second delay occasionally from these calls) from what I assume is throwing too many individual POST requests to the server.
Am I right in thinking that there's some way of doing it all in one call and that doing so would improve performance, and what's the easiest way of doing it? Perhaps my use of eval() is part of the problem - or maybe my webhost is just shit.
function startCheckAchs(){
//hide the loading alert
$(document).ajaxStop(function(){
$(this).unbind("ajaxStop");
popup('loadingAlert');
});
//load lifeTimeBaked
lifeTimeBaked = loadAch("lifetimebaked");
loadAch("ach_started", "#achStarted", "achstarted");
loadAch("ach_round1", "#achRound1", "achround1");
loadAch("ach_round2", "#achRound2", "achround2");
loadAch("ach_round3", "#achRound3", "achround3");
if( rewards == 1) {
loadAch("ach_baked100", "#achBaked100", "achbaked100");
loadAch("ach_baked500", "#achBaked500", "achbaked500");
loadAch("ach_baked1000", "#achBaked1000", "achbaked1000");
loadAch("ach_nobread", "#achNoBread", "achnobread");
loadAch("ach_nodough", "#achNoDough", "achnodough");
loadAch("ach_noflour", "#achNoFlour", "achnoflour");
loadAch("ach_allach", "#achAllAch", "achallach");
}
}
function loadAch(ach, achDiv, achVar){
$.ajax({
type: "POST",
url: "scripts/loadach.php",
data: {"achievement" : ach},
dataType: "text",
success: function(result){
if ( achDiv && achVar && result == 1){
$(achDiv).show();
eval(achVar + " = 1");
return result;
} else {
return result;
}
}
});
}
Loadach.php:
$achievement=trim($_POST['achievement']);
$user = $_SESSION['userid'];
$query = "SELECT $achievement FROM breadusers WHERE userid='$user'";
$link =#mysql_query($query);
if(!$link){
die('Could not query:' . mysql_error());
}
echo mysql_result($link, 0);
?>
You are currently loading achievements individually, while you should be doing something like:
<?php
$query = "SELECT ach_started, ach_round1 FROM breadusers WHERE userid='$user'";
$link = mysql_query($query);
$results = mysql_fetch_assoc($link);
echo json_encode($results);
?>
Then, in your javascript code, parse the JSON response (setting dataType: "json" should work), loop over the returned object (has keys such as ach_started, ach_round1, etc etc), and show/hide divs as needed.
Unfortunately you are going to have to redesign that.
SQL queries are slow.
Lots of requests make things slow.
See if you can group all of the data for a user in your database. That way you can make one select for all of the data you need.
You could use a multi-dimensional array and fill it with the data needed, send the array with ajax to the php code, and then you could loop through the array in the php code and echo back the desired results.
This way you would only be making 1 ajax call each time but still get the same results. might be faster this way but i have not tested this. =)
Most browsers have a limit on the number of concurrent server requests they can handle.
If you're using sessions, you'll also find that the server can only process a single request for each session at a time, because the session file is locked by each request, and subsequent requests must wait for it to be unlocked either when the first request finishes, or when a session_write_close() is issued by the executing request.

Categories