simple jsonp not working with php server - php

I tried following some basic examples, and it is not working. I am not sure I completely understand jsonp, but I followed the basic tutorials and on an intuitive level, I can't see anything wrong. (Of course, I am missing something, hence the question).
JavaScript code:
postData = $(this).serialize();
console.log(postData);
$.ajax({
data: postData,
url: 'externaldomain.php',
dataType: 'jsonp',
success: function(data){
console.log(data);
alert('Your comment was successfully added');
},
error: function(){
console.log(data);
alert('There was an error adding your comment');
}
});
PHP code:
$tag = mysql_real_escape_string($_GET["callback"]);
The annoying part is that it is not even showing me an error to Google for.
Can anyone help out figuring the problem please?

Since you haven't posted your full or relevant PHP code I'm going to assume it looks like this
$tag = mysql_real_escape_string($_GET["callback"]);
echo $tag."(";
// print json here
echo ")"
I'm not really sure how jquery handles jsonp requests but what I used to do is add a new script tag to the DOM that looks like this
<script> function cb(json) { alert(json); } </script> // (I)
<script src="{url}?callback=cb"></script> // (II)
When (II) is loaded, and because we have a callback then the script that we are including in the DOM looks like this
cb({
// json goes here
})
which pretty much is like a function call to some function called cb that we are using. It is therefore natural to have an implementation of cb (which is in (I)). That implementation is similar to the success(data) function in jQuery's ajax. It is used to use and manipulate the json requested
However I noticed that you are doing a POST request along the ajax call with jsonp. Unfortuantely (according to this question How to make a jsonp POST request that specifies contentType with jQuery?) doing POST with JSONP is not feasable due to implementation pursposes.

You can't POST using JSONP... it simply doesn't work that way...
So you can usually only perform GET requests. You can NOT perform POST requests.
For details about how jsonp work look at this nice article. jsonp-how-does-it-work
For more clearification :
See Other SO question Link1 Link 2
But there is work around for that with some limitations look at this Using PUT/POST/DELETE with JSONP and jQuery. (for me nothing works at all)

Related

parse HTML table from third party server (jQuery or PHP)

I have a HTML table with sport results on a third party server that I would like to parse as a JSON or XML so I can grab me the values out of it...
I would prefer to do this with jQuery and already played around with $.ajax but I don't get it running :/
I also thought about a PHP script running on my server and doing something with file_get_contents() and parsing the result as JSON - without success...
Dose anyone have an idea - what is the best solution to do what I want? I need a thought-provoking impulse ;)
My jQuery attempt:
$.ajax({
dataType: "jsonp",
url: "....",
success: function(data) {
console.log(data);
},
error: function() {
console.log('error');
}
});
Running in to an error:
As per comments:
For cross-site content, make a proxy script using PHP. All this will need to do is grab the remote content and echo it out.
Your ajax request will then point to this script instead, and you will be able to parse the response using standard jQuery functions as if it were a normal page e.g. $(data).filter('table');
Your 'dataType' is wrong? Shouldn't that be either 'html' or 'json' since i see you are receiving HTML content.

$_REQUEST works, but $_POST doesn't -

Thank you for sharing in my headache - here is the short speil:
Recently inherited a poorly coded WordPress site - which leveraged a WP Contact Form 7 -
I stripped all the WP-CF code out (due to the fact that the WordPress had been stripped out before it was handed over to me) -- just to make a simple patch script and get on with real work.
I replaced the WPCF scripts with this one: (to make things as easy as possible for me):
jQuery(document).ready(function() {
$ = jQuery;
console.log("Ready");
$("#quack-button").click(function(e) {
console.log("Quack");
e.preventDefault();
e.stopPropagation();
POSTDATA = $.param($("#quack-form").serializeArray());
$.ajax({
method : "POST",
url : "http://www.domain.com/contact.php",
data : POSTDATA,
success : function(response) {
console.log(response);
alert("Thank you ! We'll get in touch as soon as we can -! ");
}
});
});
});
but, after trying many different forms/combinations of $.param and serialize -
The server side script continued to return a blank array....
print_r($_POST);
However, when I changed it to print_r($_REQUEST) - it all worked, fine....
Now, what possible ways could this even happen? What blindspots am I missing that could create this sort of scenario...?
This is the most baffling I've dealt with in some time... I appreciate any understanding anyone can throw at this...
If you want to send it as $_POST, change this line:
method: 'POST'
to this:
type: 'POST'
According to docs, thats the way of setting it.
type (default: 'GET')
Type: String
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

jQuery.ajax() v1.5 returns "parsererror" for json data

I have this function for getting a server id from a list. The function always returns "parsererror". I have looked at the JSON data returned but I cant seem to get it working, since jQuery have rewritten the ajax in v1.5.
function server_id()
{
$.ajax({
type: "GET",
url: "http://localhost/server_list.php",
dataType: "json",
success: function(data, status) {
alert(status + "\n\n" + data.server_id);
},
complete: function(data, status){
alert(status);
}
});
}
server_list.php
header('Content-type: application/json');
$output['server_id'] = '123';
print json_encode($output);
In firebug Net >> XHR it reads it as JSON as it brings up the tab and the Response tab shows what is below.
{"server_id":"123"}
I have also tried setting the content type header like below but having no luck.
Content-type: application/json
UPDATED
I only get "parsererror" if the validation plugin is loaded from http://bassistance.de/jquery-plugins/jquery-plugin-validation docs.jquery.com/Plugins/Validation v1.7.
If you add the plug jquery automatically adds the jsonp callback to the query string even when you set to false or dont include the parms for jsonp. Very Strange
Any ideas on how to fix?
Thanks
The simple solution here seems to be that jQuery 1.5 is not compatible with 1.7 of the validation plugin. Downgrading to jQuery 1.4.x (or otherwise patching or removing the validation plugin code as philhag suggested) solves the issue.
Huge thanks to those on this thread who identified the conflict. It saved me a bunch of headaches having to debug the jQuery code.
You seem to want regular json communication (dataType is "json" instead of "jsonp" and server_list.php sends json), but you're setting jsonp options. Remove the jsonp and jsonpcallback lines. Setting jsonp to false does not mean you disable it!
When these two lines are commented out, everything seems to work fine.
I suffered for days before finding this thread, thanks to those who pointed at jQuery.validate as the culprit.
In my testing it actually seems to be jquery.validate-vsdoc.js which is causing the issue, not the plugin itself, in case that's of any use to anyone else.

How to get serverside information into javascript?

I don't know how to ask this question that's why I'm going to simulate what I need, some developers make what I need by rendering javascript with php. A simple sample file would look like:
my_javascript_file.php
<?php include "my_class.php"; ?>
$(document).ready(function(){
$.ajax({
url: "<?php $my_obj->post_url(); ?>",
success: function(){
alert("Post successful")
}
});
};
which outputs following:
$(document).ready(function(){
$.ajax({
url: "/post_handler.php",
success: function(){
alert("Post successful")
}
});
};
my question comes there, is there any way to achieve that with pure js techniques?
Thanks,
Sinan.
P.S. This is just a simple example of course I can hardcode post url here, or get url by location object etc with javascript I hope you get what I mean...
EDIT: Sorry for confusions by the terms I used, it is just getting some information from my application and writing to my javascript dynamically. I don't mean comet or data encode etc.
What I want to know is how to use server-side data on javascript files(if there is any way). Like what php method does on my example, it simply echoes a string which comes from my application. Is there a way to do that by a javascript library or a framework, like a template engine you assign vars and use it in that template system. Hope it's more clear now.
Yes there is a way, but its odd. You can use the jaxer server. It lets you run javascript on the server.
EDIT:
As I said in my comment I don't think you want to be downloading extra js to the client in order to implement a templating engine. Its probably a separation or decoupling that you're talking about. In which case you could have the following in a separate js file:
var myObject = {
var1 : '',
var2 : 0,
init : function(options) {
var1 = options.var1;
var2 = options.var2;
$('#someElem').click(function() {
// do stuff
return false;
};
}
};
and then call it like this from your html page
<head>
<script type="text/javascript">
var options = {
var1 : <?php echo "hello" ?>,
var2 : <?php echo 1 ?>
}
myObject.init(options);
...
i am not sure i know what you mean by "push" ... if it is a real server push, you should look at comet servers ...
also, to me it's unclear what "pure js techniques" are ... you can do this without jQuery of course ... but pure JS, as the languages primarily designed to manipulate the DOM will not suffice of course ... you need AJAX-like approaches ... however there was a proposal for push in HTML5, but yeah, this is gonna take some time ...
so i hope this helps ... but maybe you should clarify your question a little, i am sure you will get better answers ... :)
greetz
back2dos
You could ask the server for the URL using .get or .ajax (assuming your urls.php will handle this properly and return a proper string - or JSON, in which case you might as well use .getJSON - with the URL in it). For example (untested of course):
$.get("urls.php", { operation: "post_handler" },
function(data){
$.ajax({
url: data,
data: eventData,
success: function(){
alert("Post successful");
}
});
});
================= Edit: New Potential Answer =====================
Say you manage to retrieve JavaScript Data Objects from the server, do you wish to inject the JavaScript data you obtained in your HTML markup, client-side?
If that's the case you might look at IBDOM: http://ibdom.sf.net/
I wrote it, we've had it in production on a number of a sites for a couple of years.
================= Old Answer Below ====================
So you want "eventData" to be "something" which can be consumed by JavaScript.
I'd recommend first taking a look at JSON in PHP:
[REMOVED link to JSON in PHP, not needed]
Then your PHP Code might resemble this:
<?php include "my_class.php"; ?>
$(document).ready(function(){
$.ajax({
url: "<?php $my_obj->post_url(); ?>",
data: <?php json_encode ($my_obj->getData()); ?>,
success: function(){
alert("Post successful")
}
});
};
So the idea here, is that the value of your "data:" field would become a JSON Object graph generated by PHP on the server.

Is this a jQuery bug, or am I missing something?

I am using jquery-1.3.2 in an AJAX web application. I use the jQuery ajax $.post() method to submit requests to the server.
On the server I am using php to build an array and then json_encode the answer. Then on the client I use the callback function of the AJAX post method to process the response.
All works well until I use the $.post() method to send variables to the server. If I send variables to the server, the response I get back is [object Object] and therefore I am unable to parse it. I have a work around at the moment that when posting variables I request a HTML response and then I parse that.
So the code involved taken from my site is:
The Jax call:
$.post("inc/sendfeedback.php", {NAME: name,TYPE: type,EMAIL: email,COMMENT: comment}, function(data) {PostData(data);}, "json");
So the PostData code looks like this:
function ProcessData(data)
{
//alert(data);
var jo = eval("(" + data + ")");
if(jo.result == "true")
{
if(jo.data != "" && jo.element != "")
{
$(jo.element).html(jo.data);
}
}
SMessage(jo.error);
}
If I uncomment the above code the alert with have in it [object Object].
if I remove the Post variables from the call it works fine.
The server code look like this:
$arr = array ("result" => $result,"data" => $data,"error" => $error,"element" => $element);
echo(json_encode($arr));
Is this a bug with the jQuery library, I tried it with the 1.2 version however its was still present there? I also search the jQuery site and can not find anyone having this issue.
So I assume I am missing something. But what?
$.ajax({
url: "script.php",
global: false,
type: "POST",
data: {NAME: name,TYPE: type,EMAIL: email,COMMENT: comment},
dataType: "json",
contentType: "application/json",
success: function(data){
alert(data.result);
}
}
No need to eval, jQuery evals/parses it before calling the success callback.
eval = pure evil
http://docs.jquery.com/Ajax/jQuery.ajax#options
Because you are using an associative PHP array, json_encode will return a string representation of a Javascript Object and not a Javascript Array. However, you should still be able to process it in a similar fashion to an array:
for (var key in data)
{
var item = data[key];
}
I would strongly recommend you download Firefox+Firebug addon and use the console API for debugging/dumping what is being returned by the server.
I have since registered and now can't post comments into this thread without reputation and can not see any easy method to claim this question as mine.
Deviant, your suggestion of using the $.ajax() method worked. Reason it didnt work for me the first time was I submitted the post data as a JSON object when the server code was expecting POST data.
So I fixed my javascript to call the server script correctly and everything works exactly as it should.
So the conclusion is, the $.post() method has a bug in it. I have not tracked it down but line 3633 is were the post method makes the call. I started digging however have not yet found the issue.
I qualify this by the fact the $.ajax() to the same server script and the same javascript processes the response and it all works, use the $.post method and my script fails with the return even through the return object appears to be a valid JSON object.
Thanks for the help guys. Now to go and remove all my $.post calls for $.ajax calls.
The result of all this can be seen at www.pygames.net
Cheers
Shane
a.k.a FrogSkin

Categories