receive multiple values from db using ajax - php

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

Related

Get php id with ajax?

$.ajax({
url: "salvar.php",
type: "post",
async: false,
dataType : "html",
data: {
"feito": 1,
"id": id,
"html": html,
"css": css,
"js": js
},
success: function(data) {
alert(data.id);
}
});
I am using the following code made in ajax to send data to the php page doing the processing along with the database.
<?php
require_once 'banco/conexao.php';
if(isset($_POST['feito'])){
$id_setado = $_POST["id"];
if($id_setado === ''){
$id = base_convert(time(), 10, 36);
$busca = mysqli_query($conn,"SELECT id FROM codigos WHERE id = '$id'");
$buscaId = mysqli_fetch_array($busca);
if ($buscaId == false) {
$html = base64_encode($_POST['html']);
$css = base64_encode($_POST['css']);
$js = base64_encode($_POST['js']);
$inserir = mysqli_query($conn,"INSERT INTO codigos (id,html,css,js) VALUES ('$id','$html','$css','$js')");
}
}else{
$id = $id_setado;
$html = base64_encode($_POST['html']);
$css = base64_encode($_POST['css']);
$js = base64_encode($_POST['js']);
$atualizar = mysqli_query($conn,"UPDATE codigos SET html='$html',css='$css',js='$js' WHERE id = '$id'");
}
}
?>
What I would like is to know how I can get the $id that receives base_convert(time(), 10, 36); in the "success" response of ajax. Specifically this data that I want. How can I get this php variable with ajax?
Use echo to get the value of $id
echo $id

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

How to pass mysql result as jSON via ajax

I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);

PHP pass multiple parameters on success in ajax call

I am doing this ajax call
<script>
function reserveSeat(showID) {
$.ajax({
url: 'reserve_seat.php',
type: 'post',
data: { "showID": showID}
}).done(function(data) {
var booked_seats = JSON.parse( data1, data2, data3 ); //get multiple values
console.log(booked_seats);
});
};
</script>
and in my reserve_seat.php I want to pass multiple echo
$query = "SELECT * FROM `seats` WHERE show_id='" . $_POST['showID'] ."'";
$result = mysql_query($query);
if($result){
$booked_seats = array();
while($row = mysql_fetch_array($result)){
array_push ($booked_seats, array($row['id'], $row['row_no'], $row['col_no']));
}
echo json_encode($booked_seats, var2, var3); //echo multiple variable
} else {
echo mysql_error();
}
What I want is commented in the above code. How can I do this?
Change your echo line to :
echo json_encode(array("booked_seats" => $booked_seats, "var2" => $var2, "var3" => $var3);
And in your ajax
function(data) {
var arr = JSON.parse( data );
var booked_seats = arr["booked_seats"];
console.log(booked_seats);
}
Why don't you just print the encoded JSON output?
Not to mention json_encode() requires an array as said by other posters
json_encode() PHP Manual
use array in side
json_encode(array($booked_seats, var2, var3)).

jQuery AJAX call to a database query

I have an AJAX function as so:
function admin_check_fn(type)
{
//$("#notice_div").show();
//var allform = $('form#all').serialize();
$.ajax({
type: "POST",
//async: false,
url: "<?php bloginfo('template_url'); ?>/profile/adminquery_check.php",
data: { type: type },
//data: 'code='+code+'&userid='+userid,
dataType: "json",
//dataType: "html",
success: function(result){
var allresult = result.res
$('#result').html( allresult );
alert(allresult);
//$("#notice_div").hide();
}
})
}
And server-side:
$queryy="SELECT * FROM wp_users";
$name = array();
$resultt=mysql_query($queryy) or die(mysql_error()); ?>
<?php while($rowss=mysql_fetch_array($resultt)){
$name = $rowss['display_name'];
}
echo json_encode( array(
"res" => array($rowss['display_name']),
"fvdfvv" => "sdfsd"
)
);
Basically for some reason it is not displaying all of the returned values from the query to the users table in the database. It works when I query another table with just one entry in it, so im thinking it could be something to do with the fact there is an array it is not parsing correctly?
Just wondered if anyone else has came accross this problem?
Thanks
Your ajax success is treating the returned data as html but it is json.
var allresult = result.res
/* assumes allResult is html and can be inserted in DOM*/
$('#result').html( allresult );
You need to parse the json to create the html, or return html from server
Also php loop:
$name = $rowss['display_name'];
Should be more like:
$name[] = $rowss['display_name'];
You always overwrite the name:
<?php while($rowss=mysql_fetch_array($resultt)) {
$name = $rowss['display_name'];
}
But this part is not within your loop:
"res" => array($rowss['display_name']),
Therefore you only get one result (the last one).
Smamatti has a good point.
To fix this:
<?php
$query = "SELECT * FROM wp_users";
$names = array();
$result = mysql_query($query) or die(mysql_error());
while( $rows = mysql_fetch_array( $result ) ){
$names[] = $rows['display_name'];
}
echo json_encode( array(
"res" => $names,
"fvdfvv" => "sdfsd"
)
);

Categories