Separate values returned from AJAX - javascript

My ajax functions returns two values, and when I call "data" they are displayed as one.
Javascript
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'checkinfo.php',
data: { address: "37.187.139.123", port: "26618" },
dataType: 'html',
async: true,
success: function(data)
{
$("output").html(data);
}
});
});
PHP
<?php
$SERVER_IP = $_REQUEST['address'];
$SERVER_PORT = $_REQUEST['port'];
$QUERY_PORT = $_REQUEST['port'];
$HEADS = "3D";
$show_max = "unlimited";
$SHOW_FAVICON = "on";
$TITLE = "My fancy Serverpage";
$TITLE_BLOCK_ONE = "General Information";
$TITLE_BLOCK_TWO = "Players";
$ping = json_decode(file_get_contents('http://api.minetools.eu/ping/' . $SERVER_IP . '/' . $SERVER_PORT . ''), true);
$query = json_decode(file_get_contents('http://api.minetools.eu/query/' . $SERVER_IP . '/' . $QUERY_PORT . ''), true);
if(empty($ping['error'])) {
$version = $ping['version']['name'];
$online = $ping['players']['online'];
$max = $ping['players']['max'];
$motd = $ping['description'];
$favicon = $ping['favicon'];
}
if(empty($query['error'])) {
$playerlist = $query['Playerlist'];
}
echo $version;
echo $online;
?>
The output I get in the "output" element is" Version 1.80". Where as the $version variable is "Version 1.8" and the $online variable is "0". How do i separate these two values and assign them to two element different elements ex. output1 and output2.
Lastly, is there any better way to directly get the value from individual variables, rather than using echo for them all and collecting them as one "data".

You're dealing with a plain text/html response, which would need parsed. Also, the ajax function only returns one value. Anything echoed by the PHP script gets dumped into the ajax response.
You should change the dataType to json, and return the values as a json-encoded array:
die(json_encode(array(
'version' => $version,
'online' => $online
)));
This can be accessed in javascript as:
data.version
data.online
ProTip: If you're not sure what's being returned, check the Network tab of Chrome's developer tools (or Firebug or whatever). Console.log() can be used to dump the var to the console for inspection, and doing the following will allow you to manipulate it directly in the console:
success: function(response) {
console.log(resp=response);
/* open the console, and you can manipulate the var 'resp' */
}

Related

How to get one or two of data value in Controller Codeigniter when using AJAX Post

can someone help me with my code, i have AJAX json type POST and i wanto to get one or two of data send to controller in codeigniter, i wanto to add conditional function where the data from json.
My JSON
$('#add_people').submit(function(e){
e.preventDefault();
var id_people = $('#id_people').val();
var name_people = $('#name_people').val();
var phone_people = $('#phone_people').val();
$.ajax({
type : "POST",
url : "<?php echo base_url('add_people_data')?>",
dataType : "JSON",
data : {id_people:id_people , name_people:name_people, phone_people:phone_people},
success: function(data){
$("#show_people").html('<img src="assets/img/user/spinner.gif"> <h4>Loading data...</h4>');
$('#modal-add_people').modal('hide');
$('.modal-backdrop').remove();
$('[name="id_people"]').val("");
$('[name="name_people"]').val("");
$('[name="phone_people"]').val("");
var loadUrl = "<?php echo base_url('show-people-data')?>";
$("#show_people").load(loadUrl);
}
});
return false;
});
My Controler
public function add_people_data()
{
$id_people = $this->input->post('id_people');
$name_people = $this->input->post('name_people');
$phone_people = $this->input->post('phone_people');
$cekassignreviewer=$this->Model_reviewer->checkassignreviewer('data_people', $id_people, $name_people, $phone_people);
if ($cekassignreviewer > 0) {
$this->session->set_flashdata('failed',
"<script>swal({
title:'Failed!',
text: 'Number of people has been added',
icon: 'error',
confirmButtonText: 'Ok',
confirmButtonClass: 'btn btn-success'
});
</script>");
redirect(base_url('setting-reviewer'));
}else{
$data=$this->Model_reviewer->add_people();
echo json_encode($data);
}
My Model
function add_people()
{
$data = array(
'id_people' => $this->input->post('uniid_reviewer'),
'name_people' => $this->input->post('name_people'),
'phone_people' => $this->input->post('phone_people'),
);
$result=$this->db->insert('data_people',$data);
return $result;
}
Thank you in advance
IncomingRequest Class For CodeIgniter 4
If you are not within a controller, but still need access to the application’s Request object, you can get a copy of it through the Services class:
$request = \Config\Services::request();
With CodeIgniter’s built in methods you can simply do this:
$something = $request->getVar('foo');
The getVar() method will pull from $_REQUEST, so will return any data from $_GET, $_POST, or $_COOKIE. While this is convenient, you will often need to use a more specific method, like:
$request->getGet()
$request->getPost()
$request->getServer()
$request->getCookie()
In addition, there are a few utility methods for retrieving information from either $_GET or $_POST, while maintaining the ability to control the order you look for it:
$request->getPostGet() - checks $_POST first, then $_GET
$request->getGetPost() - checks $_GET first, then $_POST

How to get data from json array in php via ajax get request?

I have 3 data in my database and I want my js to show all my data, But when I'm using json array, I get an error and my data doesn't show it all.
var confurl = "http://localhost:8080/servisppk/web_service.php";
$.ajax({
url : confurl,
type : 'GET',
dataType: 'json',
beforeSend : function() {
$.mobile.loading('show', {
text : 'please wait while retrieving data...',
textVisible : true
});
},
success : function(dataObject) {
var appendList = '<li><h2>' + dataObject.Nama + '</h2><p>' + dataObject.NIM + '</p><p><b>' + dataObject.Fakultas + '</b></P></li>';
$('#list-mhs').append(appendList);
$('#list-mhs').listview('refresh');
},
complete : function(){
$.mobile.loading('hide');
}
});
i'm using json array in my php:
$ms = array($mhs,$mhs2,$mhs3);
ECHO JSON_ENCODE($ms);
when i'm using it, it doesn't show my data at all, it just show that my data is undefined, but when I change it to only be able to read one data, the data can appear even if only one.
changed to this:
$ms = $mhs;
ECHO JSON_ENCODE($ms);
You need send header let browser known, like:
<?php
$data = ['test' => 'hello'];
header('Content-Type: application/json');
echo json_encode($data);

jquery.ajax to PHP fails when I use ECHO in my PHP

this is the 1st time I try to use AJAX - my website needs to call a PHP during runtime when the user leaves a specific form field (VIN). I pass the value of this field to a PHP function for validation and processing. Then PHP should return 3 values for 3 different form fields.
This is my problem: I won't get the 3 values back into my javascript.
Each time when I use ECHO json_encode in my php the AJAX call crashes and the console shows "VM7190:1 Uncaught SyntaxError: Unexpected token Y in JSON at position 0(…)".
If I put any other simple ECHO in my PHP the AJAX call would return with an error.
If I remove each ECHO from my PHP the AJAX call returns as success but the returning data is NULL.
It would be so great if I could get a solution for this problem here.
If anybody would like to test the site - this is the url: mycarbio
Thank you very much.
This is my AJAX call:
function decode_my_vin(myvin) {
alert("in decode_my_vin");
dataoneID = '123';
dataoneKEY = 'xyz';
jQuery.ajax(
{
cache: false,
type: 'POST',
url: '/wp-content/themes/Impreza-child/vin-decoder.php',
dataType:'json',
data: {
'value1_VIN': myvin,
'value2_ID': dataoneID,
'value3_KEY': dataoneKEY,
'value4_Year': ' ',
'value5_Make': ' ',
'value6_Model': ' '
},
// async: false,
success: function(response) {
var obj = jQuery.parseJSON(response);
alert("success returned: " + obj);
document.getElementById("fld_7290902_1").value = "2015";
document.getElementById("fld_1595243_1").value = "Ford";
document.getElementById("fld_7532728_1").value = "Focus";
return;
},
error: function() { alert("error in der jquery"); }
});
}
And this is my PHP
<?php
header('Content-Type: application/json');
$resultYear = '2010';
$resultMake = 'Ford';
$resultModel = 'Focus';
$vinResult = array("Year: ", $resultYear, "Make: ", $resultMake, "Model: ", $resultModel);
echo json_encode($vinResult);
?>
This may not be your only problem, but you should try using an associative array when rendering the JSON:
$vinResult = array(
'Year' => $resultYear,
'Make' => $resultMake,
'Model' => $resultModel
);
Currently you are combining your property names and values.

Rewrite ajax request and the values returned

I need help to write this without the async: false,.
var imageX;
var groupX;
$.ajax({
type:'GET',
url:'php/myphp.php',
dataType:'json',
async: false,
success: function(response){
imageX = response[0].studentName,
groupX = response[0].subjectId;
alertImageX();
}
});
function alertImageX() {
(function() {
var image = {
'back': { 'url':imageX, 'img':null },
'front': { 'url':'img/bg.jpg', 'img':null }
};
php
$query = $db->prepare('SELECT studentName, subjectId FROM grade3 WHERE eligible = ? LIMIT 1');
$array = array('Yes');
$query->execute($array);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
"async: false" should not be needed in this situation because your response is already processed after AJAX request is complete, as it is placed inside the "success" element. Sorry if I missed any detail
EDIT:
Sorry I just read your comment regarding what you want to achieve. The response variable contains whatever the script called by AJAX echoed (in case of a PHP script), so you basically need to echo what you want the script to return and access that through the response variable.

Bootstrap typeahead autocompletion with the source loaded only once on pageload

I want to load the whole source data via jquery from the server but only once on pageload. I want to store it in a variable. The jquery part works but the input does not autocomplete. It does nothing. It works only if the source is written like source: ["blablabla","dadadada"].
This is my Javascript Code:
var datasource; // this is the variable where my source will be stored
$.post("typeahead.php",
{
query: 'query' // 'query' has no meaning ;)
},
function(data) { // data looks like ["asd","fds"] thanks to json_encode on the server side
datasource = data;
});
$('#searchInput').typeahead( {
source: datasource
});
Server Side php code:
/* connect to the db */
$con = mysql_connect("localhost","fahrschulesql1","******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select Database
$db_selected = mysql_select_db("fahrschulesql1", $con);
if (!$db_selected) {
die ("Select DB error: " . mysql_error());
}
$query = "SELECT Vorname, Nachname FROM Benutzer b, Fahrlehrer f WHERE b.BenutzerID = f.BenutzerID";
$result = mysql_query($query) or die ("MySQL-Error: " . mysql_error());
while($row = mysql_fetch_array($result)){
$array[] = $row["Vorname"] . " " . $row["Nachname"];
}
echo json_encode($array);
mysql_close($con);
What am I doing wrong?
You are losing the reference to the array datasource by assigning a new array. You will need to manipulate the array to avoid losing the reference to it.
var datasource = [];
$.post("typeahead.php", {
query: 'query'
}, function(data) {
/* Add the responses to the datasource, don't mess up the reference */
[].push.apply(datasource, data);
});
$('#searchInput').typeahead({
source: datasource
});
See it here.
Another option is caching the response. I personally prefer this method over the previous one.
You can use the process callback after sending the first request and cache the data. Onwards, use the cached data.
var cachedsource = (function(){
var datasource = null;
return function(query, process){
if(datasource !== null) {
/* use cached data */
return datasource;
} else {
$.post("typeahead.php", {
query: 'query'
}, function(data) {
/* cache data */
datasource = data;
process(datasource);
});
}
};
})();
$('#searchInput').typeahead({
source: cachedsource
});
See it here.
PHP is returning incorrect Content-Type. Try $.ajax instead of $.post.
$.ajax({
url: "typeahead.php",
data: {
query: 'query'
},
success: function(data) {
/* cache data */
datasource = data;
process(datasource);
},
dataType: "json"
});
Notice the dataType is set to json.
You can also set the correct Content-Type in PHP using header().
header('Content-Type: application/json');
echo json_encode($array);
where is your html code?
are you using this:
<input id="searchInput" type="text" data-provide="typeahead">
?
then be sure your callback is ok in firebug and data is returned cause you didn't specified any url for example here:
$.post("typeahead.php",
then be sure you are running your js inside document.ready
$(document).ready(function(){
//do my js
});
also try:
console.log(datasource); before passing that var to the bootstrap plugin
definitely try this:
$(function(){
$.post("typeahead.php",
{
query: 'query' // 'query' has no meaning ;)
},
function(data) { // data looks like ["asd","fds"] thanks to json_encode on the server side
$('#searchInput').typeahead( {
source: data
});
});
});

Categories

Resources