Ajax pass id using POST with php (Error Undefined variable: id) - javascript

Im new In AJAx. My problem is I have ajax Function to pass variable ID in php when the page is load the error is Undefined variable: id but when I look in firebug post id is past successfully . Here is my ajax.
$('.btn_edit').click(function(e){
e.preventDefault();
var $this = $(this);
var id_id = $(this).attr('id');
alert(id_id);
$.ajax({
type: "POST",
url: "edit_query.php",
data:{id: id_id},
success: function() {
alert("Success Input");
and this is my php page to pass.
$id = $_POST['id'];
$sql = mysql_query("select * from user where uid = ".$id."");
$table = mysql_fetch_assoc($sql);
?>

$sql = mysql_query("select * from user where uid = ".$id."");
should be
$sql = mysql_query("select * from user where uid = $id ");
and
var id_id = $(this).attr('id');
alert(id_id);
$.ajax({
type: "POST",
url: "edit_query.php",
data:"id="+id_id,
success: function() {
alert("Success Input");
}

try this
$.post( "edit_query.php", { id: id_id })
.done(function( data ) {
alert( data );
});

try this
edit_query.php
<?php
$id = $_POST['id'];
$sql = mysql_query('SELECT * FROM user WHERE uid = '.$id);
$row = mysql_fetch_assoc();
header('Content-Type: application/json');
echo json_encode($row);
exit;
your.js
$(function(){
var onClick, successHandler;
onClick = function (e) {
e.preventDefault();
$.post('edit_query.php',{id:$(this).attr('id')},successHandler,'json');
};
successHandler = function (json) {alert(json.uid);};
$('.btn_edit').click(onClick);
});

Related

Ajax and PHP : SELECT query database

I have an UI in which the user can add objects (stored as JSON in my database). So, when the user is clicking on a button, it calls the ajax wich calls my php to get the desired JSON code.
The problem is that my ajax returns me "success" but with no JSON code. I don't know where the problem is located.
Here's my JS/AJAX:
var object, objectJson;
var objectName = $(this).attr("attr-lib");
var objectId = $(this).attr("attr-id");
$.ajax({
url: 'scriptObject.php',
type: 'POST',
data: {objectId: objectId},
dataType: 'json',
success: function(response) {
console.log("success");
console.log(response);
}
});
Here's my scriptObject.php:
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result = mysql_query($query);
if($result)
{
if(mysql_num_rows($result) > 0)
{
$objJSON = mysql_fetch_array($result);
$res = array("status"=>"success", "objectJson" => $objJSON['objectJson']);
}
else
{
$res = array("status"=>"error", "message" => "No records found.");
}
}
else
$res = array("status"=>"error", "message" => "Problem in fetching data.");
echo json_encode($res);
[EDIT]
It answers me:
{"status":"error","message":"Problem in fetching data."}
Try following
<script type="text/javascript">
var object, objectJson;
var objectName = $(this).attr("attr-lib");
var objectId = $(this).attr("attr-id");
$.ajax({
url: 'scriptObject.php',
type: 'POST',
dataType : 'json',
data: { objectId: objectId },
success: function(response) {
var json = $.parseJSON(response);
if(json.status == 'error')
console.log(json.message);
else if(json.status == 'success')
console.log(json.objectJson);
}
});
</script>
and in scriptObject.php
<?php
// your database connection goes here
include 'config.php';
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result = mysql_query($query);
if($result)
{
if(mysql_num_rows($result) > 0)
{
$objJSON = mysql_fetch_array($result);
$res = array("status"=>"success", "objectJson" => $objJSON['objectJson']);
}
else
{
$res = array("status"=>"error", "message" => "No records found.");
}
}
else
$res = array("status"=>"error", "message" => "Problem in fetching data.".mysql_error());
echo json_encode($res);
?>
scriptObject.php
if(isset($_POST['objectId']))
{
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result=mysql_query($query);
echo json_encode($result);
die;
}
you are execution the php code inside a function.
how does the compiler or the interpreter know to execute a function inside your php file.
Add dataType to your ajax options
$.ajax({
url: 'scriptObject.php',
type: 'POST',
data: objectId,
dataType : 'json',
success: function(response) {
console.log("success");
console.log(response);
}
});
then your php code
function getObjectJson() {
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result=mysql_query($query);
echo json_encode($result);
}

How to get an array by JSON and how to set this return value to a modal form?

My Ajax code:
$("a#edit").click(function(){
var id = $(this).closest('tr').attr('id');
//alert(id);
$.ajax({
url: 'getdata.php',
type: "POST",
dataType:'JSON',
data: {
id: id,
},
success:function(result){
alert(result);
}
});
});
My php code:
if ($_REQUEST['id'] != "")
{
$id=$_REQUEST['id'];
$sql = "select * from visit_reports WHERE visit_planner_id='$id'";
$query = sqlsrv_query( $link, $sql);
while($data = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC))
{
print_r($data);
}
}
In Firebug, the array I get:
Array
(
[id] => 1.0000
[visit_planner_id] => 230338
[bi_staff_present_name] => BI staff present name
[bi_staff_trial_function] => BI staff trial function
)
How can I use this array value into my specific input field of modal form?
In your PHP code, Why not print JSON instead of array?
echo json_encode($data);
Now, you can parse it easily from your ajax code.
success:function(result){
var json = $.parseJSON(result);
var id = json.id; // 1.0000
var visit_planner_id= json.visit_planner_id; // 230338
// so on..
}

ajax function not working fine

I have a text field in which i am getting a string like that
say name / contact / address
and i get this value on button click function when i pass this value to php function via ajax. it returns nothing, i don't know what is wrong with my code.
here is the ajax function:
$("#load").click(function()
{
//alert("this comes in this");
var data1 = $("#country_id").val();
$.ajax({
alert("ajax start");
url: 'ajax_submit.php',
type: 'Post',
dataType: 'json',
data:{getRespondents:"getRespondents", data:data1},
success: function(e){
alert(e);
$("#rCategory").val(e.respondents[0]['category']);
$("#gender").val(e.respondents[0]['gender']);
$("#rAddress").val(e.respondents[0]['address']);
$("#rContact").val(e.respondents[0]['contact']);
alert("In this");
}
});
});
and in ajax_submit.php function is like that:
if($_POST["getRespondents"] == "getRespondents"){
$regionID= $_POST["data"];
$obj = new controller();
$result = $obj->getRespondents($regionID);
$json = array("respondents"=>$result);
echo json_encode($json);
exit();
}
In class function is written as:
function getRespondents($a){
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("demon", $connection); // Selecting Database
list($number1, $number2, $number3) = explode('/', $a);
//$sql = "SELECT r.id, r.name, r.contact, r.address from respondent as r ORDER BY r.name";
$sql = "SELECT * FROM respondent as r WHERE r.name = '".$number1."' and r.contact = '".$number2."' and r.address = '".$number3."' "
$rsd = mysql_query($sql);
$row= array();
$i=0;
while($rs = mysql_fetch_array($rsd)) {
$row[$i]["id"] = $rs ['id'];
$row[$i]["name"] = $rs ['name'];
$row[$i]["contact"] = $rs ['contact'];
$row[$i]["address"] = $rs ['address'];
$row[$i]["category"] = $rs ['category'];
$row[$i]["gender"] = $rs ['gender'];
$i++;
}
return $row;
}
I want to populate those values in given select boxes when user selects something from autocomplete function.
what are possible soultions to this problem? thanks
First of all why you use alert at the beginning of ajax? remove that alert because it might give you JavaScript error.

best option to get php array variable in Javascript produced by php script that requested through an ajax call

Currently I am trying to create a live search bar that only produce 5 results max and more option if there is over 5 results. So what I have done so far is a jquery ajax script to call a php script that runs asynchronously on key up in textbox I have.
I want to get the php array then I will code it further using javascript.
This is my code now:
Javascript code
<script type="text/javascript">
function find(value)
{
$( "#test" ).empty();
$.ajax({
url: 'searchDb.php',
type: 'POST',
data: {"asyn": value},
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
});
}
</script>
SearchDb PHP code:
<?php
function searchDb($abc, $limit = null){
if (isset($abc) && $abc) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$abc%'";
if($limit !== null){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
$lists = array();
while ( $row = mysql_fetch_assoc($result))
{
$var = "<div>".$row["testa"]."</div>";
array_push($lists, $var);
}
}
return $lists;
}
$abc = $_POST['asyn'];
$limit = 6;
$lala = searchDb($abc);
print_r($lala);
?>
How can I get $lala
Have you considered encoding the PHP array into JSON? So instead of just echoing the array $lala, do:
echo json_encode($lala);
Then, on the Javascript side, you'll use jQuery to parse the json.
var jsonResponse = $.parseJSON(data);
Then you'll be able to use this jsonResponse variable to access the data returned.
You need to read jQuery .ajax and also you must view this answer it's very important for you
$.ajax({
url: 'searchDb.php',
cache: false,
type: 'post'
})
.done(function(html) {
$("#yourClass").append(html);
});
In your searchDb.php use echo and try this code:
function searchDb($str, $limit = null){
$lists = array();
if (isset($str) && !empty($data)) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$data%'";
if(0 < $limit){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
while ( $row = mysql_fetch_assoc($result))
{
$lists[] = "<div>".$row["testa"]."</div>";
}
}
return implode('', $lists);
}
$limit = 6;
$data = searchDb($_POST['asyn'], $limit);
echo $data;
?>
If you dont have or your page searchDb.php dont throw any error, then you just need to echo $lala; and you will get result in success part of your ajax function
ALso in your ajax funciton you have
//you are using data here
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
you must try some thing like this
success: function(data) {
var lala = data;
$( "#test" ).html($lala);
}

Ajax Call Success, Post not actually sent

I have tried removing the JSON.stringify and changing the post to get change cache to false and true. I am at a loss as to what needs to happen. It always goes to the else statement in my php and returns the default JSON. I have allowed crossdomain in my php with the wildcard so that is definitely not the problem.
Code:
$(document).ready(function() {
$('.check').click(function(){
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "POST",
crossDomain: true,
url: "retrieveColumn.php",
data: JSON.stringify({ ID: thisID}),
cache: true,
async:true,
datatype: "json",
success: function(data)
{
console.log(data);
alert(data);
}
});
});
});
PHP which always goes to the else condition:
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = $ID ");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
}
else
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = 2");
$row = $stmt->fetch_assoc();
print json_encode($row);
}
Unless this is part of a larger document, you have unnecessary brackets which might be causing problems.
if(isset($_POST['ID'])){
$ID = $_POST['ID'];
{ /* <!-- HERE! What is this?? */
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = $ID ");
if($stmt->num_rows) //if there is an ID of this name{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
}
else
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = 2");
$row = $stmt->fetch_assoc();
print json_encode($row);
}
You don't need to stringify the object you submit as data here:
data: JSON.stringify({ ID: thisID}),
Use:
data: { ID: thisID},

Categories

Resources