How to copy json array variable data to php variable? - php

This is a web page for student results and 3 fields data i.e stu_class, section, exam is sending to controller and a json array data variable is coming back from controller to this page now i wanted to show that json variable's data on the webpage. So help me how to do so?
$(document).ready(function(){
$('#examination').change(function(){
var exam = $('#examination').val();
$('#exam').val(exam);
});
$('#enter').click(function(){
var stu_class = $('#stu_class').val();
var section = $('#section').val();
var exam = $('#examination').val();
$.ajax(
{
type : "POST",
dataType: "json",
url : "<?php echo base_url('index.php/marksheet/student_result_database'); ?>",
data : {
stu_class : stu_class,
section : section,
exam : exam
},
success: function(stu_data)
{
var items = [];
$.each( stu_data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val['student'] + "</li>" );
});
alert(items);
}
});
});
});
And i need to copy the data of stu_data variable of jquery to php variable $stu_data so that i can run a loop to show the values in below fields like this-
<?php foreach($stu_data as $data):
echo $data['id'];
echo $data['student'];
Something like this.
So programmers please help me..!

json_decode($str, true) -> turns a json-object into a php assoc array.
json_decode($str, false) -> turns a json-object into a php object.

Related

Ajax + PHP: null instead of an array

Ajax call is made in the background
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
var data = {elementID: value};
var json = JSON.stringify(data);
$.ajax({
url: 'php/validator_signup.php',
dataType: 'json',
type: 'post',
data: json,
success: function(data){
var parsedResponse = JSON.parse(data);
console.log(parsedResponse);
/*
if(data.response === 1){
$('#'+elementID+'-status').css("background-image", "url(img/signup/no.png)");
}else if(data.response === 0){
$('#'+elementID+'-status').css("background-image", "url(img/signup/yes.png)"); }
*/
}
});
}
}
validator_signup.php received the call. So far in test mode PHP will receive the string, parse it and encode again to return to JS:
$post = $_POST['data'];
$data = json_decode($post, true); //decode as associative array
$details = $data[0];
echo json_encode($details);
JS then needs to print this in console.
I get this:
null
instead of the value which I expect back.
Result is same whether I parse returned data or not.
If I understand it correctly, the problem is on PHP side?
There does not appear to be any value in converting to json when your data is so simple, you can just use a regular js object that jquery will convert to form data.
Also, as both the key and value you send are unknown, i would suggest sending the data in a different structure so its easy to retrieve:
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
$.ajax({
url: 'php/validator_signup.php',
type: 'post',
// ▼key ▼value ▼key ▼value
data: { id: elementID, val: value},
success: function(response){
console.log(response.message);
}
});
}
}
In php you can access the data via $_POST, and as you know the keys, its simple:
<?php
$id = $_POST['id'];
$val = $_POST['val'];
//set correct header, jquery will parse the json for you
header('Content-Type: application/json');
echo json_encode([
'message'=>'Request received with the id of: ' . $id . 'and the value of: ' . $val,
]);
die();
Change:
data: json,
To:
data: { data: json},
This is because you aren't giving the sent data a POST parameter to then be used server side to retrieve it.
Then, you can simply fetch the code server-side like this:
$data = json_decode($_POST['data']);
Hope this helps!
Here, since you are checking whether data is being post, if you see in Network, no data is being posted. To fix it, change this part:
var data = {elementID: value};
To this:
var data = {data: {elementID: value}};
Consider removing conversion of Data
PHP automatically handles the $_POST as an array! So you don't need to use the reconversion. Please eliminate this part:
var json = JSON.stringify(data); // Remove this.
And in the server side:
$data = json_decode($post, true); // Remove this
$data = $_POST['data']; // Change this
Update
OP said data[elementID]:gh is sent to the PHP file.
If this is the case, then if the data needs to be "gh" in JSON, then:
$res = $_POST["elementID"];
die(json_encode(array("response" => $res)));
This will send:
{
"response": "gh"
}
And in the client side, you don't need anything other than this:
$.post('php/validator_signup.php', function (data) {
var parsedResponse = JSON.parse(data);
console.log(data);
});
JSON data is sent to the server as a raw http input it is not associated with query name like $_POST['data'] or anything like that which means you must access the input string not a data post value to do so you need to use
$rawInput = json_decode(file_get_contents('php://input'), true);
$elementValue = $rawInput['elementId'];
thats it
$_POST = json_decode(file_get_contents('php://input'), true);
$data = $_POST['data'];

Submit Form Array Via AJAX

I have a form which I would like to submit via Ajax, however, part of it contains an array. I am having difficulty passing this array via Ajax. An example of my Ajax is below, where I would usually pass the form entry data via how it is below after data (one: $('#one').val()) where I would have one row of this for each field.
Now I have a new set of fields, where the information needs to be passed through as an array. I have tried using serialize and formData -- var fd = new FormData("#form") -- and so far either just this array has been passed through, or nothing from the form is passed through, or just the array is not passed through.
Can anyone please point me in the right direction?
$("#form").submit(
function() {
if (confirm('Are you sure you want to edit this?')) {
$("#formMessages").removeClass().addClass('alert alert-info').html(
'<img src="images/loading.gif" /> Validating....').fadeIn(500);
$.ajax({
url: $("#form").attr('action'),
dataType: 'json',
type: 'POST',
data: {
one: $('#one').val(),
two: $('#two').val()
},
success: function(data){
//success stuff would be here
}
});
}
return false;
});
Thanks.
You could try using :
var dataSend = {};
dataSend['one'] = $('#one').val();
dataSend['two'] = $('#two').val();
dataSend['three'] = $('#three').val();
then in the ajax
data: {dataSend:dataSend}
You can gather data in php with json:
$json = json_encode($_POST['dataSend']);
$json = json_decode($json);
print_r($json);
To see output.
Edit:
You can gather data in php like below:
$one = $json->{'one'};
$two = $json->{'two'};
Have you tried this:
Written in JavaScript:
your_array = JSON.stringify(your_array);
And in PHP:
$array = json_encode($_POST['array']);

Add items into dropdown using ajax/jquery using codeigniter

This may be the duplicate question but I would like to mention that other answers have not solved my problem.
As the question says, I want to populate the dropdown using ajax/jquery. I am able to send and recieve data in the JSON format successfully but it does not append with the dropdown. Following is my code:
View
<select name="guard_id" id="guard_id" style="width:100%;">
<option>select guard</option>
<optgroup label="Previously assigned guard" id="trained_guards">
</optgroup>
</select>
Jquery/Ajax call
function checkTrainedGuards(sid) {
$.ajax({
dataType: 'JSON',
type: 'POST',
url: '<?php print site_url('roster/check_trained_guards'); ?>',
data: { sid: sid},
beforeSend:function() {
// this is where we append a loading image
$('#sid').addClass('loader-roster');
},
success:function(data) {
var appenddata;
$.each(data, function (key, value) {
appenddata += "<option value = '" + value.gid + " '>" + value.gname + " </option>";
});
$('#trained_guards').html(appenddata);
},
error:function(){
// failed request; give feedback to user
}
});
}
Controller
public function check_trained_guards(){
$this->load->model("guard");
$sid=$this->input->post("sid");
$trainedGuards=$this->guard->getGuardAlreadyWorkedOnSite($sid);
foreach ($trainedGuards as $guard) {
print json_encode(array(
'gid' => $guard->gid,
'gname' => $guard->guard_name
));
}
}
}
When I test it using firebug, I an see the data is coming correct and it is in JSON format as shown below:
[{"gid":"293","gname":"Abc"},{"gid":"96","gname":"guard2"},{"gid":"101","gname":"guard3"},{"gid":"91","gname":"guard4"}]
However, I am just wondering why it is not appending the result into dropdown box?
I, Also tested this by alert(value.gid) in the jquery each loop it says undefined.
Any help will be highly appreciated.
You JSON seems to be in wrong format . Your php part should look like follows :
$arr = array();
foreach ($trainedGuards as $guard) {
$arr[] = $guard;
}
print json_encode($arr);
Now this code will return a valid JSON as Follows. JOSN will the array of objects shown below :
[{"gid":"2","gname":"Gurd1"},{"gid":"3","gname":"Guard2"}]
In your ajax response write following code
var data = [{"gid":"2","guard_name":"Gurd1"},{"gid":"3","guard_name":"Guard2"}];
//This is the response format You can also use JSON.parse if its in the string format
var appenddata = "";
$.each(data, function (key, value) {
appenddata += "<option value = '" + value.gid + " '>" + value.gname + " </option>";
});
$('#trained_guards').html(appenddata);

onchange F(x) to php to Highchart on same page

I am continuing a previous question that was asked onclick -> mysql query -> javascript; same page
This is my onchange function for a drop down of names. it is called when each drop down is changed. The idea is to send each runners name into the php page to run a mysql query then return 3 arrays to be entered into javascript.
function sendCharts() {
var awayTeam = document.getElementById('awayRunner').value;
var homeTeam = document.getElementById('homeRunner').value;
if(window.XMLHttpRequest) {
xmlhttp14 = new XMLHttpRequest();
}
else {
xmlhttp14 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp14.onreadystatechange = function() {
if(xmlhttp14.readyState == 4 && xmlhttp14.status == 200) {
var parts = xmlhttp14.responseText.split(','); //THIS IS WHAT IS RETURNED FROM THE MYSQL QUERY. WHEN I ALERT IT, IT OUTPUTS IN THE FORM 14,15,18,16,17,12,13
... code that generates the chart
series: [ {
name: document.getElementById('awayRunner').value,
data: [parts,','], //THIS IS WHERE AN ARRAY MUST BE ENTERED. THIS OUPUTS ONLY ONE NUMBER
type: 'column',
pointStart: 0
//pointInterval
},
{
name: document.getElementById('homeRunner').value,
data: parts, // TRIED THIS
type: 'column',
pointStart: 0
//pointInterval
},
{
name: 'League Avg',
data: [], //THIS IS WHERE 3rd ARRAY MUST BE ENTERED
type:'spline',
pointStart: 0
//pointInterval
},
]
});
}
}
xmlhttp14.open("GET", "getCharts.php?awayRunner="+awayRunner+"&homeRunner="+homeRunner, true);
xmlhttp14.send();
}
my php code looks like this. As you'll see, there are 3 arrays that must be returned to be entered into different spots in the javascript to generate the code.
$away=$_GET['awayRunner'];
$home=$_GET['homeRunner'];
$db=mydb;
$homeRunner=array();
$awayRunner = array();
$totalOverall= array();
$getHome="select column from $db where tmName = '$home'";
$result2 = mysql_query($getHome);
while($row = mysql_fetch_array($result2)){
$homeRunner[]= $row['column'];
}
$getAway="select column from $db where tmName ='$away'";
$result22 = mysql_query($getAway);
while($row2 = mysql_fetch_array($result22)){
$awayRunner[]= $row2['column'];
}
$week = 0;
while($week<20){
$week++;
$teamCount = "select count(column) from $db where week = $week";
$resultTeam = mysql_query($teamCount);
$rowTeam = mysql_fetch_array($resultTeam);
$t = $rowTeam['count(column)'];
$getLeague = "select sum(column) from $db where week = $week";
$resultLeague = mysql_query($getLeague);
while($row3 = mysql_fetch_array($resultLeague)){
$totalOverall[]=$row3['sum(column)']/$t;
}
}
echo join(',',$awayRunner);
currently, by doing it this way, the chart only outputs the second value in the array. for instance, if var parts is equal to 23,25,26,24,23...only 25 is shown.
A previous question resulted with the following answer -
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
I'm lost on #'s 5 - 7. Can someone provide examples of code that gets this done? Normally, I would just ask for direction, but I have been stuck on this problem for days. I'm about ready to scrap the idea of having charts on my site. Thanks in advance
EDIT
this is the first change that I have made to send and receive just one request
<script>
$(function(){
$("#awayRunner").change(function(){
$.ajax({
type: "POST",
data: "data=" + $("#awayRunner").val(),
dataType: "json",
url: "/my.php",
success: function(response){
alert(response);
}
});
});
});
The data displayed in the alertbox is in the form 12,15,16,15. Now, when I enter in
data: response,
only the second number from each is being displayed in the chart. Any ideas?
EDIT
OK, so i figured out that the info in response is a string. It must be converted to an INT using parseInt to be usable in the chart. currently, I have
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayTeam").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var asdf = [];
asdf[0] = parseInt(response[0]);
asdf[1] = parseInt(response[1]);
asdf[2] = parseInt(response[2]);
asdf[3] = parseInt(response[3]);
alert(asdf);
will have to write a function to make this cleaner.
I can't believe it, but I finally got it. here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

How Print json Array in Javascript

PHP: Code:
$category_searchresult = $db->db_query("SELECT category_code, category_name, category_comment FROM qa_categories WHERE ".$search_by." LIKE '%".$search_string."%'");
$i=1;
$qa = array();
while($categories_query_result = mysql_fetch_array($category_searchresult))
{
$qa[$i][] = $categories_query_result['category_code'];
$qa[$i][] = $categories_query_result['category_name'];
$qa[$i][] = $categories_query_result['category_comment'];
$i++;
}
echo json_encode($qa);
JS Code:
$.ajax({
type: "POST",
url: "ajax_js.php",
data: search_data,
cache: false,
success: function(search_result) {
//Print Here
});
Current Output IS from PHP:
{"1":["4BA3CC","Fontaneria","Para la Casa"],"2":["CF0345","Herramientas","Herramients de Hogar"],"3":["1265CA","Luces","Luces de todo tipo"],"4":["4C4C9F","Vidrios","Reflectores de auto"]}
Many Thank's
Add a
dataType: 'json'
to your .ajax() call. That will tell jQuery to decode the JSON string from PHP back into a native Javascript data structure. Alternatively, you can take the data parameter in the success handler and explicitly do the decoding yourself:
success: function(data) {
var data = jquery.parseJSON(data);
}
Not quiet sure what the output should be but this is the code you can use to traverse a json object:
for(var key in search_result) {
var result = search_result[key];
//result is an array, so you can traverse or access each value by the key
// or you can join all the values together
var joinedValues = result.join(' | ');
//joinedValues will be something like '4BA3CC|Fontaneria|Para la Case'
}
You may want to set those values into a container object in the page to diplay them of course.
Hope this helps.

Categories