mysql query executed even though fields are empty - javascript

I have created a simple tagging system for my schools websites for the students. Now the tagging system is working perfectly now i also have to save tags in a notifications table with respective article id to later notify the students which article they have been tagged in even that i managed to do. But now if by chance you want to remove the tags sometime realizing while typing the article you don't need to tag that person, then the first put tag also gets updated in the db.
//ajax code (attach.php)
<?php
include('config.php');
if(isset($_POST))
{
$u=$_POST['v'];
mysql_query("INSERT INTO `notify` (`not_e`) VALUES ('$u')");
}
?>
// tagsystem js code
<script type="text/javascript">
var id = '<?php echo $id ?>';
$(document).ready(function()
{
var start=/%/ig;
var word=/%(\w+)/ig;
$("#story").live("keyup",function()
{
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name.length>0)
{
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html)
{
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false();
});
$(".addname").live("click",function()
{
var username=$(this).attr('title');
$.ajax({
type: "POST",
url: "attach.php",
data: {'v': username},
});
var old=$("#story").html();
var content=old.replace(word,"");
$("#story").html(content);
var E="<a class='blue' contenteditable='false' href='profile2.php?id="+username+"'>"+username+"</a>";
$("#story").append(E);
$("#display").hide();
$("#msgbox").hide();
$("#story").focus();
});
});
</script>

Looks like your problem appears on the if statement in php code:
even though $_POST['v'] is empty and the sql still get excuted.
There is the quote from another thread:
"
Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
"
Or in my opinion.
Just put
if ($_POST['v']){
//sql query
}
Hope it helps;)

<?php
include('config.php');
$u = $_POST["v"];
//echo $a;
if($u != '')
{
mysql_query("your insert query");
}
else
{
}
?>

Related

How to GET javascript data in PHP file without page reload

I am building my best attempt at a twitter clone and have run into a bit of a problem. I want to be able to click on a post and, without a page refresh, display that post in the overlay of the page (as you would on a twitter feed to look at replies, etc.).
In script.js, I check for a click and try to change the url.
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
window.history.pushState(obj, "Status", "profile.php?id="+uid+"&status="+pid);
});
The javascript works as intended...but as I will soon find out, the victory is short-lived.
In profile.php, I attempt to GET the status id from the URL parameter.
<?php
$status_id = $_GET['status'];
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'");
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
?>
This doesn't work because, as I've learned, using 'window.history.pushState' only changes the url- but doesn't load the page. Thus the $_GET statement fails. I need a way to get the id of the post I click on into profile.php without a page refresh. Even if it means taking a different approach (instead of using a URL parameter).
PS: I tried to do an XMLHttpRequest as well- to no avail. :(
Thanks in advance!
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
$.ajax({
url: "profile.php?id="+uid+"&status="+pid,
type: "GET",
data: obj,
dataType: "html",
success: function(data){
console.log(data);
}
});
});
You need to just get something up and going that works and then you can add more to it as you figure things out. This should give you a good starting place.
Here are your two files. Make sure they are both in the same directory.
You will need to make sure you have a jquery version loaded. Put this on whatever page you are calling the script.js from.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
script.js
$(document).ready(function(){
$('body').click(function(){
var id; //define your id.
var pid; //define your pid.
var datastring = 'id=' + uid + '&status=' + pid;
console.log(datastring);
$.ajax({
url: 'profile.php',
type: 'POST',
cache: false,
data: datastring,
dataType: 'json',
success: function(data){
console.log('Made it to the success function: ' + data);
if (data) {
//It works, do something.
console.log(data);
} else{
//It does not work, do something.
console.log('Your ajax failed to get the info from your php page. Keep troubleshooting');
}
}
});
});
});
profile.php
<?php
/*
$status_id = $_POST['status']; //This needs to be sanitized and validated.
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'"); //This is unsafe sql practice.
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
echo json_encode($c); //This is what gets sent back to script.js
*/
echo 'You made it to your php page.';
?>
A few things:
You can not call any php variable from within your js. var uid = $_GET['id']; does not work.
Any value that you pass to the php page needs to be validated to make sure it is a legitimate value.
Your SQL query is prone to sql injections. Please read up on how to parameterize your queries. Good Mysqli Practices
I have finally found a AJAX-based solution to my problem.
I created a new php file called "chirp_open_ref.php" and added this ajax to script.js:
var datastring = 'status=' + messageID;
$.ajax({
url: "chirp_open_ref.php",
type: "POST",
data: datastring,
cache: false,
dataType: "text",
success: function(data){
$('.chirp-container').html(data);
}
});
Inside of 'chirp_open_ref.php':
<?php
require 'core.inc.php';
if (isset($_POST['status']) && isset($_SESSION['user_id'])){
$chirp_id = $_POST['status'];
$c = "";
$sql = $db->query("SELECT * FROM chirps WHERE id='$chirp_id'");
if (mysqli_num_rows($sql) > 0){
$c = $sql->fetch_object();
}
include'chirp.inc.php';
}
?>
'chirp.inc.php' is simply a template for the layout/structure of each post.
This works like a charm, but I am always open to any criticism of how I am performing this. Thanks for all the help guys!

javascript missing a url parameter during redirection

my website has an option of country like for different country the website layout is different. it is running on the basis of sessions if session is not set the user will be redirected to index to select a country then will be redirected from the page where he originally came from. here's the code
my session_check_client.php file that is included in every file except index
<?php
session_start();
if(!isset($_SESSION['country']))
{
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
header("location:index.php?return_uri=$actual_link");
}
?>
now what happens is when i go back to home page i wanna check whether this requested has some return parameter or just user has visited he website for the first time. there are two button for two countries of which i am showing the code.
function canada(){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=canada',
success: function (data) {
var $_GET = <?php echo json_encode($_GET);?>;
if($_GET){
//window.location.href=$_GET['return_uri'];
alert($_GET['return_uri']);
}
else {
window.location.href = "home.php";
}
}
});
}
function us(){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=us',
success: function (data) {
var $_GET = <?php echo json_encode($_GET);?>;
if($_GET){
//window.location.href=$_GET['return_uri'];
alert($_GET['return_uri']);
}
else {
window.location.href = "home.php";
}
}
});
}
now the problem is when i am alerting the value of $_GET['return_uri'] it is giving me a false value
e.g my return_uri value is http://localhost/interfold/products2.php?category=Aprons&id=57725599688 it actually shows the whole value in return_uri in index page like http://localhost/interfold/products2.php?category=Aprons&id=57725599688 but when is get the url value using javascript it is onlye giving me the value http://localhost/interfold/products2.php?category=Aprons it is missing the $ and afterwards parts!!! any recommendations?
Since you are only using super global variables, you can directly print a JS variable above the function you are describing:
var actual_link = "<?php echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>";
function postCountry( country ){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=' + country,
success: function (data) {
if(actual_link){
//window.location.href=actual_link;
alert(actual_link);
}
else {
window.location.href = "home.php";
}
}
});
}
postCountry('us');
postCountry('canada');

AJAX doesn't get data from PHP file with Jquery

I'm trying post data to PHP file but i can't receive any data from PHP file. Let me add codes.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="some-class"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
url: "foo.php",
type: "POST",
data: "id=" + somedata,
success: function(){
$("#someid").html();
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
<?php
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','somedatabase');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM sometable WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row['info'];
}
mysqli_close($con);
?>
This what i have in HTML file:
<p id="someid"></p>
Data1
Data2
Note: This website is horizontal scrolling and shouldn't be refreshed. When i'm clicking links (like Data1) it's going to another page without getting data from PHP file
You have a few problems:
You are not using the data as mentioned in the other answers:success: function(data){
$("#someid").html(data);
},
You are not cancelling the default click action so your link will be followed:$('a[class="some-class"]').click(function(e){
e.preventDefault();
...;
As the id's are integers, you can use data: "id=" + somedata, although sending an object is safer in case somedata contains characters that need to be escaped:data: {"id": somedata},;
You have an sql injection problem. You should cast the variable to an integer or use a prepared statement:$data = (int) $_POST['id'];;
As also mentioned in another answer, you have two $(document).ready() functions, one wrapping the other. You only need one.
success: function(){
$("#someid").html();
},
should be:
success: function(data){
$("#someid").html(data);
},
You should add parameter in success
success: function(data){ //Added data parameter
console.log(data);
$("#someid").html(data);
},
The data get the values what you echo in PHP end.
This:
success: function(data){
$("#someid").html(data);
},
and you have two document ready, so get rid of:
$(document).ready(function () { ...
});
data: "id=" + somedata,
Change it to:
data: { id : somedata }

Trying to pass POST from JavaScript to PHP

For a few days now I have been trying to pass a simple POST call to a php script from JavaScript. I've done countless amounts of searching online without any positive results.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function successHandler(location) {
var dataString = '?lat=' + location.coords.latitude + '&long=' + location.coords.longitude + '&accuracy=' + location.coords.accuracy;
alert(dataString);
if (location.coords.latitude == '0') {
} else {
alert("AJAX made");
$.ajax({
type: "POST",
url: "updatepos.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
setTimeout(navigator.geolocation.getCurrentPosition(successHandler),15000);
}
}
function getLocation() {
navigator.geolocation.getCurrentPosition(successHandler);
}
getLocation();
</script>
Above is my JavaScript file. The datastring gets made, and it alerts it out to my browser. No problem there. The problem is, my variables don't get passed to PHP whatsoever.
Here is the PHP that is in the same directory as the JavaScript.
<?php
include 'wp-load.php';
/*global $current_user;
get_currentuserinfo();
echo $current_user->user_login;*/
include('dbconnect.php');
global $current_user;
get_currentuserinfo();
$lat = $_POST['lat'];
$long = $_POST['long'];
$accuracy = $_POST['accuracy'];
/*$lat = $_GET['lat'];
$long = $_GET['long'];
$accuracy = $_GET['accuracy'];*/
$query = "UPDATE ltc_users SET lat='$lat',accuracy=$accuracy,lon='$long' WHERE name='$current_user->user_login'";
mysqli_query($GLOBALS['DB'],$query);
echo mysqli_error($GLOBALS['DB']);
echo $lat;
echo $long;
echo $accuracy;
echo $current_user->user_login;
?>
I may note that before the script would return mysql syntax errors as it was echoed in php due to missing variables. The syntax works if I use the $_GET method and just type in the data into my browser address bar for testing. It just doesn't get the JavaScript variables for whatever reason.
You're passing a string to jquery. When you do that, the string is sent out as-is by jquery. Since it's just a bare string, and not a key:value pair, there's no key for PHP to glom onto and populate $_POST with.
In fact, you shouldn't ever have to manually build a string of key:value pairs for ajax - jquery will take an array/object and do it all for you:
var stuff = {
lat : location.coords.latitude,
long : location.coords.longitude,
accuracy : location.coords.accuracy
}
$.ajax({
data: stuff
});
Here is your code combined with #Marc B
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" > </script>
<script type="text/javascript">
function successHandler(location) {
if (location.coords.latitude == '0') {
} else {
alert("AJAX made ");
$.ajax({
type: "POST",
url: "updatepos.php",
data: {
"lat":location.coords.latitude,
"long":location.coords.longitude,
"accuracy":location.coords.accuracy
},
dataType: "json",
async:true,
cache: false,
success: function(html) {
alert(html);
},error: function(a,b,c){
console.log(a.responseText);
}
});
setTimeout(function(){navigator.geolocation.getCurrentPosition(successHandler);},15000);
}
}
function getLocation() {
navigator.geolocation.getCurrentPosition(successHandler);
}
$(function(){
getLocation();
});
</script>
code in jsfiddle http://jsfiddle.net/y7f1vkej/ it seems to be working for me

json import breaks down but from same server source

I am exploring the ajax synchronous json import into my javascript code.
The JSON source link I want to use is
http://www.nusantech.com/hendak/default.php?m=galaksi&galaksi=1&viewID=1&t=json
But to keep server loads down, a week ago or so I created a static page showing the same data at
http://www.nusantech.com/hendak/noobjson.php
My javascript import is as below:
<head>
<title>Nusantech</title>
<script src="\OpenLayers213\OpenLayers.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
var jsonData = {};
$.ajax({
url: "http://hendak.seribudaya.com/noobjson.php",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
alert("Galaksi value retrieved from JSON (expected: 1) : "+jsonData.galaksi);
</script>
<script type="text/javascript">
function kemasMaklumat(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
</head>
From there I retrieve the values I want on jsonData, eg, (x,y) coordinates as
(jsonData.planets[7].coordinates[0].x,jsonData.planets[7].coordinates[0].y)
It works fine with the noobjson.php link, but when I point it back to default.php, nothing appears. The page took a while to load which make it seem like its loading the json values, but the alert("Galaksi value retrieved") returns undefined.
I copy & pasted the output from the default.php page on a JSON verifier on the web and it showed OK. I don't know why the static link works but the $_GET based link doesn't.
Can someone suggest me what is happening?
EDIT
I have tried:
<script type="text/javascript">
var jsonData = {};
$.ajax({
// url: "http://hendak.seribudaya.com/noobjson.php",
url: "http://hendak.seribudaya.com/default.php?"+encodeURIComponent("galaksi=1&viewID=1&m=galaksi&t=json"),
// url: "http://hendak.seribudaya.com/default.php?galaksi=1&viewID=1&m=galaksi&t=json",
async: false,
dataType: 'json',
type: 'GET',
contentType: "application/json",
success: function(data) {
jsonData = JSON.parse(JSON.stringify(eval("("+data+")")));
alert("Success");
},
error: function(data) {
alert("Failed to download info." + data);
}
});
</SCRIPT>
enter code here
I always get the Failed to download info unless I use the noobjson URL.
It is as if that URL with the GET doesn't exist.
You have to encode the URL component before sending the request. Try:
$.ajax({
url: "http://www.nusantech.com/hendak/default.php?" + encodeURIComponent('m=galaksi&galaksi=1&viewID=1&t=json'),
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
Reference: encodeURIComponent()
I have solved it.
In the default.php, what I have done was:
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
if ($_GET["t"]!="json") { echo "<PRE>\n"; $lb="\n"; }
echo "{\"galaksi\": ".$galaksi.",";
echo $lb."\"hari\": ".$hari.",";
echo $lb."\"planets\": [";
//etc
//etc
}
So I replaced all the individual echoes with $JSONstr like below.
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
$JSONstr="";
// if ($_GET["t"]!="json") { $JSONstr="<PRE>\n"; $lb="\n"; }
$JSONstr=$JSONstr."{\"galaksi\": ".$galaksi.",";
$JSONstr=$JSONstr.$lb."\"hari\": ".$hari.",";
$JSONstr=$JSONstr.$lb."\"planets\": [";
//etc
//etc
//and at the end:
echo $JSONstr;
}
Then I added the echo $JSONstr; at the end. Originally I did that so that I can do :
echo json_encode($JSONstr);
but this creates {\"Galaksi\" : 1} at the JSON output instead of the intended { "Galaksi": 1 }
So I removed the json_encode and just output the string.
Also I had to remove the
if ($_GET["t"]!="json"){ $JSONstr="<PRE>\n"; $lb="\n"; }
I also used a different JSON tester this time.
Originally I used http://www.freeformatter.com/json-validator.html which says JSON Valid for my initial JSON output. Then I used this one, which said that my JSON output url was invalid, although if I copy+paste the output string it returned valid. http://jsonformatter.curiousconcept.com/
So after making those changes and removing the "<PRE>", the curiousconcept validator gave me a valid status.
Then I used this in the javascript, and I am now able to retrieve expected values.
Thank you all, hope this helps someone else too.

Categories