I am trying to get 2 variables from ajax in php. With one variable its working fine. New to ajax, so I am not sure how will I include a second variable. As of now I am getting the msg_count with out any issues. My ajax script is below:
function addmsg(type, msg) {
$('#msg_count').html(msg);
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "notification/select.php",
async: true,
cache: false,
timeout: 50000,
success: function(data) {
addmsg("new", data);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
};
$(document).ready(function() {
waitForMsg();
});
select.php script is below:
$sql = "SELECT * from notification where tousername='$tousername' and isread = 0";
$result = $con->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$not=$row['notification'];
echo $not;
I am able to pass the $count properly. I need to pass $not also to the ajax. How will I do that?
My edited php script to use it with a WHILE Loop is as follows:
$result= mysqli_query($con,"SELECT * from notification where tousername='$tousername' and isread = 0");
while($row = mysqli_fetch_array($result)) {
$count = $result->num_rows;
$not=$row['notification_msg'];
$res=[];
$res['count'] = $count;
$res['not'] = $not;
echo json_encode($res);
Like #guradio said, set dataType : 'json' inside ajax properties and json_encode data that you want to pass into success block like following code :
$.ajax({
....
....
dataType : 'json', // added here
success : function ( data ) {
// access data from response
// access it using data.count, data.not
console.log(data)
// just called like original code
// passed on result `data`
addmsg( type, data );
// the rest of the code
}
...
});
function addmsg(type, msg){
// access it using msg.count, msg.not
console.log(msg.count)
$('#msg_count').html(msg);
}
In Php :
$sql = "SELECT * from notification where tousername='$tousername' and isread = 0";
$result = $con->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
$not=$row['notification'];
// added here
echo json_encode( array( 'count' => $count, 'not' => $not ) );
Edited : This depend on how you want to store the data and populate it
// defined container outside loop
$res = [];
while($row = mysqli_fetch_array($result)) {
$count = $result->num_rows;
$not=$row['notification_msg'];
array_push( $res, array( 'count' => $count, 'not' => $not ) );
}
echo json_encode($res);
Suggestion(credited to guradio):
Must be noted that, there is not necessary to add async : true inside ajax properties as the default behavior of Ajax is asynchronous and the default value of that is TRUE unless you wanna it to be false, but not recommended.
Related
I am using PHP to retrieve some records from a MySQL database, I would like to send these to my AJAX and loop through them, in order to prepend rows to an existing table.
However I can only see the last (most recent) record returned from my query. Could someone please point out where I am going wrong?
AJAX:
$.ajax({
type: "POST",
url: 'feed.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
console.log(data); // logs `{Direction: "O", CardNo: "02730984", SerialNo: 20559303}`
$.each(data, function(key, value) {
// here I want to loop through the returned results - for example
$("#transactionTable").prepend('<tr><td>'+ SerialNo +'</td><td>'+ CardNo +'</td><td>'+ Direction +'</td></tr>');
});
}
});
feed.php
if(isset($_POST['lastSerial']) && $_POST['lastSerial'] == true) {
$query = "SELECT TimeStamp, Direction, CardNo, SerialNo FROM Transactions";
// this query returns approx. 20 results
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$data["Direction"] = $row['Direction'];
$data["CardNo"] = $row['CardNo'];
$data["SerialNo"] = $row['SerialNo'];
}
echo json_encode($data);
}
Also in my PHP, should I be using a while or if statement?
You're using a single $data object and resetting its contents each time. You want to build an array of objects:
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = array(
"Direction" => $row['Direction'],
"CardNo" => $row['CardNo'],
"SerialNo" => $row['SerialNo']
);
}
echo json_encode($data);
Followed by:
success: function(data) {
$.each(data, function(key, value) {
$("#transactionTable").prepend(
'<tr><td>' + value.SerialNo + '</td>' +
'<td>' + value.CardNo + '</td>' +
'<td>'+ value.Direction +'</td></tr>');
});
}
In your feed.php you loop through the results, but on each loop you overwrite the data. Thus, you are only returning the last result from the database to the AJAX request.
Many solutions exist, but you have to do something like
$data["Direction"][] = $row['Direction'];
$data["CardNo"][] = $row['CardNo'];
$data["SerialNo"][] = $row['SerialNo'];
or better:
$data[] = $row;
Since you dont change the key, you can use the last option. With jQuery you can loop over it, and access the data with value.Direction, value.CardNo, value.SerialNo
note: not tested
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)).
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
This code should be working fine, as far as i can tell but for some reason it's not working. Can somebody please help me?!! T_T
js script:
$.ajax({
type: 'POST',
url: '<?=base_url()?>/folder_name_ajax/unit_vacancy',
dataType: 'json',
data:{unit_id:unit_id, unit_landlord_id:unit_landlord_id, unit_stat:unit_stat},
beforeSend: function(){
},
success: function(response){
console.log(response);
alert('Unit status successfully updated.');
}
});
Controller:
function unit_vacancy()
{
$this->load->model('modelAjax');
$unit_id = mysql_real_escape_string($this->input->post('unit_id'));
$unit_landlord_id = mysql_real_escape_string($this->input->post('unit_landlord_id'));
$unit_stat = mysql_real_escape_string($this->input->post('unit_stat'));
$xplod_stat = explode('-',$unit_stat);
$this->modelAjax->update_unit_vacancy();
}
Model:
function update_unit_vacancy()
{
$unit_id = mysql_real_escape_string($this->input->post('unit_id'));
$unit_landlord_id = mysql_real_escape_string($this->input->post('unit_landlord_id'));
$unit_stat = mysql_real_escape_string($this->input->post('unit_stat'));
$xplod_stat = explode('-',$unit_stat);
$result = $this->db->query("SELECT COUNT(ID) AS count FROM ".TBL_PREFIX."".UNIT_VACANT_TBL." WHERE unit_id = '$unit_id' ");
$count = $result->num_rows();
if($count == 0)
{
$result = $this->db->query("INSERT INTO ".TBL_PREFIX."".UNIT_VACANT_TBL."
(
unit_id,
landlord_id,
status
)
VALUES
(
'$unit_id',
'$unit_landlord_id',
'insert'
)
");
}
else
{
$result = $this->db->query("UPDATE ".TBL_PREFIX."".UNIT_VACANT_TBL."
SET
status = 'update'
WHERE
unit_id = '$unit_id'
");
}
}
I can't seem to understand what i did wrong here!!!
You are not echo(ing) anything in your controller as i see.? Where is your json? Is your update_unit_vacancy() returning the json? If yes then echo it.
echo $this->modelAjax->update_unit_vacancy();
And check your console too for the response of the ajax. Would recomment you one more thing though, change the below line:
url: '<?=base_url()?>index.php/rentdaddy_ajax/unit_vacancy',
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"
)
);