Fetching PHP Data with Javascript and assign it to an array - javascript

I've got a php script with collects data from a server and displays it in an array and after that as a json with the function.
echo json_encode($result);
Now I want to access that array with my javascript and display it. It should be saved in a var as an array so it should look like:
data = [ "xxxx" , "ssss",];
But I guess I can simply put in my function which gets the array data instead so it'd be:
data = myfunction ;
What I've tried so far:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
};
oReq.open("get", "http://myserver.com/myscript.php", true);
oReq.send();
and
function getdata(url) {
jQuery.ajax(
{
type: "GET",
url: "http://myserver.com/myscript.php/",
dataType: "text",
success: function (response) {
var JSONArray = jQuery.parseJSON(response);
connsole.log(JSONArray);
}
});
}
But none seems to work and I get displayed 'undefined' instead of my arrays.
Would be really great if somebody has some ideas on that and can help me out.
Edit:
Since we are getting nowhere here's my php code:
<?php
error_reporting(0);
$html = file_get_contents("url here");
$dom = new DOMDocument();
$dom->loadHTML($html);
$tbodyRows = $dom->getElementsByTagName( 'tbody' )
->item( 0 ) // grab first tbody
->getElementsByTagName( 'tr' );
$result = array();
foreach( $tbodyRows as $tbodyRow )
{
$result[] = $tbodyRow->getElementsByTagName( 'td' )
->item( 2 ) // grab 3rd column
->nodeValue;
}
echo json_encode($result);
?>

Try this code:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "text",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
Open the browser's console, and let me know about its contents. If you don't see Error or Success, your code isn't actually executing

I have done a similar thing earlier. I will describe it and I wish it will help you.
In the following code (get_categories.php), I am retrieving data from the database and add them to an array. Then return it by encoding as a JSON.
$sql = "SELECT category_name FROM category;";
$dataArray = [];
$result = $connection->query($sql);
if ($result) {
while ($row = $result->fetch_assoc()) {
$dataArray[] = $row;
}
echo json_encode($dataArray);
}
Then in my Javascript code, I can get the data as follows.
$.ajax({
url: "/get_categories.php",
type: "GET",
dataType: "json",
success: function (categories) {
for (var i = 0; i < categories.length; i++) {
console.log(categories[i]);
}
},
error: function (jqXHR, textStatus, errorThrown) {
// Error handling code
}
});

Related

Don't alert AJAX

I'm trying to get result and alert it if the solicitude was successful or not on the PHP file, it worked (because changed the results) but the AJAX didn't show alerts (No error and no "true")
js:
function addentrys() {
var nwentry = {};
el = document.getElementById('addname').value;
eldmn = document.getElementById('adddomain').value;
nwentry.name = el;
nwentry.domain = eldmn;
$.ajax({
type: 'POST',
url: 'api/domain',
dataType: 'json',
data: nwentry
}).done(function(data) {
alert(data);
});
}
php:
$app->post('/domain', function () {
$jsonContents = file_get_contents('data/data.json');
$name = $_POST['name'];
$domain = $_POST['domain'];
$data = json_decode($jsonContents, true);
$last_item = end($data);
$last_item_id = $last_item['id'];
$data[] = array(
'name' => $name,
'domain' => $domain,
'id' => $last_item_id+1
);
$json = json_encode($data);
file_put_contents('data/data.json', $json);
return true;
});
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.

Receive php multidimensional array in ajax

I have this php
include_once($preUrl . "openDatabase.php");
$sql = 'SELECT * FROM dish';
$query = mysqli_query($con,$sql);
$nRows = mysqli_num_rows($query);
if($nRows > 0){
$dishes = array();
while($row = $query->fetch_assoc()) {
$dishes[] = $row;
}
}else{
$dishes = "cyke";
}
echo json_encode($dishes , JSON_FORCE_OBJECT);
and this ajax (in framework7)
myApp.onPageInit('dailyMenu',function() {
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.log(data);
});
});
What i get in the ajax data is
{"0":{"idC":"2","title":"helloWorld1","subtitle":"hellsubWorld","price":"16.5","img":"img/testeImg.jpg","soldout":"0"},"1":{"idC":"3","title":"helloworld2","subtitle":"hellosubWorld2","price":"20.5","img":"img/testeImg.jpg","soldout":"1"}}
I already tried data.[0]; data.['0']; data.0; data0 when i use data["0"] just gives me the '{'.
I want to acess the title and the rest inside that 0. to do a cicle for where i will print multiple divs where i only change the array position in a html page.
Exemple
for(...){
innerhtml += <div clas="">
<div class""> data(position i).title </div>
<div> data(position i) subtitle</div>
</div>
}
try this one (after callback add type: json)
$$.post('url', {}, function (data) {
var obj = JSON.parse(data);
console.log(obj);
alert(obj["1"].title);
});
or maybe you can use JSON.parse(data);
Since you are receiving a json data as response, you should use this:
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.dir(data);
},'json');
Pay attention to },'json');on end of the code, now the $$.post is reading the response as a JSON.
If you aren't doing any update to data base, you could use:
$$.getJSON('http://theIP/eatsServer/dailyMenu.php',{}, function (data) {
console.dir(data);
});
This is the way with $$.ajax:
$$.ajax({
url: "url_here",
method: "POST",
dataType:"json",
data: {},
success: function(r){
// response r.
}, error: function(error){
//error
}
});

go through each row returned by a ajax call

I have following code to execute a query on the Database. it returns a list of objects, one for each row result from the query:
function getcontent()
{
var data = {
"id": "<?php echo $stournid; ?>"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(response) {
//**************************** HERE!!!!
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
return false;
}
The response.php file contains this:
<?php
$id = "";
if (is_ajax()) {
if (isset($_POST["id"]) && !empty($_POST["id"])) { //Checks if action value exists
$id = $_POST["id"];
querydata($id);
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function querydata($id){
require_once('dbconfig.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_error) {
die('Errore di connessione (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$myArray = array();
if ($games = $mysqli->query("my query is here.. pretty long but working correctly.")){
while($row = $games->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
}
?>
here is the returned data:
[{"id":"1435","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|6|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":"57","id_gamer2":"55","called":"2","callreadytime":"13:08:07","starttime":"22:12:19","endtime":"22:20:03","id_winner":"57","id_loser":"55","playsequence":"00001","tabsequence":"A00010001","dest_winner":"B00010001-1","dest_loser":"C00010001-1","connectionname":"","p1name":"Calamante Lorenzo","p2name":"Badiali Maurizio"},
{"id":"1436","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|4|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":null,"id_gamer2":null,"called":"0","callreadytime":"00:00:00","starttime":"00:00:00","endtime":"00:00:00","id_winner":"0","id_loser":"0","playsequence":"00015","tabsequence":"W00010001","dest_winner":"","dest_loser":"1","connectionname":"","p1name":null,"p2name":null}]
What I would like to do, is in the Javascript, go through all the returned lines one by one and updated some div's accordingly. I am having difficulties on how to iterate the returned lines.
Any help appreciated.
Thanks
success: function(response) {
// redponse is an array of objects (so lets loop through it using forEach)
response.forEach(function(row) {
// row is a row (object) from the array
var id = row.id;
var location = row.location;
var date = row.date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
Note: Array.prototype.forEach is like a loop but better. Check the docs.
Don't want to use forEach?
If you don't want to use forEach, you can use an old for like this:
success: function(response) {
// using for is not very pretty, hein?
for(var i = 0; i < response.length; i++) {
// response[i] is the i-th row of the array
var id = response[i].id;
var location = response[i].location;
var date = response[i].date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},

php can not get the data send by ajax

this is the js code, ajax has two arguments, the first is url, 2nd is a object which contains type data and onsuccess. (I didn't use jQuery but the function I define myself, the code is at the end of the question)
I just want to send the 'text' string to php, so is there any problem to do like this? I also have tried change the data to data: {searchinput:"text"}, but still don't work.
ajax(
'http://localhost/test.php',
{
type: 'POST',
data: "searchinput=text",
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
this is the php code, sorry for changing the code wrong while pasting it on.
$searchinput = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
then the error is
Undefined index: searchinput
I have search some method like change onsuccess function to setTimeout, and do ajax again, but it doesn't work, just send the data again but the php still can't get the data
this is the ajax function
function ajax(url, options) {
if (!options.type) {
options.type = "post"
};
var xhr = new XMLHttpRequest();
xhr.open(options.type, url, true);
xhr.send(options.data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
options.onsuccess(xhr.responseText, xhr)
} else {
options.onfail(xhr.responseText, xhr);
}
};
}
}
Well, since you used the ajax wrong, I'm not surprised. There should be a error in the console.
jQuery AJAX is used like this:
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
url is a part of the object the ajax expects, so it needs to be inside and not outside of it. Also, data is expecting another object, you gave it a plain string.
Also, as #Muhammad Ahmed stated in his answer, you are using a wrong variable in your php code.
Edit: AJAX in JavaScript without jQuery:
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/test.php', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// worked
var data = JSON.parse(this.responseText);
} else {
// failed
}
}
};
request.send();
request = null;
$searchcon = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
In This code there is a mistake on ist line you are using variable $searchcon
and on query you are using $searchinput change ist varaible name to $searchinput instead of $searchcon. and also change your ajax code.
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseTxt, xhr) {
console.log(responseTxt);
}
}
);
send data value like below and use print_r($_POST) on php page to see values are coming or not
$.ajax(
{ url: 'test.php',
type: 'POST',
data:{
searchinput:text
},
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
Try with this code you were using ajax in wrong manner. You can learn more about how ajax works and how to code for ajax over http://api.jquery.com/jquery.ajax/
$.ajax(
{
type: 'POST',
url : 'http://localhost/test.php',
data: {searchinput:text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
and within your PHP file you need to update your typo i.e. you were getting value of your POST in $searchcon variable
$searchcon = $_POST["searchinput"];
^^^^^^^^^^
and within your query you were using
$query = "select * from text where data like'".$searchinput."%' ";
^^^^^^^^^^^^^^
it should be like
$query = "select * from text where data like'".$searchcon."%' ";
^^^^^^^^^^
Try this code :
var other_data = $('form').serializeArray();
$.ajax({
url: 'work.php',
data: other_data,
type: 'POST',
success: function(data){
console.log(data);
}
});
or
you can also pass the data in url also.
Try the code which suits your requirement.
$.ajax({
url: 'work.php?index=checkbox&action=empty',
type: 'POST',
success: function(data){
console.log(data);
}
});

ajax function not returning right data

I'm trying to get the proper information out of this ajax function (thumbnail image, the owner of the image). I dont think it knows what data.images[i].imgurl and data.images[i].username is.
ajax.php
require_once 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('123456');
// Receive AJAX request and create call object
$tag = $_GET['tag'];
$maxID = $_GET['max_id'];
$clientID = $instagram->getApiKey();
$call = new stdClass;
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";
// Receive new data
$media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));
// Collect everything for json output
$images = array();
foreach ($media->data as $data) {
$images[] = array(
"imgurl"=>$data->images->thumbnail->url,
"username"=>$data->user->username;
);
}
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $images,
));
search.php
<script>
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
tag: tag,
max_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('#photos').append('<div id=box><div class=mainimg><img src="'+ data.images[i].imgurl +'"></div><div class=\"pfooter\">'+ data.images[i].username +'</div></div>');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
..
In your search.php file you have to close the variable statement with a semicolon.
Change this line:
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'),
to this:
var tag = $(this).data('tag'),
maxid = $(this).data('maxid'); // <-- added semicolon

Categories