Jquery Json request and callback to html table - php

I habe built a cascading drop down that functions very well. when the form is submitted, the Id is passed to second script. I can´t seem to get the callback function to ...function properly. Don´t know what wrong.
note I updated the code with the suggested changes, but something still goes wrong.
The php:
<?php
if (!empty($_GET['id'])) {
$id = $_GET['id'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=blankett', 'root', 'root');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `forms`
WHERE `id` = '$id'";
$statement = $objDb->prepare($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array();
foreach ($list as $row ) {
$out[] = '<tr><td>'.$row['name_form'].'</td> <td>'.$row['date_added'].'</td></tr>';
}
echo json_encode(array('error' => false, 'list' => $out));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
}else {
echo json_encode(array('error' => true));
}
?>
The Jquery ajax call.
$('#blankett_form').submit(function() {
var id = $(this).find('.update:last').val();
if (id == '') {
alert('Välj land och region.'); //glöm inte bort att ändra beroende på land.
} else {
var table = '<table class="table table-hover table-bordered"><thead><tr><th>blanketter.</th><th>datum tillagt.</th></tr></thead><tbody></tbody></table>'
$('#formsubmit').empty().append(table)
$ajax({
url: 'func/blankett_func2.php',
data: {'id':id},
dataType: 'JSON',
success: function(data)
{
$.each(data.list, function(index, value){
$('#formsubmit tbody').append(value);
});
}
});
return false
});

Replace :
$each(data.out, function(){
var trow = out;
$('#formsubmit tbody').append(trow);
});
With :
$each(data.form, function(i, val){
$('#formsubmit tbody').append(val);
});
as there is no out variable inside the each function, and it looks like you're naming the key form in the returned array ?
In the PHP you are redeclaring the array inside the loop, needs to be:
$out = array();
foreach ($list as $row ) {
$out[] = '<tr><td>'.$row['name_form'].'</td> <td>'.$row['date_added'].'</td></tr>';
}
and there's no need to pass an empty array to execute():
$statement->execute();

You arent sending the data properly, you have to send the id key and the id value e.g.
data: {'id':id},
Also your json output is of the form {"error": false, "form": "html string"} so to access the html string you have to use data.form instead of data.out. So try
$.each(data.form, function(index, value){
$('#formsubmit tbody').append(value);
});

Related

Pass array data inside value="" separated with ':' using AJAX/JSON | PHP, HTML

Is it possible to pass data in aray using AJAX/JSON? Like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."?
This is the sample code.
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
$emp=$row['empno'];
$empno = str_pad(++$emp,7,"0",STR_PAD_LEFT);
echo "<option value='".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."".$empno."'>".$row['departmentname']." : ".$row['jobposition']."</option>";
}
}
I understand that this can work using AJAX, but I don't know how to set it up for array that is only separated with ":"
<script>
$(document).ready(function() {
$("#accounttype").change(function() {
var accounttype = $(this).val();
if(accounttype != "") {
$.ajax({
url:"earnings_amendment-employee_select_title.php",
data:{accounttitleselector:accounttype},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#accounttitleselector").html(resp);
}
});
}
else {
$("#accounttitleselector").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
Thank you.
Add the row data in new array results and return the results in json format using json_encode
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
$emp=$row['empno'];
$empno = str_pad(++$emp,7,"0",STR_PAD_LEFT);
$array[] ="<option value='".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."".$empno."'>".$row['departmentname']." : ".$row['jobposition']."</option>";
}
}
echo json_encode($array);
In jquery after ajax success parse the response with JSON.parse(), and the data becomes a JavaScript object.
//use each loop to get the option data from response
success:function(response) {
var data = JSON.parse(response);
$("#accounttitleselector").html($.each(data, function(index, value) {
value
}))
}
});

e.preventDefault / return false breaks ajax script firing properly

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'];

receive multiple values from db using ajax

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

Div onClick With JSON Call Doesn't Work

I have a search function that calls a php file onkeyup. Now in JQuery i have a onClick function that when you click a div from that same JSON call it alerts something, maybe it will be easier to understand from my code below:
<?php
$Connect = new mysqli("localhost", "root", "", "Data");
$Val = $_POST['Val'];
if($Val)
{
$Search = 'SELECT * FROM Users WHERE ';
$Term = explode(" ", $Val);
foreach($Term as $Key)
{
$I = 0;
$I++;
if($I == 1)
{
$Search .= 'Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
else
{
$Search .= 'OR Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
}
if($Result = $Connect->query($Search))
{
while($Row = $Result->fetch_assoc())
{
$User = $Row['Username'];
$USearch['S'][] = '<div class="Result"><label class="TText" style="cursor:pointer;">' . $User . '</label></div>';
}
}
}
echo json_encode($USearch);
?>
Now, as you can see, once the user types into a box a div shows up showing all LIKE records of Users, once the div is clicked on nothing happens.
$('.Result').click(function()
{
alert('Hi');
});
When the ajax call return a state of success you can use for example the jquery bind method. (see here for more info http://api.jquery.com/bind/ )
function myAjaxFunct(val){
$.ajax(
{
type: "POST",
url: myPhpFile.php,
datatype: "jsonp",
data: {val: val},
success: function (result) {
$("#jsonResultDisplay").text(result);
$('.Result').bind('click', function() {
alert('hi');
});
}
});
}
You are dynamically creating element that is why it doesn't work.
Use on()method.
Check an example:
http://jsfiddle.net/pZQ8T/

passing a javascript variable to a php function and quoting it correctly

Im using Zend Framework ..in one of my phtml file's i have this code
<script>
function foobar(id,type){
var idarray = <?php AppNamespace_General::getparentids( ?>id, type<?php ) ?>; // here the id and type are from js
//the php function returns a json array to the js variable
......
location.href = baseurl +'/somepage/id/'+id;
}
How can i correctly pass the js elements to the php function
The php function(Already thought of doing it via ajax..its quite complex)
public static function getparentids($id, $type, $elmarray = '') {
if (empty($elmarray)) { //avoiding redeclaration of array
$elmarray = array();
}
switch (strtolower($type)) {
case 'group':
case 'product':
case 'specification':
$gp_handler = new PackAssist_Model_DbTable_Groups();
$q = "SELECT * FROM t_groups WHERE group_id = $id";
$sql = $gp_handler->getAdapter()->query($q);
break;
case 'part':
$pt_handler = new PackAssist_Model_DbTable_Parts();
$q = "SELECT * FROM t_parts WHERE part_id = $id";
$sql = $pt_handler->getAdapter()->query($q);
break;
}
$result = $sql->fetchAll();
$i = 0;
if (count($result) > 0) {
foreach ($result as $row) {
if (isset($row['group_parent_id']) && $row['group_parent_id'] != 0) {
if (in_array($row['group_id'], $elmarray)) {
$e = $row['group_parent_id'];
} else if ($row['group_parent_id'] != 0) {
$e = $row['group_id'];
}
} else if (isset($row['part_group_id'])) {
$e = $row['part_group_id'];
} else if ($row['group_parent_id'] == 0) {
break;
}
if (isset($e) && !empty($e)) {
array_push($elmarray, $e);
}
self::getparentids($e, 'group', $elmarray);
$i++;
}
} else {
array_push($elmarray, $id);
}
array_pop($elmarray); //removing the group of super parent group which we dont need
if ($i == 0) { // just encode the array only once
echo json_encode(array_reverse($elmarray));
}
}
If you use jQuery, you can do the following to execute the JSON request:
$.ajax({
type: 'GET',
url: '/path/to/script.php',
data: '{ id: '+id+', type: '+type+' }',
contentType: 'application/json',
dataType: 'json',
success: function(data) {
dataObject = JSON.parse(data);
// process data
},
error: function(e) {
console.log(e.message);
}
});
You can use your existing PHP code with this solution. The url you point to would just have to print the JSON result, as you are currently doing in getparentids().

Categories