I have a filter for some devices in a webpage, made of checkbox. Whenever one of the checkbox is clicked, i call a function which add to an object the value of the checkboxes checked. I want to send this object to a php file, via ajax, and use it to perform some MySQL query, then return the results from the php and display them on the page. The problem is, i'm missing something, since i kept getting a parseerror in my js.
Here's my code:
device-filter.js
$(document).ready(function(){
$(".ez-checkbox").click(function() {
console.log("ok");
var re = {Brand: "", Cost: "", OS: ""};
$("#Brand :checkbox:checked").each(function(){
re.Brand += $(this).val()+" & ";
});
$("#Cost :checkbox:checked").each(function(){
re.Cost += $(this).val()+" & ";
});
$("#OS :checkbox:checked").each(function(){
re.OS += $(this).val()+" & ";
});
if(re.lenght==0){
}
else{
$.ajax({
method: "POST",
dataType: "json", //type of data
crossDomain: true,
data: re,
url:"./php/filtered-device-query.php",
success: function(response) {
//display the filtered devices
},
error: function(request,error)
{
console.log(request+":"+error);
}
});
}
});
});
filtere-device-query.php
<?php
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_db");
if (mysqli_connect_errno()) { //verify connection
echo "Error to connect to DBMS: ".mysqli_connect_error(); //notify error
exit(); //do nothing else
}
else {
//echo "Successful connection"; // connection ok
$devices =json_decode($_POST['re']);
echo var_dump($devices)."<br>";
$myArray = array();//create an array
$brand = rtrim($devices["Brand"], " &");
$cost = rtrim($devices["Cost"], " &");
$os = rtrim($devices["OS"], " &");
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND 'Cost' = '$cost' AND 'OS' = '$os' ";
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
//free result
$result->close();
//close connection
$mysqli->close();
}
?>
Thanks in advance for any help!
You have some typos, first in the jQuery:
if(re.lenght==0){
should be:
if(re.length==0){// note the correct spelling of length
Then in your PHP you're using quotes on column names in the query. Those should be removed or better yet, back ticked:
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND `Cost` = '$cost' AND `OS` = '$os' ";
More importantly...
An object, as you've described it, has no length. It will come back as undefined. In order to find the length you have to count the keys:
if(Object.keys(re).length == 0){...
The object re, as you've declared it, already has 3 keys, a length of 3. Checking for length of 0 is a waste of time.
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
Related
My Alert is showing that updated successfully but data is not updating in database and not able to click ok button of alert. Here is my php code for upresult.php. Hope This will b helpful. Thank you in advance
my jquery
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url:"upresult.php",
type:"POST",
data:formData,
async:true,
success:function(data) {
alert(data);
},
cache:false,
contentType:false,
processData:false
});
});
});
upresult.php
<?php
include("connection.php");
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
$qry="update stud set stud_name='".$name."',mobile='".$mob."',dob='".$dob."',address='".$add."',gender='".$gen."',country='".$cn."',state='".$st."',city='".$ct."' where stud_no='".$no."'";
$data=mysqli_query($conn,$qry);
if($data)
{
echo '<script language="javascript">';
echo 'alert("Updated Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot update record")';
echo '</script>';
}
?>
You want to alert alert. Try with editing your flow control structure like this:
<?php
include("connection.php");
// you need to validate this data before sending it to update query
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
// this parameters should be binded to avoid SQL injection
$query = "
update stud
set
stud_name = '$name',
mobile = '$mob',
dob = '$dob',
address = '$add',
gender = '$gen',
country = '$cn',
state = '$st',
city = '$ct'
where stud_no = '$no';
";
/** This may be query for checking.
* Just execute it after first query and grab response from it.
* Depends of response you will return appropirate text message.
*/
$checkUpdateQuery = "
select if(count(*) = 1, true, false) as response
from stud
where stud_name = '$name',
and mobile = '$mob',
and dob = '$dob',
and address = '$add',
and gender = '$gen',
and country = '$cn',
and state = '$st',
and city = '$ct'
and stud_no = '$no';
";
/** mysqli_query will return false only if some error occurred.
* In other cases you will get true,
* so you need to check if data is updated by another query.
*/
$data = mysqli_query($conn, $query);
echo $data ? 'Updated Successfully' : 'Cannot update record';
Few things you should consider is do you have certain stud_no in database, mysqli_query returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
If you want we can change this query. Can you use PDO instead of mysqli?
I have jQuery script to send data from one php to another one.
<script>
jQuery(function(){
jQuery(".button").click(function(){
$.ajax({
url : "content_articles.php",
type : 'POST',
data : {'mark': ButtonValue}
}).done(function(response){
alert(response);
}).fail(function(jqXHR, textStatus, errorThrown){
alert('FAILED! ERROR: ' + errorThrown);
});
});
});
It should take button's value and send it. The value is right, checked with "some debug" alert. But all I have in the end is alert 'FAILED! ERROR: ' with no error message.
On the other side i use
$rowid=$_POST['mark'];
It is empty of course...
The rest of content_articles
<?php
$rowid=$_POST['mark'];
/*echo $_POST['mark'];
exit;*/
mysql_set_charset('utf8');
$mysqli = mysql_connect("localhost", "root", "");
$MySQLSelectedDB = mysql_select_db('content', $mysqli);
$res = mysql_query("SELECT id FROM news ORDER BY id DESC LIMIT 1");
$last =mysql_fetch_assoc($res);
if($rowid==""){
$sql="SELECT * FROM news WHERE id = ".$last['id'];
}
else
{
$sql = "SELECT * FROM news WHERE id='".$rowid."'";
}
$result = mysql_query($sql) or die(mysql_error());
?>
In you ajax replace alert('succesful'); by alert(response);.
Let's check if MARK is arriving ok, put next 3 lines at the top of your code :
$rowid=$_POST['mark'];
echo $_POST['mark'];
exit;
Let's shorten your code :
$rowid=$_POST['mark'];
mysql_set_charset('utf8');
$mysqli = mysql_connect("localhost", "root", "");
$MySQLSelectedDB = mysql_select_db('content', $mysqli);
$sql = "SELECT * FROM news WHERE id='".$rowid."'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['SOME_COLUMN'];
You replace "SOME_COLUMN" by a column in table "news".
let's check if there are results from your query, replace the last line by this one:
echo mysql_num_rows( $result );
You can try to use next
var ButtonValue = $(this).attr('value');
// check here that your ButtonValue is not empty, you can call alert(Buttonvalue); to sure that this var is not empty and receive value from clicked element
$.post('content_articles.php', { mark:ButtonValue }, function(data){
alert(data); // to show what the resposne from script
});
Make sure in console of browser that your PHP script is available and server not return any error (like 404 or 500 and etc)
I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);
I have this PHP:
function getList() {
$sql = " SELECT * FROM list ";
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array('result' => $result));
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
and this javascript:
$.ajax({
type: 'GET',
url: rootURL + '/' + myAPI,
dataType: "json",
success: function(list) {
var list = list.result;
console.log (list);
}
error: function( jqXHR, textStatus, errorThrown ) {
console.log (" errors: " );
console.log (jqXHR);
console.log (textStatus);
console.log (errorThrown);
}
});
now everything was working fine until I added some rows in the list table of my DB.
So now the js list result from AJAX is empty:
{"result": }
The error I receive from AJAX is:
Object { readyState=4, status=200, statusText="OK", more elements...}
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
so I tried to remove: dataType: "json", but result is still empty.
the only way to make it works is to limit the SQL query like this:
$sql = " SELECT * FROM list LIMIT 9 ";
and it works:
{"result":
[
{"ID":"1","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"2","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"3","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"4","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"5","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"6","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"7","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"8","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"9","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
]
}
I don't understand why there is such a limit. I also tried:
$sql = " SELECT * FROM list LIMIT 10 ";
and so on, but the result is still empty:
{"result": }
Can you help me please?
Thanks
Read the manual at http://php.net/json_encode. It says:
All string data must be UTF-8 encoded.
Make sure your data is in UTF-8 encoding in the database. If not you have to convert it first.
If it is working with LIMIT 9 and not working with LIMIT 10 so problem is in your records after 9th row so please check your 10th row It may have any 'special character', 'new line character' which is creating problem.
There are 2 points I'd like to point out in your code to have a look at. First of all, the construction of the error should be using the json_encode function, which will ensure valid format, so instead of doing echo '{"error":{"text":'. $e->getMessage() .'}}'; you should do
$response = new stdClass();
$response->error = new stdClass();
$response->error->text = $e->getMessage();
echo json_encode($response);
Note, that it looks overly complex, but I tried to retain the format you specified in your example.
The other thing is that Javascript will not like type: 'json' if the correct headers are not set. So what I suggest your PHP function should look like is this:
function getList() {
$response = new stdClass();
$sql = " SELECT * FROM list ";
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$response->result = $result;
unset($db);
} catch(PDOException $e) {
$response->error = new stdClass();
$response->error->text = $e->getMessage();
}
header("Content-Type: application/json");
echo json_encode($response);
exit();
}
I hope this helps!
I'm new to dynamic data and trying to
read data from a mysql database using PHP
turning this data to JSON
fetching the data through javascript (jQuery)
Inserting it into my page.
As far as I can see, 1) and 2) work fine, 3) seems to kind of work and 4) is where it breaks.
I've set up the database and the table, query & echo the data like so (api.php)
<?php
include 'db.php';
$con = new mysqli($host,$user,$pass,$databaseName);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM $tableName";
$myArray = array();
if ($result = $con->query($query)) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$con->close();
?>
Now I get it through javascript...
jQuery(function($) {
$.ajax({
url: 'php/api.php',
data: "json",
dataType: "",
success: function(data) {
var r = new Array(), j = -1;
for (var key=0, size=data.length; key<size; key++){
r[++j] ="<tr><td>";
r[++j] = data[key][0];
r[++j] = "</td><td>";
r[++j] = data[key][1];
r[++j] = "</td><td>";
r[++j] = data[key][2];
r[++j] = "</td></tr>";
}
var joined = r.join('');
console.log(joined);
$('#maintable tbody').html(joined);
}
});
});
... and throw it in the tbody element of my table.
The result is absolutely not what I expected:
See http://i.imgur.com/hRNrmdC.jpg (sorry for the partly german interface)
The Answer to the GET request is valid JSON, at least in theory (checked by http://jsonlint.com/ ), but to me it seems the data is treated as a string and split into an array of chars (each char a "key" in data[]), therefore "data[key][1] returns nothing.
var json = JSON.stringify(eval("(" + data + ")"));
and continuing with json[key][0] didn't help...
Now I wonder why and especially, what went wrong and how its fixed.
You have mixed up the keys in your ajax call:
data: "json",
dataType: "",
Should be:
dataType: "json",
as you are not sending or using any data at all.