How do I get two arrays in Ajax call? - javascript

JS CODE:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
}
});
PHP CODE:
<?php
$username = "trainerapp";
$password = "password";
$hostname = "localhost";
$link = #mysql_connect($hostname, $username, $password);
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator where availability_status in (1,2)");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
$j = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$j]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$j]['firstname'] = $row1['firstname'];
$traineravaildetails[$j]['lastname'] = $row1['lastname'];
$traineravaildetails[$j]['emailidvalue'] = $row1['email_id'];
$j++;
}
echo json_encode(array('result1'=>$trainerdetails,'result2'=>$traineravaildetails));
}
?>
Please help me with the code in the ajax success function area. I've tried using initChart2 but I get an error which says initChart2 is not defined. I don't seem to understand of how to get two arrays from PHP in ajax since I'm a newbie ajax. If someone can help me with the code along with explanation, it'd be great. And I also need to know how to differentiate outputs in ajax which are sent from PHP.

You have two choices:
First one is to simply parse received (text) data to JSON:
var jsonData = JSON.parse(data);
// or simply data = JSON.parse(data);
But the best one in my oppinion is to specify json dataType to the $.ajax() request:
$.ajax(
data: {action:'test'},
type: 'post',
dataType: 'json',
success: function(data) {
...
}
});
This way, $.ajax() will also check for the validity of the received JSON data and error callback will be called instead of success one in case of wrong JSON data received.
...also is important to note you missed to send the json content-type header in your php with:
header("Content-Type: application/json");
Sending this header the dataType: 'json' parameter is no longer (strictly) necessary because $.ajax() guesses it by default attending to the received content-type. But, personally, I prefer to do both.
See $.ajax() documentation.

You forgot:
header("Content-Type: application/json");
… in your PHP.
While you are outputting JSON, you are telling the browser that it is HTML (which is the default for PHP) so jQuery isn't converting it to a useful data structure.
Add that and then you should be able to access data.result1 and data.result2.

To get ajax data:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
data.result1;
data.result2;
}
});
You can use console.log(data); to view data structure

Related

Jquery ajax with JSON return can't access to data inside the JSON

So I have this jquery code:
$(function(){
var url = 'template/traitComTest.php';
window.onload = function(e) {
// $(".formCom").ajaxForm({url: 'template/traitComTest.php', type: 'post'});
$.ajax({
type: "POST",
url: url,
data: $( ".formCom").serializeArray(),
success: function(reponse){
console.log(reponse);
}
});
}
});
with this php code:
if (isset($_REQUEST)) {
$adresse = $_POST['adresse'];
$com = $_POST['commentaire'];
$sql = $bdd->prepare('UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem ');
$sql->execute(array(
":com" => $com,
":exem" => $adresse
));
$myData1 = array('result' => $sql);
echo json_encode($myData1);
$sql->closeCursor();
$sqlSelect = $bdd->prepare("SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp");
$sqlSelect->execute(array(
":exemp" => $adresse
));
$myData = array('result1' => $sqlSelect);
echo json_encode($myData);
}
I get this response from ajax on chrome' console =>
{"result":{"queryString":"UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem "}}{"result1":{"queryString":"SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp"}}
and my issue is that I can't access to the data inside the json and need your help
Ok so you are basically returning 2 seperate sets of json encodes. It does not work that way. you can only accept a single set of json while reading through ajax. Not two. In your php script i see that you have included that following parts.
$myData1 = array('result' => $sql);
echo json_encode($myData1);
and
$myData = array('result1' => $sqlSelect);
echo json_encode($myData);
you should remove both parts and combine them into one single array using array_merge
$myData1 = array('result' => $sql);
$myData = array('result1' => $sqlSelect);
echo json_encode(array_merge(myData1, $myData));
also in your ajax request, set dataType to json
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(".formCom").serializeArray(),
success: function(reponse){
console.log(reponse);
});
You have 2 problems:
You are sending back invalid json: Instead of echoing out different json strings, you need to build a data-structure (an array or object) and only at the end encode and echo that once. Now you have concatenated json in your response and that makes it really hard to parse.
You are not parsing the json you get back in your javascript. When you return valid json (see 1.), you can add dataType: 'json' to your ajax call to have jQuery parse the response automatically:
$.ajax({
type: "POST",
dataType: 'json',
url: url,
// etc.
So you have a form and you want to submit and that ajax will return some data after submitting the form. And if you want to access the data of response. You need to add this things
1.) Add type = 'post' in your $.ajax object
2.) And use JSON.parse(response)

How to get data in PHP from AJAX jQuery request

So I've followed all your advice about making an jQuery or Javascript AJAX request to a php file on a server.
The problem I'm running in to is that my response is this
Fatal error: Array callback has to contain indices 0 and 1 in
So here is my jQuery
$(document).ready(function(){
$(".ex .select").click(function(){
$("body").data("id", $(this).parent().next().text());
Those lines serve to capture a variable and save it as data on the body element, so I can use it later.
But I want to send that same variable to PHP file, to add to a complex API request - eventually to return the results, create $_SESSION variables and so forth
var pageId = {
id: $("body").data("id"),
};
But let's avoid that as a problem and just make my array simple like
var pageId = {
id: "12345",
};
$.ajax({
type: 'GET',
url: 'test.php',
data: pageId,
datatype: 'json',
cache: false,
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
});
});
And for now at least I was hoping to keep my PHP file simple for testing my grasp of the concepts here
<?php
$id = $_GET('id');
echo json_encode($id);
?>
I'm expecting the response
Data: 12345
Status: Success
But I get the Error Message above.
You need to change $_GET('id') to $_GET['id']
and in order to send status, you need to add status to an array just like below and try to parse JSON on your response.
<?php
$id = $_GET['id'];
$result = array("id"=>$id, "Status"=>"Success");
echo json_encode($result);
?>
And access in jquery using . like if you use data variable in success then
success:function(data){
alert(data.Status);
}
change $id = $_GET('id'); to $id = $_GET['id'];
because $_GET, not a function it's an array type element.

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

Javascript Not Calling PHP function in wordpress

I am trying to get the following code to work:
//In Javascript
function updateContentEditable(){
var span = $(this);
var data = new Object();
data.pid = '1';
data.content = 'this is a test';
data.action = 'update_content'; //This should run update_content php function
$.post(ajaxPath, data, onContentSaved); //ajaxPath returns: /wp-admin/admin-ajax.php
}
//In PHP
function update_content(){
echo "<script>alert (\"php was reached\")</script>";
}
NOTE:
//onContentSaved is this:
function onContentSaved(data){
console.log(data);
}
My problem is the the php function is not being run.
What I'm I doing wrong?
Assuming you are using jquery, try this:
function SendRequestCallBack(webMethod, parameters, callBack) {
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
success: function(results) {
$(".ajaxImage").hide();
eval(callBack(results.d));
}
});
}
function formatData(obj){
alert(obj);
}
$(document).ready(function()
{
SendRequestCallBack("http://url-to-php","{'any':'parameters'}",formatData);
});
Then all the PHP needs to do is echo valid JSON. Or if you like you can change the contentType: parameter to text/xml or text/plain etc depending on what you want it to return. Keep in mind that your PHP needs to output the matching content type as well. for example
<?php
header("Content-type: text/json");
echo {"d":[{"firstname":"John","lastname":"Doe"},{"firstname":"Jane","lastname":"Doe"}]}
?>
If you want to pass data in to the PHP function, set it in the parameters, and make sure that your PHP will accommodate it using the $_POST array.

json import breaks down but from same server source

I am exploring the ajax synchronous json import into my javascript code.
The JSON source link I want to use is
http://www.nusantech.com/hendak/default.php?m=galaksi&galaksi=1&viewID=1&t=json
But to keep server loads down, a week ago or so I created a static page showing the same data at
http://www.nusantech.com/hendak/noobjson.php
My javascript import is as below:
<head>
<title>Nusantech</title>
<script src="\OpenLayers213\OpenLayers.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
var jsonData = {};
$.ajax({
url: "http://hendak.seribudaya.com/noobjson.php",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
alert("Galaksi value retrieved from JSON (expected: 1) : "+jsonData.galaksi);
</script>
<script type="text/javascript">
function kemasMaklumat(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
</head>
From there I retrieve the values I want on jsonData, eg, (x,y) coordinates as
(jsonData.planets[7].coordinates[0].x,jsonData.planets[7].coordinates[0].y)
It works fine with the noobjson.php link, but when I point it back to default.php, nothing appears. The page took a while to load which make it seem like its loading the json values, but the alert("Galaksi value retrieved") returns undefined.
I copy & pasted the output from the default.php page on a JSON verifier on the web and it showed OK. I don't know why the static link works but the $_GET based link doesn't.
Can someone suggest me what is happening?
EDIT
I have tried:
<script type="text/javascript">
var jsonData = {};
$.ajax({
// url: "http://hendak.seribudaya.com/noobjson.php",
url: "http://hendak.seribudaya.com/default.php?"+encodeURIComponent("galaksi=1&viewID=1&m=galaksi&t=json"),
// url: "http://hendak.seribudaya.com/default.php?galaksi=1&viewID=1&m=galaksi&t=json",
async: false,
dataType: 'json',
type: 'GET',
contentType: "application/json",
success: function(data) {
jsonData = JSON.parse(JSON.stringify(eval("("+data+")")));
alert("Success");
},
error: function(data) {
alert("Failed to download info." + data);
}
});
</SCRIPT>
enter code here
I always get the Failed to download info unless I use the noobjson URL.
It is as if that URL with the GET doesn't exist.
You have to encode the URL component before sending the request. Try:
$.ajax({
url: "http://www.nusantech.com/hendak/default.php?" + encodeURIComponent('m=galaksi&galaksi=1&viewID=1&t=json'),
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
Reference: encodeURIComponent()
I have solved it.
In the default.php, what I have done was:
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
if ($_GET["t"]!="json") { echo "<PRE>\n"; $lb="\n"; }
echo "{\"galaksi\": ".$galaksi.",";
echo $lb."\"hari\": ".$hari.",";
echo $lb."\"planets\": [";
//etc
//etc
}
So I replaced all the individual echoes with $JSONstr like below.
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
$JSONstr="";
// if ($_GET["t"]!="json") { $JSONstr="<PRE>\n"; $lb="\n"; }
$JSONstr=$JSONstr."{\"galaksi\": ".$galaksi.",";
$JSONstr=$JSONstr.$lb."\"hari\": ".$hari.",";
$JSONstr=$JSONstr.$lb."\"planets\": [";
//etc
//etc
//and at the end:
echo $JSONstr;
}
Then I added the echo $JSONstr; at the end. Originally I did that so that I can do :
echo json_encode($JSONstr);
but this creates {\"Galaksi\" : 1} at the JSON output instead of the intended { "Galaksi": 1 }
So I removed the json_encode and just output the string.
Also I had to remove the
if ($_GET["t"]!="json"){ $JSONstr="<PRE>\n"; $lb="\n"; }
I also used a different JSON tester this time.
Originally I used http://www.freeformatter.com/json-validator.html which says JSON Valid for my initial JSON output. Then I used this one, which said that my JSON output url was invalid, although if I copy+paste the output string it returned valid. http://jsonformatter.curiousconcept.com/
So after making those changes and removing the "<PRE>", the curiousconcept validator gave me a valid status.
Then I used this in the javascript, and I am now able to retrieve expected values.
Thank you all, hope this helps someone else too.

Categories