How do i send a 2d array with ajax? - php

I am currently trying to send a 2d array that i receive from a database (sql, phpmyadmin) with ajax.
My ajax function looks like this: (it is generated in php)
$.ajax({
type: \"POST\",
url: \"resultQuizGet.php\",
data: \"getAnswer=\"+question+\"\", //question is just a int variable
success: function(msg) {
alert(\"Data Saved: \" + msg);
}
});
my resultQuizGet.php file then look like
$sql = "SELECT `quiz`.question,`quiz`.rightAnswer
FROM `quiz`
WHERE `quiz`.quizID=:qID";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":qID", $_POST['quiz']);
$stmt->execute();
$resultsQuiz = $stmt->fetchAll();
echo ...
What do i have to do now to receive a 2d array instead of just a normal string.
What i would like to the msg variable to be is a 2d array that is equal to $resultsQuiz

Modify your php as follows, to output the data as a json formatted string:
$sql = "SELECT `quiz`.question,`quiz`.rightAnswer
FROM `quiz`
WHERE `quiz`.quizID=:qID";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":qID", $_POST['quiz']);
$stmt->execute();
$resultsQuiz = $stmt->fetchAll();
echo json_encode($resultsQuiz);
Then, modify your jQuery as follow to parse that structured string back into an array / object:
$.ajax({
type: "POST",
url: "resultQuizGet.php",
data: "getAnswer="+question, //question is just a int variable
success: function(msg) {
// Note: if it's not json, this can cause a problem
var data = $.parseJSON(msg);
// output to your console so you can see the structure
console.log(data);
// Utilize the data somehow
$.each(data, function(key, arr) {
// Arr should contain an object / array representing the rows from your php results
console.log(arr);
// If your row has a field titled `question`, you can access it one of two ways:
alert(arr.question); // Object notation
alert(arr['question']); // Array notation
});
}
});

Related

How to retrieve an array from an AJAX call?

I make an Ajax call that needs to return (after success:...) a multidimensional array representing an SQL query :
$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
data: {action: this.title},
type: 'post',
success: function(data) {
//I need to use the data array here.
});
Here is the method that is called :
<?php
$bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');
$req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");
$data = ... //Here I need to transform the previous request into a multidimensional array.
//For exemple data[3][2] will contain the value within the third row of the second column
echo $data; //returning the array
}
Thanks
Problem
You are trying to return am array. But as AJAX calls works on HTTP protocol, you can transfer only text, normally. So your ajaxmethod.php will print the array and the rendered page i.e. the text will be returned as it is displayed, not an array.
Solution
Convert the array into a JSON object using json_encode() (PHP) andreturn that. Then decode it on the page that made the ajax call, using JSON.parse() (JavaScript). This will give an array.
Code
$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
data: {action: this.title},
type: 'post',
success: function(data) {
//I need to use the data array here.
var array = JSON.parse(data); //This is the array you want
});
...
<?php
$bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');
$req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");
$data = ... //Here I need to transform the previous request into a multidimensional array.
//For exemple data[3][2] will contain the value within the third row of the second column
echo json_encode($data) //returning the array
}
You cant just echo an array (you can't, it an array not a simple value).
Luckily, there is a thing called JSON. In PHP you store all the information you want (in this case, your rows from the DB) in a large array and then you do echo json_encode($array);.
At the Javascript side you change the $.ajax to $.getJSON so that jQuery also understands that we're talking about JSON, et voila, you have a nice javascript version of your PHP array.
// I am not familiar with PDO, but something along these lines:
$allData = $req->fetchAll();
echo json_encode($allData); // Now you output a JSON version of the array
And then javascript
$.getJSON(
'http://localhost/Project/ajaxmethod.php',
{action: this.title},
function(response) {
// And in 'response' you now have a ready to use JS object)
console.log(response);
});
*You can also use $.ajax() if you really want to, just add a dataType: 'json

How to split data while loop data in php and pass to ajax html with different id's

I have db table of doctors nearly more than 100 doctors list in it, Here is my PHP code for doctors dc.php :
$conn= mysqli_connect('localhost', 'root', '', 'test');
$query = mysqli_query($conn, "select * from doctors");
while($result=mysqli_fetch_array($query)){
$dc_name = $result['name'];
$dc_img = $result['image'];
$dc_email = $result['email'];
echo $dc_name."||".$dc_img."||".$dc_email;
}
I want echo all doctors another main page index which already fixed large layout with bootstrap,html,css by using ajax calling on click
Here is my code for ajax
$(function(){
$(".divscrolla").on("click", function(){
$.ajax({
url:'db.php',
type:'POST',
data:{"data":$(this).val()},
success:function(data){
var splitted = data.split("||");
$("#result_name").html.splitted[0];
$("#result_img").html.splitted[1];
$("#result_email").html.splitted[2];
}
});
});
Here I want display all 100 records by AJAX
But here I am getting only first element only, but I have more 100 records in database.
How can I solve by simplifying this?
Did you try
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
$jsonstring = json_encode($resultArray);
echo $jsonstring;
And then in the AJAX code don't split, let the json format help you. By setting the data type to json dataType: "json",
$(function(){
$(".divscrolla").on("click", function(){
$.ajax({
dataType : "json",
url:'db.php',
type:'POST',
data:{"data":$(this).val()},
success:function(data){
//consume the data in a assoc array manner
//data[0]['name'] for first entry's name
}
});
});
}

How can I create a JSON object dynamically?

I would like to create a JSON object dynamically. The JSON object will have to be as the follows:
{
$capa:[$fila['test_name'],...etc],
.
.
.etc
};
The key and value will be retrieved through a MySQL query.
This is what i'm doing:
$array_container= array();
while($fila=mysqli_fetch_assoc($sql)){
$format_org=str_replace(" ","_",$fila["organization"]);
$format_eval=str_replace(" ","_",$fila["EvaluationType"]);
$format_test=str_replace(" ","_",$fila["test_name"]);
$CapaEnviar=$format_org.$format_eval;
$array_container[] = array($CapaEnviar => $fila['test_name']);
}
echo json_encode($array_container,true);
Using the previous code, I can retrieve a JSON object with duplicate keys.
This code is an answer for an AJAX request, so once the JSON object has been created correctly, I will send back this JSON object in order to retrieve the key and value, so I will have to retrieve separately the key and value.
From your comment,
...the results of this array is as the follows: [{"TEST1":"valueT1"},{"TEST1":"otherValue"}] and what i'm looking for is to have a json like this: [{"TEST1":['valueT1','otherValue']}] as you can see, i want to avoid duplicates keys.
Solution:
In your while loop, change this line
$array_container[] = array($CapaEnviar => $fila['test_name']);
to
$array_container[$CapaEnviar][] = $fila['test_name'];
Update:
how i can retrieve this key and their values through ajax?
Since you're expecting a json object from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, loop through the json result to get (key, value) pairs
Here's the reference:
jQuery.ajax()
So your AJAX skeleton code should be like this:
$.ajax({
type: 'POST',
url: 'yourpage.php',
dataType: 'json',
cache: 'false',
beforeSend: function(){
},
success: function(data){
$.each(data, function(key, value) {
alert("Key:" + key + ", value: " + value);
});
},
error: function(){
// error
}
});

jquery ajax don't get more than one value from php script

I try to use jQuery ajax call to retrive some data via php script.
Script take from mysql table all values of column 'rezhour' what also based on $_GET variable.
Then he print all finded values via json_encode() function
PHP:
<?php
header('Content-type: application/json');
$fromdate = $_GET['fromdate'];
$getrezhiredh = mysql_query("
SELECT rezhour FROM rezhiredhours
WHERE rezdate = '".$fromdate."' ORDER BY rezhour
");
$i=0;
$data = array();
while($row = mysql_fetch_array($getrezhiredh)){
$data['hours'][$i] = $row['rezhour'];
$i++;
}
$result = array(
$data
);
print json_encode($result);
?>
When script is called from browser adress bar all is fine and in we have correct result as below:
[{"hours":["2","9","13","14"]}]
Each digit in result above corresponds selected table row.
The problem is when i want to do the same via ajax.
jQuery:
<script>
var date = jQuery('input').val()
jQuery.ajax({
type: "GET",
dataType: "html",
data: "fromdate="+date,
url: "script.php",
success: function (data) {
console.log(data);
},
});
</script>
Now all is fine only when mysql query return result with one row and this looks in console like this:
[{"hours":["1"]}]
When mysql query return result with more than one row console show this:
[[]]
For me is really weird that jquery ajax call have problem to print correct result when we have more than one rows with selected data.
What i must do to have the same result in AJAX?
EDIT:
I found an important clue. The problem is WHERE clause in MYSQL query. When u remove from query this clause, php script return data from entire table and now ajax can print into console all selected values from specifed column.
The problem is i must use WHERE clause to load only data from before selected date at the website. Any idea how to do this?
If you want to return json data ,must use dataType:json. Valid data format is data :{key:value},...
var date = jQuery('input').val();
jQuery.ajax({
type: "GET",
dataType: "json",
data: {fromdate : date },
url: "script.php",
success: function (data) {
console.log(data);
},
});

Splitting a JSON Array with JQuery that has been returned by PHP

I am new to JQuery and the whole JQuery to PHP back to JQuery process.
So i have a simple ajax JQuery script:
$.ajax({
type: "POST",
url: "includes/calc.php",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
This goes to a PHP script and then I return a value, using a simple echo
echo $newprice;
The success function above uses this as 'data'. This all works and is fine.
But what if I want to return more than one value.
I think I can used json_encode();
As I understand it something like:
$dataset = array($var1, var2, var3);
echo json_encode($dataset);
But say I have two values, how do i put them both into the JSON and then how do I split them on the other end.
So say 'data' is an array, how do I tell JQuery to split it?
Sorry if this is simple
If you specify the dataType option for .ajax() as json, jQuery will automatically parse the JSON string returned by the call into an appropriate javascript object/array.
So your call might look like this:
$.ajax({
type: "POST",
url: "includes/calc.php",
dataType: "json",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
Now, let's say the response from your PHP script is a JSON string representing an object like this:
{"key1":"value1","key2":"value2"}
In your success handler you can simply access this as an object like this:
success: function(data){
alert(data.key1);
alert(data.key2);
}
Or, if the returned JSON string represents an array like this:
["value1","value2"]
Then you can access the array values in the success handler like this:
success: function(data){
alert(data[0]);
alert(data[1]);
}
If you do not want to add the dataType option, you can also opt to manually parse the returned JSON string into an object/array like this:
success: function(data){
var dataObj = JSON.parse(data);
alert(dataObj.key1);
alert(dataObj.key2);
}
$.ajax({
type: "POST",
url: "includes/calc.php",
datatype : 'json',
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data.firstvalue);
alert(data.secondvalue);
}
})
please look at that datatype. now the respose need to be json.
In your php user json_encode instead of echo.
$firstvalue = 'your first value';
$secondvalue = 'your second value';
echo json_encode(array('firstvalue' => $firstvalue,'secondvalue' => $secondvalue));
There are many ways to organize data in a JSON object. The simplest is to return a linear array of strings or numbers. Use http://jsonlint.com/ to test your data to see if it's valid JSON, or just feed a PHP array (linear or associative) into json_encode.
If data is a JSON linear array, you can treat it like any other JavaScript array in your success callback:
var first = data[0]; // first element
var second = data[1]; // second element
implode your php variables with a symbol or any custom data
like
$var[0] = '1st variable';
$var[1] = '2nd variable';
$var[2] = '3rd variable';
echo implode('_SPLIT_',$var);
Now in jquery success function
split the response with 'SPLIT'
as
var response = data.responseText.split('_SPLIT_');
var variable1 = response[0];
var variable2 = response[1];
var variable3 = response[2];
and assign as your wish

Categories