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
}
});
Related
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
}
});
I want to get data with ajax and jquery. But i get thhis error and i dont know how to fix it.
VM5601:2 Uncaught SyntaxError: Unexpected token < in JSON at position 10
This is my code.
Model
public function GetBloodCatById($id)
{
$this->db->from('tbl_blood_cat');
$this->db->where('id_blood_cat',$id);
$query = $this->db->get();
return $query->row();
}
Controller
public function ajax_edit($id)
{
$data = $this->Blood->GetBloodCatById($id);
echo json_encode($data);
}
View
function edit_blood(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('Home/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
contentType: 'application/json',
success: function(data)
{
$('[name="id_blood_cat"]').val(data.id_blood_cat);
$('[name="catName"]').val(data.category);
$('#myModalBloodCat').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Blood Cat'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
This is data that will be get
{"id_blood_cat":"1","category":"Plasma","createBy":"nicky","updateBy":null,"createAt":"2017-05-11 18:30:09","updateAt":"2017-05-11 18:30:09","flag":"1"}
I had been strugle with this for hours. Please help me thx.
wrapping json in array is always good choice.Here i have modified your function little
public function ajax_edit($id)
{ $res = array();
$data = $this->Blood->GetBloodCatById($id);
$res = $data;
echo json_encode($data);
}
and ajax success handler is like
........
success: function(data)
{ response = $.parseJSON(data);
$.each(data, function (i, item) {
$('[name="id_blood_cat"]').val(response.id_blood_cat);
$('[name="catName"]').val(response.category);
}
$('#myModalBloodCat').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Blood Cat'); // Set title to Bootstrap modal title
},
........
Reomve php tag and try to set url like this
url : "/Home/ajax_edit/?id=" + id,
Try: url: 'file:///Home/ajax_edit/?id='+id
I have script that return this from the server using ajax call
//ajax call
var comment_frm = $('#comment_form');
comment_frm.submit(function (ev) {
$.ajax({
type: comment_frm.attr('method'),
url: comment_frm.attr('action'),
data: comment_frm.serialize(),
success: function (data) {
if (data == 1){
$("#success_message").show();
$('#comment_form').trigger("reset");
}
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
//prevent the page from loading
ev.preventDefault();
});
[{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"comment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]
I want to format it to look like this and assign the json result to a javascript variable
var comment_array = {"Comments": [{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"coment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]}
//php code
$operation = $_POST['operation'];
if($operation == 'add_comment'){
$name = $_POST['name'];
$comment = $_POST['comment'];
$blog_id = $_POST['blog_id'];
$comment_status = 1;
if ($me->add_comment($name, $comment, $blog_id)){
//get the comment
$comment_array = $me-> fetch_moderated_comment($blog_id);
echo json_encode($comment_array);
}else{echo 10;}
}
I will also love to know how to read get that from the call... Can someone please help me
Working Example
You could assign a variable to hold your new 'Comments' array and then push to it:
var a = [{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"comment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]
var b = {"Comments": []};
for (var prop in a) {
b.Comments.push(a[prop]);
}
echo json_encode(['Comments' => $comment_array]);
If I understand correctly, just wrap the result in an object literal:
vat result = {"Comments": comment_frm};
I'm trying to send an AJAX request to a php file, and I want the php file to respond with a JSON object, however the AJAX function is continually failing when declare that I specifically want JSON returned. Any help will greatly be appreciated.
this is my ajax function
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'json',
success: function(msg){
//var content = data.substr(0, data.indexOf('<'));
populateMessages(msg);
},
error: function(){
alert("ERROR");
}
});
}
and this is the relevant code for the php file
$message_links[] = array();
.....
while($run_message = mysql_fetch_array($message_query)){
$from_id = $run_message['from_id'];
$message = $run_message['message'];
$user_query = mysql_query("SELECT user_name FROM accounts WHERE id=$from_id");
$run_user = mysql_fetch_array($user_query);
$from_username = $run_user['user_name'];
$message_links[] = array("Hash" => "{$hash}", "From" => "{$from_username}", "Message" => "{$message}");
// is that not valid json notation???
}
}
echo json_encode( $message_links, JSON_FORCE_OBJECT);
//$arr = array("a" => "1", "b" => "2");
//echo json_encode($arr);
UPDATE:
Well, I ended up switching the dataType request to 'html' and I am now able to actually access these values via JSON, however, I would still like to know why the php file was not returning correct JSON notation. Any insight would be awesome, cheers.
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'html',
success:function(msg){
var content = msg.substr(0, msg.indexOf('<'));
msg = JSON.parse(content);
populateMessages(msg);
},
error: function(xhr, textStatus, errorThrown) {
alert(errorThrown);
alert(textStatus);
alert(xhr);
}
});
}
function populateMessages(data){
var out = '';
var json;
for (var i in data){
var my_string = JSON.stringify(data[i],null,0);
json = JSON.parse(my_string);
alert(json.Hash);
out += i + ': ' + my_string + '\n';
}
alert(out);
}
You need to set the header as json type before your echo in PHP:
header('Content-Type: application/json');
I'm trying to send data from an html data attribute on a span element and receive it with Ajax and then process it with php and mysql and return the new value to my data attribute in html, but I'm getting a error that says "$.parseJSON unexpected character", can someone please look over my code to see if I'm processing the data correctly as I'm new to working with JSON.
HTML / PHP
<span data-object=
'{"art_id":"<?php echo $row['art_id'];?>",
"art_featured":"<?php echo $row['art_featured'];?>"}'
class="icon-small star-color"></span>
<!-- art_id and art_featured are both int and art_featured will be either 1 or 0 -->
jQuery / Ajax
$("span[class*='star']").on('click', function () {
var data = $.parseJSON($(this).data('object'));
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', JSON.stringify( data ));
});
});
PHP / mySQL
if($_POST['art_featured']==1) {
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 0 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 0);
echo json_encode($result);
}
else if($_POST['art_featured']==0){
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 1 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 1);
echo json_encode($result);
}
if(query($sql_articles)) {
}
else {
}
You don't need to use $.parseJSON, jQuery does that for you.
$("span[class*='star']").on('click', function () {
var data = $(this).data('object');
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', data);
});
});
You also don't need to stringify it later.