Hi I was trying to get 2 dimensional array from php using ajax ,jquery ,but I am not able to get the response
here is my code
html code
$.ajax({
type: "POST",
url: "get_data.php",
data: "",
dataType: "json",
success: function (json) {
var data = json.msg;
initChart(data);
}
});
php code
header('Content-Type: application/json');
$responce=array();
for($i=0;$i<10;$i++)
{
$responce[]=array($i,$j);
}
echo json_encode(array("msg"=>$responce));
but I am getting message "json is empty " when debugged in Bugzilla
Maybe this is what you mean?
for($i=0;$i<10;$i++) {
for($j=0;$j<10;$j++) {
$responce[]=array($i,$j);
}
}
Try this :
$response = array();
for($i=0; $i<10; $i++) {
$response[$i] = array();
for($j=0; $j<10; $j++) {
$response[$i][$j] = 10 * $i + $j;//Value is just an example. The important part is the left hand side of the assignment.
}
}
Related
$('.guncel').click(function() {
var values = [];
$('.menum').each(function(i, sel) {
var selectedVal = $(sel).val();
values.push(selectedVal);
});
$.ajax({
url: 'islenendata.php', // The PHP file that you want to send
your user input to
type: 'POST',
data: {
data1: values
}, // The data to be sent
dataType: 'text',
success: function(result) {
$("#div1").html(result);
}
});
});
welcome.php ajax data work and result come to #div1 but in islenendata.php
Results not appear this is islenendata.php data not appear in this page
PHP Code:
<?php
$cars = $_POST['data1'];
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x] ;
echo "<br>";
}
?>
Results are going to welcome.php succesful but in islenendata.php nothing appear
So I'm having trouble with passing data using ajax post to php
Here is my jquery :
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat = ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
and here is the php file:
$kodeobat = $_POST['kodeobat'];
$stmt = $db_con->prepare("SELECT kodeobat, hargaobat FROM Obat WHERE kodeobat='".$kodeobat."'");
$stmt->execute();
while($row=$stmt->fetchAll(PDO::FETCH_ASSOC))
{
if($kodeobat == $row['kodeobat']){
echo json_encode($row);
}
}
and it results : Notice: Undefined index: kodeobat in .../getdata.php on line 4 which is this line $kodeobat = $_POST['kodeobat'];
Is there something wrong with the code? Thank youuu :)
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat == ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
Notice if (kodeobat == "")
Try sending your JSON as JSON by using PHP's header() function:
header("Content-Type: application/json", true);
look at this
If you are unaware of what type of value you would get in response here is a try..
$kodeobat = $_POST['kodeobat'];
if(empty($kodeobat)) {
echo("Value is empty");
} else if(is_array($kodeobat)) {
$i = count($kodeobat); //If the value is array iterate it
for($j = 0; $j < $i; $j++) {
echo($kodeobat[$i] . " ");
}
} else if(is_object($kodeobat)){
$json = json_decode($_POST,true); //if it is a json value decode it
$kodeobat_new = $json['kodeobat'];
}
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);
I am a little stuck on how to retrieve all the values from the json array in jquery. I know it needs to be looped but how ? The function -
at the moment is:
$.ajax({
url: 'query.php',
data: "",
dataType: 'json',
success: ajaxfunction
});
function ajaxfunction(json_data){
// problem is below, i need to output all the data from the array
console.log (json_data)
while(json_data){
$('#maindisplay').html("<b>Product: </b>"+json_data.prod_name+"<b> colour: </b>"+json_data.colour); // problem is here, i need to output all the data from the array
}
}
The php:
$result = mysql_query("SELECT * FROM fproduct WHERE fproduct.category='Shirts'");
$elements = array ();
do{
$row=mysql_fetch_array($result);
if ($row) //if there is anything
$elements[] = ($row);
} while($row);
echo json_encode($elements);
You have to iterate over the elements of the array.
function ajaxfunction(json_data){
for (var i = 0; i < json_data.length; i++){
$('#maindisplay').append($("<b>Product: </b>"+json_data[i].prod_name+"<b> colour: </b>"+json_data[i].colour+"<br>"));
}
}
In my ajax code:
$.ajax({
url: CI_ROOT + "isUserExist",
type: "GET",
data: {recepient: recepient},
success: function(r) {
console.log(r)
}
})
Gives me an output [{"records":"1"}][{"records":"1"}] So I parsed it to json by adding dataType: "json" in my ajax code. But when I parsed it, it doesn't give me output but error on try-catch-block.
How do I get it to display as objects?
In my PHP code, I'm doing it this way:
for ($i = 0; $i < count($matches[0]); $i++) {
echo json_encode($this->searchmodel->doesUsersExists($matches[0][$i]));
} //gets the user id of the user from a given string.
Add each entry to an array and then json encode that array, instead of json encoding each one separately. If you only have one call to json_encode, you will get valid JSON:
$result = array();
for ($i = 0; $i < count($matches[0]); $i++) {
$result[] = $this->searchmodel->doesUsersExists($matches[0][$i]);
} //gets the user id of the user from a given string.
echo json_encode($result);
That's not valid JSON. Make an array from your exist results and encode that.