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

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");
}
});

Related

Failing to get simple SoundCloud javascript api method to work

I have the following code below :
<!DOCTYPE html>
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207",{}, function(user){
console.log("in the function w/ " + user);
});
</script>
</head>
</html>
The code should print the user name to the console however whenever I run this, my console gives the error of :
Failed to load resource: The requested URL was not found on this server:
file://api.soundcloud.com/users/3207?client_id=f520d2d8f80c87079a0dc7d90db9afa9&format=json&_status_code_map%5B302%5D=200
However if I were to directly http://api.soundcloud.com/users/3207.json?client_id=f520d2d8f80c87079a0dc7d90db9afa9, then I get a valid JSON result.
Is there something incorrect with my how I am using the SC.get function?
Thanks
Well, you should test your index.html locally on a web-server like Apache and not by opening it as a file.
Working example
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207", {}, function(user) {
console.log("in the function w/ " + JSON.stringify(user));
var res = document.getElementById("result");
res.innerHTML = JSON.stringify(user);
});
<script src="http://connect.soundcloud.com/sdk.js"></script>
<div id="result"></div>

got error when using javascript ajax json to retrieve php array

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];

Javascript function plays correctly old site but not new

I recently moved my companies website to one of our unused web servers in order to update the Joomla backend from 1.5.26 to the latest Joomla 2.5. We couldn't go to 3.x because of modules.I used SP Upgrade, and everything migrated brilliantly once I had my new theme and current modules installed.
We have a customized default theme and an assigned theme to the home page. Within the assigned theme (assigned to the home menu) directory, index.php has a script above the header. I will post this code below.
The old site can be found at the following link and when you first go to the site, you will see the video play.
cpmchurchministries.com/old
The new site can be found at the following link and when you first go to the site, you will see only an image.
cpmchurchministries.com/new
The code is the same for both sites, index.php:
<head>
<jdoc:include type="head" />
<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/css/template.css" type="text/css"/>
<script type="text/javascript" src="<?php echo $this->baseurl ?>/templates/<?php echo $this->template ?>/swf/swfobject.js"></script>
<script type="text/javascript">
swfobject.embedSWF("<?php echo $this->baseurl ?>/templates/chosenpeople/swf/cpm_logo.swf", "flash_logo", "245", "162", "7");
window.addEvent('domready', function() {
if($('default_header')) {
if(Cookie.get("cpm_movie") != "full") {
full_movie();
} else {
small_movie();
}
}
});
function small_movie() {
$('default_header').removeClass('full_movie');
$('default_header').addClass('small_movie');
swfobject.embedSWF("<?php echo $this->baseurl ?>/templates/cphome/swf/header_home.swf", "flash_header", "696", "157", "7");
}
function full_movie() {
$('default_header').removeClass('small_movie');
$('default_header').addClass('full_movie');
Cookie.set("cpm_movie", "full", {duration: 365});
swfobject.embedSWF("<?php echo $this->baseurl ?>/templates/cphome/swf/video_header.swf", "flash_header", "696", "400", "7");
}
</script>
<?php if ($editmode) echo '<link rel="stylesheet" href="'.$this->baseurl.'/templates/system/css/general.css" type="text/css" />'."\n"; ?>
Has anyone run into a similar issue? Is it possible to get any help?
Thank you. . .
The newer version of Joomla that you are using uses a newer version of the MooTools library so you need to make the following two function changes to the code:
OLD
window.addEvent('domready', function() {
if($('default_header')) {
if(Cookie.get("cpm_movie") != "full") {
full_movie();
} else {
small_movie();
}
}
});
function small_movie() {
$('default_header').removeClass('full_movie');
$('default_header').addClass('small_movie');
swfobject.embedSWF("/new/templates/cphome/swf/header_home.swf", "flash_header", "696", "157", "7");
}
function full_movie() {
$('default_header').removeClass('small_movie');
$('default_header').addClass('full_movie');
Cookie.set("cpm_movie", "full", {duration: 365});
swfobject.embedSWF("/new/templates/cphome/swf/video_header.swf", "flash_header", "696", "400", "7");
}
NEW
window.addEvent('domready', function() {
if($('default_header')) {
if(Cookie.read("cpm_movie") != "full") {
full_movie();
} else {
small_movie();
}
}
});
function small_movie() {
$('default_header').removeClass('full_movie');
$('default_header').addClass('small_movie');
swfobject.embedSWF("/new/templates/cphome/swf/header_home.swf", "flash_header", "696", "157", "7");
}
function full_movie() {
$('default_header').removeClass('small_movie');
$('default_header').addClass('full_movie');
Cookie.write("cpm_movie", "full", {duration: 365});
swfobject.embedSWF("/new/templates/cphome/swf/video_header.swf", "flash_header", "696", "400", "7");
}
EDIT for easy copy paste
I have this error on your "new site" :
GET http://cdn.wibiya.com/Toolbars/dir_0775/Toolbar_775982/Loader_775982.js 403 (Forbidden)
I can't access the "old site", there is a Joomla login page. It would be easier if we could access it to compare both sites.
As Pointy said, you are getting some errors in the Javascript console:
Uncaught TypeError: Object function
(){e(this);if(g.$prototyping){return this;}this.$caller=null;var
i=(this.initialize)?this.initialize.apply(this,arguments):this;this.$caller=this.caller=null;
return i;} has no method 'get' (index):27
GET
http://cdn.wibiya.com/Toolbars/dir_0775/Toolbar_775982/Loader_775982.js
403 (Forbidden) (index):249
Uncaught ReferenceError: JCaption is not defined (index):17
GET http://cpmchurchministries.com/main/flash/menorah_shine.swf 404
(Not Found)
When there are errors with Javascript, the flow is stopped, so your image on the header is not replaced by the video (is not a "video", it's a flash swf movie).
One of the offending codes are:
<script type="text/javascript">
window.addEvent('load', function() {
new JCaption('img.caption');
});
</script>
If you cannot remove this code, Try this link to get rid of the JCaption problem and try again your site.
By the way, to see the errors on the console, try using a Chrome Browser, Tools, Javascript console (a must for every webdev!)

Uncaught TypeError: number is not a function : While create dojo class

I am learning dojo
i have created a dojo class using declare as below
require(
["dojo/_base/declare"],function(declare){
return declare(null,{
constructor : function(){
alert("done");
}
});
});
and this is save in /learnDojo/root/test.js
and the index.html as below
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<script type="text/javascript">
var dojoConfig = {
async: false,
parseOnLoad: false,
isDebug : true,
packages:[
{ name:"base",
location:"/learnDojo/root"
}]
};
</script>
<script src="//localhost:8080/dojo1.9.0/dojo/dojo.js" type="text/javascript"></script>
<script type="application/javascript">
require(["base/test","dojo/_base/declare","dojo/domReady!"],function(test,declare){
var test = new test();
});
</script>
<body>
</body>
</html>
i have the index.html in the /learnDojo which is in webapps folder of the tomcat
When i load this from browser i am getting the error "Uncaught TypeError: number is not a function"
Why? any issue with code or dojo syntax for creating the class
When defining Dojo modules you should be using define(), not require(). So your /learnDojo/root/test.js file would look like this:
define(
["dojo/_base/declare"],function(declare){
return declare(null,{
constructor : function(){
alert("done");
}
});
});
The reason for this is that define() will actually return the object/value you returned in your callback (in this case the return declare(...) statement. A require() however will not return that value, causing strange errors.

Next and previous button using jquery

I am using a PHP Simple HTML DOM Parser to save a website as a htm file. I then use jQuery to extract a div from the file and put it into a div. I want to create a
Previous and Next button but the problem I have is that to do this I have to change the URL so the parser can get the page. I would really appreciate if you can help. Below is the code I am using.
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=1');
$html->save('site/rtnews.htm')
?>
<script type="text/javascript" src="site/jquery.js"></script>
<script type="text/javascript">
$('document').ready(function() {
$('#wrap').click(function (event){
event.preventDefault();
});
$("#wrap").load('site/rtnews.htm #postsArea');
});
</script>
</head>
<body>
<div id="wrap">
</div>
</body>
You will have to create a new php file for this and make an AJAX request to that file. I assume you have already realised that you cannot make a cross-domain request due to CORS.
Here is your new php file, let's call it proxy.php. It will proxy the request, responding with the page that is passed to it via GET :
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=' . $_GET["page"]);
echo $html;
?>
Your new JavaScript;
$('document').ready(function() {
var $wrap = $('#wrap'),
page = 1;
$('#next').on('click', function () {
getPage(++page);
});
$('#prev').on('click', function () {
getPage(--page);
});
var getPage = function (page) {
$wrap.load('proxy.php?page=' + page + ' #postsArea');
};
getPage(page);
});

Categories

Resources