Well i have this php for get the value of mysql.
I get two rows in this query.
include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT
accion_inmediata.accion,
accion_inmediata.responsable,
accion_inmediata.peligro,
accion_inmediata.ambiente,
DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion
FROM
accion_inmediata
WHERE
accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = mysql_fetch_array($result);
echo json_encode($array);
and this is my Jquery code
function traerAcciones(pnc){
$.ajax({
url: 'php_ajax/select_acciones.php?pnc='+pnc,
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function() {
alert(this.accion);
});
}
});
}
when i execute this code the alert show me "undefined".
The $.each loop works fine but the value is the problem.
Please help and sorry for my bad English
Try to pass the value and the Index as parameters, this is how it works:
$.each(data, function(index, value) {
alert( value.accion );
});
Might also be a problem with the data object not containing what you think it does, do a
console.log(index, value);
inside your loop and a
console.log(data);
before the loop and you will see what you have and how to handle it.
Hope it helps!
Currently you are returning the array of your first row only. So to retrieve both you might want to do this:
include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT accion_inmediata.accion, accion_inmediata.responsable, accion_inmediata.peligro, accion_inmediata.ambiente, DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion FROM accion_inmediata WHERE accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = array();
while($row = mysql_fetch_array()):
$array[] = $row;
endwhile;
echo json_encode($array);
Now your jquery should be able to retrieve the data. Also, please avoid using MYSQL_QUERY it's deprecated.
Related
I really thought I would figure this one out but I am stuck.
I only want to get one single result from this PHP file, so I believe it is unescessary to use an array then?
However, I've tried console.log(result) multiple times but I am only recieving "null".
What am I doing wrong?
AJAX:
$.ajax({
url: "includes/getwinner.php",
success: (function (result) {
console.log(result);
})
})
PHP
include("../steamauth/db.php");
$result=mysqli_query($db, "select low_winner from pots");
$row=mysqli_fetch_assoc($result);
echo $row['low_winner'];
Try this:
if ($result = mysqli_query($db, "select low_winner from pots")) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
echo $row["Name"];
}
/* free result set */
mysqli_free_result($result);
}
Use the mysqli_free_result function correctly, docs here.
So, I've been looking for a variety of sources to answer my question the last few day and thus have found nothing that's worked for me. I'll preface this further by saying that in regards to PHP and Javascript I started learning them like a week ago. I also understand that there will likely be better ways to format/write the code I'm about to post so please bear with me! :)
Essentially, I am trying to use a page name play.php in combination with AJAX to echo MYSQL queries back onto the page inside certain page elements.
So the code for main.js which is linked directly to play.php. I've tried about three different way that I've seen in various answers and have not gotten the information I wanted. I either get no response or I get undefined in all of them.
function selectChar(uname, cname)
{
var data = {
username : uname,
charname : cname
};
$.ajax({
data : data,
type : 'Get',
url : 'start.php',
dataType:"json",
success : function (result) {
var data_character = JSON.parse(result);
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
}
});
}
The one above I see most often and the one below I just found earlier today. I get undefined when I attempt to call the array.
function selectChar(uname, cname)
{
$.get("start.php?username="+uname+"&charname="+cname).done(function(data_character){
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
});
}
and finally the PHP code that queries the database and echos the data back.
<?php
$conn = new mysqli($hostname,$username,$dbpassword, $dbname);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_GET['username'];
$charname = $_GET['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
//Send the array back as a JSON object
echo json_encode($result);
?>
I'm not looking for someone to do work for me but I do require some guidance here. What would be an appropriate way to make this work? Is my code terribly incorrect? Am I missing an aspect of this altogether? Please, I would really seriously appreciate any help someone could give me!
P.S. I did just get done reviewing several other similar questions none of which seemed to help. Either there was never a conclusive outcome as to what worked for them or the solution didn't work when I attempted it.
try this:
php get post and return json_encode
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_POST['username'];
$charname = $_POST['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
//Send the array back as a JSON object
echo json_encode($rows);
?>
JS ajax response and request
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
Hey Logan the issue may be with how the AJAX request is being sent. Try adding the processData property to your request and setting it to false. It just means the data won't be read as a query string and it is as raw data.
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
processData: false,
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
I would also try echo json_encode($_POST) to see if the you get the following response back :
{username: "hello", charname: "hl"}
Here i am passing the javascript array values to php using the jquery ajax.now i want to recive the data in php script. how should i do it?
php:
<?php
$list = array
(
//here i want to get the ajax array data
);
$t = time();
$file = fopen("xls/$t-userinput-input.csv","w");
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file); ?>
Jquery:
function arrayPush(val1,val2) {
uservalues.push(val1,val2);
passvalues()
}
function passvalues(){
$.ajax({
type: "POST",
data: {info:uservalues},
url: "write.php",
success: function(msg){
alert("Thankyou")
}
});
}
Because you're POSTing the data, just try with:
$list = $_POST['info'];
First of all, read it from PHP POST variable:
$jsonRawData = $_POST['info']
Next, decode it to have php array - http://php.net/manual/en/function.json-decode.php
$decoded = json_decode($jsonRawData);
You can always peek what's inside PHP variable with var_dump.
I have some URL mysite.com/json.php, which returns something like this : [{"invoice_number":"INV#20101"}]
on another page I have a <input type="hidden" id="myinvoice" />
I just wanted to set that invoice_number value to this hidden field withJQuery. How can I do this?
on JSON page I have converted JSON with this code :
<?php
$return_arr = array();
$fetch = mysql_query("SELECT invoice_number FROM db_stocks ORDER BY stock_id DESC LIMIT 1 ");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['invoice_number'] = $row['invoice_number'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
You can use jQuery.ajax() to get the returned array then set the value.
$.ajax({
url: "json.php",
success: function(data) {
$("#myinvoice").val(data[0].invoice_number);
}
});
You can use the following jquery:
$.get('mysite.com/json.php', function(data){
$('#myinvoice').val(data[0].invoice_number);
} 'json');
Also please don't use mysql but use pdo or mysqli instead, see why-shouldnt-i-use-mysql-functions-in-php for more information about this.
I met some trouble in my ajax request.
In fact I do not know how to ou many records.
I've tried this :
$rqt = "SELECT a,b,c from table";
$res = mysql_query($rqt);
while ($data = mysql_fetch_assoc($res)):
$objet = $data;
endwhile;
//requettage
return $objet;
but it out to php only one rows even if I have many records in database.
Second trouble is for display that records.
I've tried this in jquery
$.ajax({
type: "POST",
url: "requetes_ajax/fetch_debours_detail.json.php",
data: "groupe="+groupe_debours,
success: function(data){
$('.remove').remove()
console.log(data);
$.each(data, function (key, value) {
$('#fetchdebours tr:last').after('<tr class="remove"><td>'+data.libelle_debours+'</td><td>'+data.date+'</td><td>'+data.debours_montant_ht_tva+'</td><td>'+data.debours_montant_ht_no_tva+'</td><td>'+data.debours_montant_ttc+'</td></tr>')
//alert(key + ': ' + value);
});
}
});
for that things the trouble I have is that instead of displaying all records in one row, it fill all items horizontally and also vertically so I have as many rows as I have column.
Anykind of help will be much appeciated
In the while loop you are forever replacing the $objet variable with the latest row, so in the end the latest row is all what you get.
To build an array, use this code:
$objet = array();
while ($data = mysql_fetch_assoc($res)):
$objet[] = $data;
endwhile;
To pass the data as JSON you should first declare dataType: "json" in your $.ajax call. The second step is to actually output the PHP array as JSON. Try the following code:
$json = json_encode($objet);
print($json);
Since now you are passing an entire array instead of just one object, your display code needs a small adjustment:
$.each(data, function (k, obj) {
$('#fetchdebours tr:last').after('<tr class="remove"><td>' + obj.libelle_debours + '</td> ... </tr>')
});
I haven't tested the code, use with caution.
From the syntax of you ajax request, you want json to comeback as a response, try this:
$rqt = "SELECT a,b,c from table";
$res = mysql_query($rqt);
$data = mysql_fetch_assoc($res);
return json_encode($data);
see json_encode
requires PHP >= 5.2.0