got error when using javascript ajax json to retrieve php array - javascript

My html page is suppose to retrieve the array from the php page and alert the first element in the array. But when I run the html, got the following error, "Uncaught TypeError: Object function (E,F){return new o.fn.init(E,F)} has no method 'parseJSON' " in the console window. I tried to use jQuery.parseJSON(json_data) instead of $.parseJSON(json_data) but still got the same error. How can I fix this?
script.js:
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array =jQuery.parseJSON(json_data);
var rec = data_array[0];
alert(rec);
alert("GOOD");
},
error: function() {
alert("BAD");
} });
}
newcal.html:
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="demo.css">
<body onload="getArr();">
<div id="rounded"><div id="main" class="container">
<div id="pageContent">
Hello, this is the default content
</div>
</div>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
</html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>

parseJSON was added in jQuery 1.4.1 (in 2010)
You are using jQuery 1.3.2 (from 2009), which is too old.
The current version of jQuery 1.x is 1.11 (released this year).
Use a more recent version of jQuery.
You should also tell the browser that you are sending it JSON instead of claiming that your JSON is HTML. (PHP defaults to claiming that anything it outputs through a web server is HTML)
<?php
header("Content-type: application/json");
$output = array("cat","dog");
echo json_encode($output);
?>
Then let jQuery parse it automatically:
success: function(data_array){
// Remove the following line. It will be parsed automatically.
// var data_array =jQuery.parseJSON(json_data);
var rec = data_array[0];

Related

How to return an array from PHP script when an HTTP request is sent from javascript?

Hi I'm new to PHP and I'm stuck on an issue,
I want to send a HTTP request to a PHP script and it should return a 2x2 array. But with my code I'm receiving nothing.
index.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "get_info.php");
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send();
</script>
</body>
</html>
get_info.php:
<?php
$return_array = [[1, "h"],[2, "he"],[3, "hel"],[4, "hell"],[5, "hello"]];
return $return_array;
?>
json_encode() that array, and echo (not return!) the resulting json string:
<?php
$return_array = [[1, "h"],[2, "he"],[3, "hel"],[4, "hell"],[5, "hello"]];
echo json_encode($return_array);
// remove the trailing ?> just to make sure you don't send an unwanted newline, space or smth
Then in javascript
var myArray = JSON.parse(xhr.responseText);
console.log(myArray);
to make a js array out of it again.
Some docs and related reads:
php: json_encode()
JSON wiki
javascript: JSON.parse()
Use echo instead of return ... this isn't a function that was called; it is a code snippet that simply puts dynamic data in place of static text.

results from php library not working with AJAX

I'm calling the uberGallery (www.uberGallery.net) from the index.php like so:
<?php
include_once 'resources/UberGallery.php';
include_once 'resources/uberCall.php';
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
...
<link rel="stylesheet" type="text/css" href="resources/themes/uber-naked/style.css" />
<link rel="stylesheet" type="text/css" href="resources/colorbox/5/colorbox.css" />
<script src="//code.jquery.com/jquery.js"></script>
<script type="text/javascript" src="resources/colorbox/jquery.colorbox.js"></script>
</head>
<body>
<div class = "row">
<div class = "col col-lg-12">
<h2 id = "locName"></h2>
</div>
</div>
<div id="gallery">
<?php
$path = "london";
getGallery($path);
$path = "paris";
getGallery($path);
$path = "rome";
getGallery($path);
?>
</div>
<script type="text/javascript" src='js/UX.js'></script>
</body>
</html>
The uberCall.php is like that:
<?php
include_once ('UberGallery.php');
function getGallery($pathToImage){
UberGallery::init() -> createGallery('locations/'.$pathToImage.'/gallery');
}
if(isset( $_POST['image-path'] )) {
$path = $_POST['image-path'];
UberGallery::init() -> createGallery('locations/'.$path.'/gallery');
}
?>
So far this is working like expected.
Now I would like to load the galleries from a dropdown menue and just show the selected gallery. The dropdown selection is done in a jQuery script:
$(document).ready(function() {
$("a[rel='colorbox']").colorbox({
maxWidth : "90%",
maxHeight : "90%",
opacity : ".5"
});
$(".dropdown-toggle").dropdown();
$('#demolist li a').click(function(e) {
$('#locationSelector').val($(this).text());
var $this = $(this);
var selLocID = $this.attr("value");
e.preventDefault();
var dataString = {
'location_id' : selLocID
};
$.ajax({
type : 'POST',
dataType : 'json',
url : 'includes/locationAPI.php',
data : dataString,
success : function(data) {
$('#locData').html('');
// erase content if any
$('#locName').html(data['name']);
// from MySQL
// set location headline
$.ajax({
type : "POST",
data : {
'image-path' : data['pfad'] // from MySQL
},
url : 'resources/uberCall.php',
dataType : "html",
async : false,
success : function(data) {
result = data;
alert(result);
$('#gallery').html(result);
}
});
}
});
});
});
When going this route the ubergallery doesn't find any folders, though I'm adressing the exact same uber.php as I would from the index.php.
I have looked into the ubergallery.php with xdebug and it would be called with exactly the same parameters.
Also I tried to call createGallery() without init:: and also explicitly create a new instance of the UberGallery class before calling createGallery.
All with no luck.
What am I doing wrong here?
In your resources/userCall.php script you are not actually calling the gallery function in order to render it. This appears to be the target of the second AJAX request. The script is merely defining the function.
EDIT: You've since updated the code in your question to include the call.
Assuming image-path is the parameter you want to supply as $pathToImage you will need to have a script that calls the function getGallery passing the value from $_POST['image-path'].
For example:
<?php
require_once('resources/uberCall.php');
getGallery($_POST['image-path']);
NOTE: Without any filtering sanitisation, bear in mind this could be potentially dangerous as I could pass an image-path parameter that picks a naughty directory.
Then use that script as the target of your second AJAX call.
P.S. Remove the async: false in the second AJAX call, it stops any other interactivity on your page whilst the request is in flight.
Bear in mind that with your parameter checking in the resources/userCall.php the original request is down a directory from the second request. This means the working directory for the second request will be different, the path will resolve to "resources/locations/$path/gallery" and not "locations/$path/gallery".
You are best off creating a second script for the AJAX action in the same directory as the original and requiring in the resource/userCall.php as per the first script. Or using a configurable absolute directory path to resolve the gallery location:
<?php
require_once('UberGallery.php');
require_once('config.php');
function getGallery($path) {
UberGallery::init() -> createGallery("{$config['gallery_base_path']}/$path/gallery");
}
With $config['gallery_base_path'] being something like /absolute/path/to/my/application/locations.
Additional confusion can be caused by not knowing whether file operations will use the include path, some file options can be told to use the include path which may include the current file path and current script directory, but if not it will only try to find the file from the current working directory. Whereas include and require all use the include path and current script directory as potential points to find a script.
P.S.P.S Use getcwd to find out what the current working directory is at any point in your scripts.

Backbone: passing data to server (save() method, php file)

Hope you can help me with that problem.
I want to use Backbone's save() method and pass to php file data.
But on a very begining I have problem.
In browser's console I execute:
var test = new MyModel(); // - it's ok
test.toJSON(); // - it's ok
test.save(); // and here I have error "TypeError: d.collection is undefined"
When I use localStorage everythink is OK (it's commented in my code below). I can create models, collections, views etc. and operate on them.
I tried to use these tutorials net.tutsplus.com/tutorials/javascript-ajax/understanding-backbone-js-and-the-server/ and http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/ but I can't get how REST works and where I made mistake. Hope you can explain.
index.html
<!DOCTYPE html>
<html>
<head>
<title>S.O.S</title>
</head>
<body>
<h1>Test</h1>
<script src="jquery.min.js"></script>
<script src="underscore-min.js"></script>
<script src="backbone-min.js"></script>
<script src="backbone.localStorage-min.js" type="text/javascript"></script>
<script >
window.MyModel = Backbone.Model.extend({
defaults: {
title: 'Test'
},
//localStorage: new Store('TEST')
urlRoot: 'api/items'
});
</script>
</body>
</html>
index.php
<?php
require 'Slim/Slim.php';
$app = new Slim();
$app->post('/items', 'addItem');
$app->run();
function addItem() {
$request = Slim::getInstance()->request();
try {
echo json_encode('OK message');
} catch(PDOException $e) {
echo 'Error message';
}
}
?>
folders structure
|->main_folder
|-index.html
|->api
|->index.html
|->Slim
|-> (folder with Slim php library)
Here is a working example http://jsfiddle.net/acDb3/
Even without working REST I didn't got the error you have.
I noticed there is no Content-type for JSON output. You may add this line to the index.php to make it work.
$app->contentType("application/json");
You can also get success and error callacks to see if they are have been called.
test.save(null, {
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});

jquery $.get() not working on localhost

I'm trying to use jquery $.get() to obtain values from a server file.
Both files are currently on my machine in the /var/www directory (using linux).
I am aware of the cross-domain restriction for ajax, hence I placed the two files in /var/www.
The "client" file (f1.htm) is:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.9.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.get( "f11.htm", function( data, status ){ alert( "1" ); } );
/*
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","f11.htm",false);
xmlhttp.send();
alert( xmlhttp.readyState + " " + xmlhttp.status );
*/
alert( "2" );
</script>
</body>
</html>
while the "server" script (f11.htm) is simply:
<html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
</head>
<body>
<?php
echo "server text";
?>
</body>
</html>
the client script ("f1.htm") gets stuck at the $.get() line. I've tried this with xmlhttprequest (which is commented), and it works. why is the $.get() line not working?.
TIA
You can try this code to examine the error function being returned instead of the shorthand $.get.
$.ajax({
type:'GET',
url: 'f11.htm',
data: {},
success: function(data) {
console.log(data);
}, error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});

How do you automatically refresh part of a page automatically using AJAX?

$messages = $db->query("SELECT * FROM chatmessages ORDER BY datetime DESC, displayorderid DESC LIMIT 0,10");
while($message = $db->fetch_array($messages)) {
$oldmessages[] = $message['message'];
}
$oldmessages = array_reverse($oldmessages);
?>
<div id="chat">
<?php
for ($count = 0; $count < 9; $count++) {
echo $oldmessages[$count];
}
?>
<script language="javascript" type="text/javascript">
<!--
setInterval( "document.getElementById('chat').innerHTML='<NEW CONTENT OF #CHAT>'", 1000 );
-->
</script>
</div>
I'm trying to create a PHP chatroom script but I'm having a lot of trouble getting it to AutoRefresh
The content should automatically update to , how do you make it do that? I've been searching for almost an hour
I would take that PHP functionality you have and putting it in a sperate page that returns JSON. From there you can call that method using jQuery and the AJAX tools built in. Really simple. Start here for jQuery: http://api.jquery.com/category/ajax/
you'll need to set up a server side script that renders only the contents of the chat div and use ajax to grab that. it can be done with jquery quite easily:
In your html document:
<head>
...
<script src="/path/to/jquery.js" type="text/javascript"></script>
<script>
var chatUpdateInterval = null;
function initChat() {
chatUpdateInterval = window.setInterval(updateChat, 5000); /* every 5 seconds */
}
function updateChat() {
$.ajax({
url: '/url/path/to/your/script.php'
,dataType: 'HTML'
,success: function(data, status, xhr){
$('#chat').append($(data).html());
}
});
}
$(document).ready(function(){
initChat();
});
</script>
...
</head>
<body>
<div id="chat">
please stand by while we're firing up the coal!
</div>
</body>
Note that this won't be really good, it's just a sample to get you started. you should look into jquery's $.ajax

Categories

Resources