Can't get json result on my phonegap page - javascript

I'm trying to get some json data in my application, but it won't come in the result function.
function myLoad(){
output.innerHTML = 'in the load';// + items;
var myJsonUrl = 'http://....be/.../lineup.php';
$.getJSON(myJsonUrl, function(data) {
output.innerHTML = "IN THE FUNCTION";
});
output.innerHTML = 'END load';
}
In mu output div I can see 'in the load' so it stops at the .getJSON part.
I've included the right jquery libraries (jquery mobile and jquery1.4) and the json from the specified url validates.
What am i doing wrong?
EDIT:
In chrome it works sigh.
I was testing it in Eclipse web browser since I'm working for an Android application.
Apperantly that browser s**ks.
Thx for the idea Sir Troll
=> still can't answer my own question

I might be a bit late in answering this but was working on phonegap and had similar issue. You would need to add the URL in your phonegap.plist file under ExternalHost Array.
I added that and I am now getting JSON data from an external URL.
Hope this helps.

Are you sure you're not getting the data? Your example would most likely overwrite END load with IN THE FUNCTION, since the callback will be executed after the function finishes.
So output.innerHTML would get the values like this:
1. "in the load".
--> Ajax request start
2. "end load"
--> Ajax request finishes
3. "in the function"
I would suggest trying to output data in the callback, and remove the innerHTML changes from outside the callback function.

Is the jsonUrl in the same domain as your script? I'm not really sure, but I think you cannot do cross-domain requests with AJAX scripts.
Update:
Is the php script sending json headers?
header('Content-type: application/json')

Related

post request returns ok but no data and function not working

Ok, I've been putting together a website for the las couple of weeks.
I got everything working before moving on to next phase. Made a lot of changes but none to the functions that I'm talking about.
basically I have a code:
var grabbedItems = [];
function grab(){
$.post(questions.php, {"grab":"grab"}, function(data){
grabbedItems = data;
console.log(grabbeditems);
}, "json");
}
The function gets called on page load. The problem is that network tab says 200 ok for questions.php, but console.log() doesn't even log anything. I can't think what i've done wrong. i haven't even changed the page that the function is on. What could be the problem, apache says no errors network says 200 ok. But functions are not working. I don't think there is anything wrong with my JQuery file, that returns 200 ok aswell.
Any help would be appreciated.
The problem was with the data in one of the mysql fields. I used a £ sign. for some reason the JSOn didn't like it. Maybe I should look into the coding of the database entries.

Passing data from PHP to JS and JS to PHP

Hi I'm trying to learn PHP and javascript, therefore I tried to do an exercise about passing data but I didn't understand the js function and currently unable to do anything.
Here is the code
php-code.php
$v1=$_GET['v1'];
$v2=$_GET['v2'];
$v3=$_GET['v3'];
//Some operations about them
echo $output;
my-js.js
var v1 = $('#v1 option:selected').val();
var v2 = $('#v2 option:selected').val();
var v3 = $('#v3 option:selected').val();
//This is where I want to pass these variables to my php file and get the output
//But i don't know how
js-execute.php
//this is where my js gets the variables at first
PHP is a server-side language while JavaScript is a client-side one. This means that PHP will be executed when someone requests a page, but the browser will only get the result of the PHP code. On the other hand, JavaScript is sent to the browser and the browser will execute it at the appropriate time (when the page loads or when an event happens). That's why if you look at the source code of a page, you will be able to see the JavaScript code, but never the PHP code.
If you want to pass values from JavaScript to PHP, you will need to make a remote call to a PHP file. PHP isn't like JavaScript – once it's done running its code, it won't be able to respond to anything without a reload of the page.
The easiest way to send something to a PHP file and fetching the result with JavaScript can probably be achieved with JQuery. It has a function $.get which will fetch a given URL. Just be sure to properly validate the input on the server side – never trust user input.
JavaScript (using JQuery to send v1, v2 and v3 to page.php)
function requestPage(v1, v2, v3) {
$.get('page.php', {'v1':v1, 'v2':v2, 'v3':v3}, function(data) {
alert(data);
});
}
PHP (a trivial example)
// Be sure to properly validate input!
if(isset($_GET['v1']) && is_scalar($_GET['v1'])) {
echo strrev($_GET['v1']);
}

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

Check iframe status after AJAX File Upload with Rails

There is a similar post Retrieving HTTP status code from loaded iframe with Javascript but the solution requires the server-side to return javascript calling a function within the iframe. Instead, I would simply like to check the HTTP status code of the iframe without having to call a function within the iframe itself since my app either returns the full site through HTML or the single object as JSON. Essentially I've been trying to implement a callback method which returns success|failure dependent upon the HTTP status code.
Currently I have uploadFrame.onLoad = function() { ... so far pretty empty ... } and I am unsure what to check for when looking for HTTP status codes. Up until now, I've mainly relied upon jQuery's $.ajax() to handle success|failure but would like to further understand the mechanics behind XHR calls and iframe use. Thanks ahead of time.
UPDATE
The solution I came up with using jQuery
form.submit(function() {
uploadFrame.load(function() {
//using eval because the return data is JSON
eval( '(' + uploadFrame[0].contentDocument.body.children[0].innerHTML + ')' );
//code goes here
});
});
I think the best solution is injecting <script> tag into your iframe <head> and insert your "detecting" javascript code there.
something like this:
$('#iframeHolderDivId').html($.get('myPage.php'));
$('#iframeHolderDivId iframe head').delay(1000).append($('<script/>').text('your js function to detect load status'));
Maybe it's not the best solution but I think it works

I want to request JSON inside of a WordPress page

For the last few hours I've been trying to set up this http://code.google.com/apis/books/docs/dynamic-links.html on a WordPress blog. Google's API sends back a JSON response (which is supposed to be "put" into _GBSBookInfo variable). However, that variable never is assigned so my javascript callback function explodes saying the variable doesn't exist. So far, all of my javascript is in the WordPress header.
I tried this outside of WordPress and it works fine.
This is the static page:
<script src="http://books.google.com/books?bibkeys=0307346609&jscmd=viewapi&callback=response_handler">
This is the handler:
function response_handler(data) {
var bookInfo = _GBSBookInfo["0307346609"]; // the var that doesn't exist
document.getElementById("test123").innerHTML = bookInfo.thumbnail_url;
}
Thanks for any help in advance, WordPress has been extremely frustrating by limiting so much! If I'm doing anything stupid please say so, I'm a new javascript programmer.
EDIT:
I've used firebug so far to identify the problem to be: the _GBSBookInfo variable never gets "created" or "exists". I'm not sure how javascript works at this level. Hopefully this helps.
ERRORS:
Error: _GBSBookInfo is not defined
Line: 79
Try replacing _GSBookInfo with data, like so:
function response_handler (data) {
var bookInfo = data["0307346609"];
document.getElementById("test123").innerHTML = bookInfo.thumbnail_url;
}
Based on your post, google returns this:
response_handler({
"0307346609": {
"bib_key":"0307346609",
....
"thumbnail_url":"http://bks2.books.google.com/books?somethumbnailstuff"
}
});
... so the above code should work for you.

Categories

Resources