I have categories and I want to display the categories with my dropdown when I click on the dropdown.
This approach does'nt work. What are the elements than I need to change inside the code ?
Thank you
my ajax php
$Qcheck = $OSCOM_Db->prepare('select distinct categories_id as id,
categories_name as name
from :table_catogories
');
$Qcheck->execute();
$list = $Qcheck->rowCount() ;
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
now my files
<?php
$categories_ajax = OSCOM::link('categories_ajax.php');
?>
<script type="text/javascript">
function myAjax() {
$("#myAjax").on('click', function(){
$.ajax({
url: '<?php echo $categories_ajax; ?>',
dataType: 'json',
success: function(data){
//data returned from php
}
});
)};
</script>
// my dropdown
<?php echo HTML::selectMenu('move_to_category_id', CategoriesAdmin::getCategoryTree(), 'onclick="myAjax()"') . HTML::hiddenField('current_category_id', $current_category_id); ?>
note CategoriesAdmin::getCategoryTree() display the categories name. it's an array
my dropdown function element
public static function selectMenu($name, array $values, $default = null, $parameters = '', $required = false, $class = 'form-control') {}
Related
I have a slight problem with my code, lets say i have a json like this one :
[{"img":"john.png","name":"John","username":"#john"},
{"img":"mark.png","name":"mark","username":"#mark"}]
I wanna get data organized like :
John #john john.png
Mark #mark mark.png
But every time the data comes out like this:
John Mark #john #mark john.png mark.png
This is my Php Code:
<?php
class search{
public function gettingvalues($search_value){
require_once('conx.php');
$dir = "usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
$results[] = $json;
}
echo json_encode($results);
}
}
}
}
?>
This the index code:
<?php
if (isset($_POST['data'])) {
require('search.php');
$search = new search;
$search->gettingvalues($_POST['data']);
header('Content-Type: application/json; charset=utf-8');
die();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data) {
var img = [];
var username = [];
var name = [];
$.each(json_data, function(index, element) {
img.push(element.img);
username.push(element.username);
name.push(element.name);
})
$('#feedback').html('');
$('#feedback').html(name+username+img);
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
Actually this is my first time with json, i don't know what is the problem or maybe i missed something, I hope getting some answers.
You need to build the HTML in the order that you want it displayed.
var html = '';
$.each(json_data, function(index, element) {
html += `${element.name} ${element.username} ${element.img}<br>`;
}
$("#feedback").html(html);
I'm trying to incorporate the jquery sortable functionality into my website and saving the positions in the database is giving me all sorts of headaches... I've been fighting this for 3 days now, and I cannot seem to get this work properly.
As it stands, it is saving positions to the database, but not in the order or positions, that you'd expect. Meaning, if I move the item in position 0 to position 1, it saves the positions in a different order in the db. check out a live version here.
Here is my code...
index.php file:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while($items = $result->fetch_assoc()) {
?>
<div id='sort_<?php echo$items['position'] ?>' class='items'>
<span>☰</span> <?php echo$items['description'] ?>
</div>
<?php
}
}
?>
</div>
js.js file:
$("#container").sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: {positions: post, id: itId },
dataType: 'json',
cache: false,
success: function(output) {
// console.log('success -> ' + output);
},
error: function(output) {
// console.log('fail -> ' + output);
}
});
}
});
$("#container").disableSelection();
save.php file:
require_once('conn.php');
$itId = $_POST['id'];
$orderArr = $_POST['positions'];
$arr = array();
$orderArr = parse_str($orderArr, $arr);
$combine = implode(', ', $arr['sort']);
$getIds = "SELECT id FROM items WHERE groupId = '$itId' ";
$result = mysqli_query($db, $getIds);
foreach($arr['sort'] as $a) {
$row = $result->fetch_assoc();
$sql = " UPDATE items
SET position = '$a'
WHERE id = '{$row['id']}' ";
mysqli_query($db, $sql);
}
echo json_encode( ($arr['sort']) );
Can anyone please point to where I am going wrong on this?
Thank you in advance.
Serge
In case someone lands on here, here is what worked in my case...
NOTE: I did not create prepared statements in the index.php select function. But you probably should.
index.php file:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while( $items = $result->fetch_assoc() ){
?>
<div id='sort_<?php echo $items['id'] ?>' class='items'>
<span>☰</span> <?php echo $items['description'] ?>
</div>
<?php
}
}
?>
</div>
jquery sortable file:
var ul_sortable = $('#container');
ul_sortable.sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var post = ul_sortable.sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: post,
dataType: 'json',
cache: false,
success: function(output) {
console.log('success -> ' + output);
},
error: function(output) {
console.log('fail -> ' + output);
}
});
}
});
ul_sortable.disableSelection();
update php file:
$isNum = false;
foreach( $_POST['sort'] as $key => $value ) {
if ( ctype_digit($value) ) {
$isNum = true;
} else {
$isNum = false;
}
}
if( isset($_POST) && $isNum == true ){
require_once('conn.php');
$orderArr = $_POST['sort'];
$order = 0;
if ($stmt = $db->prepare(" UPDATE items SET position = ? WHERE id=? ")) {
foreach ( $orderArr as $item) {
$stmt->bind_param("ii", $order, $item);
$stmt->execute();
$order++;
}
$stmt->close();
}
echo json_encode( $orderArr );
$db->close();
}
Change your JS code like this:
{...}
tolerance: 'pointer',
cursor: 'move',
// new LINE
items: '.items', // <---- this is the new line
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize'); // it could be removed
// new LINES start
var post={},count=0;
$(this).children('.items').each(function(){
post[++count]=$(this).attr('id');
});
// new LINES end
$.ajax({
{...}
With this $.each loop you overwrite your var post -> serialize and define your own sort order. Now look at your $_POST["positions"] with PHP print_r($_POST["positions"]); and you have your positions in your own order.
I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];
Here is my ajax function in response I am getting result but I don't know how to set that response in my page. Is it possible with json_decode or I have to try something else
JSON file is
<?php
$group_id = $_POST['group_id'];
$query = "SELECT *,group_id FROM contact JOIN addressgroup ON addressgroup.contact_id = contact.contact_id WHERE group_id IN (".$group_id.") GROUP BY contact.contact_id";
$res = mysql_query($query);
$data = array();
$k=0;
while($row = mysql_fetch_array($res))
{
$data[$k][0] = $row['user_id'];
$data[$k][1] = $row['first_name'];
$data[$k][2] = $row['middle_name'];
$data[$k][3] = $row['last_name'];
$k++;
}
echo json_encode(array($data));
?>
AJAX function
var myarray;
function getcon() {
myarray = [];
myarray.push($(".group_id").val());
$.ajax({
dataType: "json",
type: "POST",
url: "getcon.php",
data: 'group_id=' + myarray.join(),
success: function(data) {
totalRecords=data.length;
zone.fnClearTable();
for(var i=0; i < (data.length); i++) {
zone.fnAddData([
data[k][0],
data[k][1],
data[k][2],
data[k][3],
]);
}
return false;
}
});
return false;
}
As your Response is an JSON object..
you have to use it like this:-
replace
echo json_encode(array($data));
by
echo json_encode($data); /* because $data is already an array*/
and keep it same as it was earlier
while($row = mysql_fetch_array($res))
{
$data[] = $row['user_id'];
$data[] = $row['first_name'];
$data[] = $row['middle_name'];
$data[] = $row['last_name'];
$k++;
}
<script>
var myarray;
function getcon() {
myarray = [];
myarray.push($(".group_id").val());
$.ajax({
dataType: "json",
type: "POST",
url: "getcon.php",
data: 'group_id=' + myarray.join(),
success: function(data) {
console.log(data)/* check the structure of data here*/
zone.fnClearTable();
zone.fnAddData([
data.user_id.,
data.first_name,
data.middle_name,
data.last_name,
]);
return false;
}
});
return false;
}
</script>
JSON is an object! Your are getting object, so in your ajax function You must use some loop function like for or $.each JQuery functions.
`success : function (data) {
$.each (data,function(key,val){
$("#someId).html(key + " - " + val)
}
}`
i know how to validate form using it for 1 field. But i would like enter code and take back multiple values from my db. exmp: price, quantity etc.
It is posible to do using ajac?
php file:
$sql = "SELECT * FROM database WHERE code='$field_code'";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$query=sqlsrv_query($conn, $sql, $params, $options);
$row = sqlsrv_fetch_array($query);
if ($row == true)
{
$code = ($row['code']);
$life = ($row['life']);
$agree = ($row['agree']);
}
echo $code;
echo $life;
echo $agree;
?>
And script is:
$("#field_code").change(function() {
$("#message").html("<img src='pictures/ajax_loader.gif' width='26px' height='26px' /> checking...");
var data1 = $("#field_code").val();
$.ajax({
type: 'POST',
url: 'validation.php',
data: $('form').serialize(),
success: function validate(code) {
if (data == ? ) {
to do something
} else {
to do something
}
How to receive all 3 values from php file?
}
})
you need to use json encode for this
$values[]= array('code'=>$row['code'],
'life'=>$row['life'],
'agree'=>$row['agree']);
echo json_encode($values);
and in ajax
var data = jQuery.parseJSON(data);
and access values like data.life,data.code and data.agree