How to insert a variable in a query from .ajax post - php

I thought this will be very simple but i think there is a bug when posting a variable from .ajax to a query. Is there any other way I ca get my result?
here is my jquery:
jQuery_1_4_2(document).ready(function()
{
jQuery_1_4_2('.mainfolder').live("click",function()
{
event.preventDefault();
var ID = jQuery_1_4_2(this).attr("id");
var dataString = 'folder_id='+ ID;
if(ID=='')
{
alert("Serious Error Occured");
}
else
{
jQuery_1_4_2.ajax({
type: "POST",
url: "display_folder.php",
data: dataString,
cache: false,
success: function(html){
jQuery_1_4_2(".right_file").prepend(html);
}
});
}
});
});
here is my display_folder.php
<?php
$folder_id = $_POST['folder_id'];
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>
Can anybody explain why this not work? i tried to echo $folder_id and it is working, but when you put it inside the query it is not working.
Note: This is not a dumb question where i forgot my connection of db. Thanks

I agree with both you and here I am providing (just for clean display) the same with some little formatting.
var dataString = 'folder_id=1';
$.ajax({
url: "folder.php",
type:'post',
async: false,
data:dataString,
success: function(data){
alert(data);
}
});
and php part where I am getting folder_id properly.
<?php
$postid = $_POST['folder_id'];
//echo $postid;
$link = mysql_connect("localhost","root","");
mysql_select_db("test", $link);
$query = mysql_query("select * from post where id='$postid'");
while($row=mysql_fetch_array($query))
{
echo $row['text'] . "<br>"; //a, b etc in each row
}
?>
So it should work.

Try this in your php code
<?php
$folder_id = addslashes($_POST['folder_id']);
//echo $folder_id;
$qry=mysql_query("SELECT * FROM tbl_folder WHERE folder_id='$folder_id'");
while($row=mysql_fetch_array($qry))
{
echo $row['folder_name'] . "<br>";
}
?>

Related

How to assign ajax response to Variables

I have drop down Select box as follows
<?php
$sql = "SELECT scheduleName FROM schedule";
$result = mysqli_query($link,$sql);
echo "<select name='schedule' id='schedule'>";
echo "<option value=''>-- Select Schedule --</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['scheduleName'] . "'>" . $row['scheduleName'] . "</option>";
}
echo "</select>";
?>
And I have a file called processClg.php as follows
<?php
include "config.php";
if ($_POST['type']=='POST')
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE 'Row id of drop down selection'";
$res = mysqli_query($link,$qry);
}
?>
How can I call processClg.php file on $("#schedule").change(function ());by assigning Row id of drop down selection as where condition.
Update
Am getting Response from processClg.Php as follows
[{"id":"2","scheduleName":"shanth","subject":"Patho","university":"Dali","facultyName":"Dr","scheduleStartDate":"2015-06-05","scheduleEndDate":"2015-06-09"}]
How to assign response values from ajax call to the following Php variables
<?php
$scheduleStartDate = '';
$scheduleEndDate = '';
?>
Any help my greatly appreciated.
$("#schedule").change(function() {
var value = $('#schedule option:selected').text();
var ajaxCheck = $.ajax({
url: 'processClg.php',
type: 'POST', // had mention post bcoz u mention in processClg.php
dataType: 'json', // processClg.php will return string means change to text
data: { id: value },
success: function(data){
console.log('success');
itrToRead(data);
}
});
});
function itrToRead(data) {
$(data).each(function(key, value){
console.log('key is: '+key+' and value is: '+value);
});
}
processClg.php
<?php
include "config.php";
if ($_POST['type']=='POST') {
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_POST['id']."'";
$res = mysqli_query($link,$qry);
echo $res;
}
?>
You can call ajax as follows:
var RowId;
$.ajax({
type: "POST",
async: false,
url: url,
data: postdata,
//dataType: "json",
success: function (data) {
RowId = data;
}
});
The fact is that to assign response to variable is pass the parameter async: false,
Then its work.
I guess you have your dropdown in your rendered page and you want to send the selected value to the php page:
$("#schedule").change(function(){
var val2pass = $(this).find(':selected').val(); // get the value
$.ajax({
url: 'processClg.php',
type:'post', // <-----you need to use post as you are using $_POST[]
data: { rowid : val2pass }, //<---pass the value
success: function(data){
itrToRead(data);
}
});
});
So now on the php side you need to do this:
<?php
include "config.php";
if ($_POST['type']=='POST')
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_POST['rowid']."'";
$res = mysqli_query($link,$qry);
}
?>
Your procellClg.php will be
<?php
include "config.php";
if (isset($_REQUEST['qid']))
{
$qry = "SELECT * FROM schedule WHERE scheduleName LIKE '".$_REQUEST['qid']."'";
$result = mysqli_query($link,$qry);
echo "<select name='schedule' id='schedule'>";
echo "<option value=''>-- Select Schedule --</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['scheduleName'] . "'>" . $row['scheduleName'] . "</option>";
}
echo "</select>";
}
?>
and then make Ajax function call
$("#schedule").change(function() {
val = $(this).val();
$.ajax({
type: "POST",
async: false,
url: 'processClg.php',
data: {qid:val},
success: function(data){
$(this).html(data);
}
});
});

Using AJAX to return JSON from PHP

Apologies if this is a repeat question, but any answer I have found on here hasn't worked me. I am trying to create a simple login feature for a website which uses an AJAX call to PHP which should return JSON. I have the following PHP:
<?php
include("dbconnect.php");
header('Content-type: application/json');
$numrows=0;
$password=$_POST['password'];
$username=$_POST['username'];
$query="select fname, lname, memcat from members where (password='$password' && username='$username')";
$link = mysql_query($query);
if (!$link) {
echo 3;
die();
}
$numrows=mysql_num_rows($link);
if ($numrows>0){ // authentication is successfull
$rows = array();
while($r = mysql_fetch_assoc($link)) {
$json[] = $r;
}
echo json_encode($json);
} else {
echo 3; // authentication was unsuccessfull
}
?>
AJAX call:
$( ".LogIn" ).live("click", function(){
console.log("LogIn button clicked.")
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "scripts/sendLogDetails.php",
data: dataString,
dataType: "JSON",
success: function(data){
if (data == '3') {
alert("Invalid log in details - please try again.");
}
else {
sessionStorage['username']=$('#username').val();
sessionStorage['user'] = data.fname + " " + data.lname;
sessionStorage['memcat'] = data.memcat;
storage=sessionStorage.user;
alert(data.fname);
window.location="/awt-cw1/index.html";
}
}
});
}
As I say, whenever I run this the values from "data" are undefined. Any idea where I have gone wrong?
Many thanks.

Passing json to php and getting response

I am new to php/ajax/jquery and am having some problems. I am trying to pass json to the php file, run some tasks using the json data and then issue back a response. I am using the facebook api to get log in a user,get there details, traslate details to json, send json toe the server and have the server check if the users id already exists in the database. Here is my javascript/jquery
function checkExisting() {
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.id );
var json = JSON.stringify(response);
console.log(json);
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
}
Here is my php file
if(isset($_POST['user']) && !empty($_POST['user'])) {
$c = connect();
$json = $_POST['user'];
$obj = json_decode($json, true);
$user_info = $jsonDecoded['id'];
$sql = mysql_query("SELECT * FROM user WHERE {$_GET["id"]}");
$count = mysql_num_rows($sql);
if($count>0){
echo 1;
} else{
echo 0;
}
close($c);
}
function connect(){
$con=mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to Database: " . mysqli_connect_error();
}else{
return $con;
}
}
function close($c){
mysqli_close($con);
}
I want it to return either 1 or 0 based on if the users id is already in the table but it just returns a lot of html tags. . The json looks like so
{"id":"904186342276664","email":"ferrylefef#yahoo.co.uk","first_name":"Taak","gender":"male","last_name":"Sheeen","link":"https://www.facebook.com/app_scoped_user_id/904183432276664/","locale":"en_GB","name":"Tadadadn","timezone":1,"updated_time":"2014-06-15T12:52:45+0000","verified":true}
Fix the query part:
$sql = mysql_query("SELECT * FROM user WHERE {$_GET['id']}");
Or another way:
$sql = mysql_query("SELECT * FROM user WHERE ". $_GET['id']);
Then it's always better to use dataType in your ajax
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
dataType: "jsonp", // for cross domains or json for same domain
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
Where is $jsonDecoded getting assigned in your PHP? Looks unassigned to me.
I think you meant to say:
$obj = json_decode($json, true);
$user_info = $obj['id'];
And your SELECT makes no sense. Your referencing $_GET during a POST. Maybe you meant to say:
$sql = mysql_query("SELECT * FROM user WHERE id = {$user_info}");

Ajax post in oscommerce

I'm trying to update my database on the event of a change in my select box. The php file I'm calling on to process everything, works perfectly. Heres the code for that:
<?php
$productid = $_GET['pID'];
$dropshippingname = $_GET['drop-shipping'];
$dbh = mysql_connect ("sql.website.com", "osc", "oscpassword") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("oscommerce");
$dropshippingid = $_GET['drop-shipping'];
$sqladd = "UPDATE products SET drop_ship_id=" . $dropshippingid . "
WHERE products_id='" . $productid . "'";
$runquery = mysql_query( $sqladd, $dbh );
if(!$runquery) {
echo "Error";
} else {
echo "Success";
}
?>
All I have to do is define the two variables in the url, and my id entry will be updated under the products table, ex: www.website.com/dropship_process.php?pID=755&drop-shipping=16
Here is the jquery function that is calling dropship-process.php:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
$('#drop_shipping').change(function() {
var pid = $.urlParam('pID');
var dropshippingid = $(this).val();
$.ajax({
type: "POST",
url: "dropship_process.php",
data: '{' +
"'pID':" + pid + ','
"'drop-shipping':" dropshippingid + ',' +
'}',
success: function() {
alert("success");
});
}
});
});
I'm thinking that I defined my data wrong some how. This is the first time I've ever used anything other than serialize, so any pointer would be appreciated!
Would it not be enough to define your URl like so:
url: "dropship_process.php?pID="+ pid +"&drop-shipping="+ dropshippingid
Your ajax code is not correct. replace your ajax code by below code:
$.ajax({
type: "POST",
url: "dropship_process.php",
dataType: 'text',
data: {"pID": pid,'drop-shipping': dropshippingid},
success: function(returnData) {
alert("success");
}
});

jQuery and MySQL

I have taken a jQuery script which would remove divs on a click, but I want to implement deleting records of a MySQL database. In the delete.php:
<?php
$photo_id = $_POST['id'];
$sql = "DELETE FROM photos
WHERE id = '" . $photo_id . "'";
$result = mysql_query($sql) or die(mysql_error());
?>
The jQuery script:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The div goes away when I click on it, but then after I refresh the page, it appears again...
How do I get it to delete it from the database?
EDIT: Woopsie... forgot to add the db.php to it, so it works now >.<
There's no way the php could even come close to working. Where is the database? Check out http://www.php.net/manual/en/mysql.examples-basic.php from which you can see there's more to the database than just a query.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
You have your data as a GET string, but you are using a POST request, try changing your string variable to an object. Like :
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = { id : id };
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
Plus I am hoping you are preparing your MySQL connection properly in your PHP, you cannot just call mysql_query and hope it will know which database you mean, and how to connect to it by itself :)
Look at #Quotidian answer! :)

Categories