Simple jQuery, PHP and JSONP example?
When you use $.getJSON on an external domain it automatically actions a JSONP request, for example my tweet slider here
If you look at the source code you can see that I am calling the Twitter API using .getJSON.
So your example would be:
THIS IS TESTED AND WORKS (You can go to http://smallcoders.com/javascriptdevenvironment.html to see it in action)
//JAVASCRIPT
$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?','firstname=Jeff',function(res){
alert('Your name is '+res.fullname);
});
//SERVER SIDE
<?php
$fname = $_GET['firstname'];
if($fname=='Jeff')
{
//header("Content-Type: application/json");
echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';
}
?>
Note the ?callback=? and +res.fullname
How to show jsonp response sent by php on a page
If you want to ouput the result thrown by php for your ajax result then
Create a div like this
<div id='yourDiv'></div>
Then inside the success event
success:function(data)
{
('#yourDiv').html(data);
}
Note :
If you prefer class then
<div class='yourDiv'></div>
replaced by
('.yourDiv').html(data);
Additional Data :
It's better to check the data in your success event like this
As you getting like this as response
{"success":1,"uid":"1","username":"admin","role":"admin"}
success:function(data)
{
if(data.success==1)
{
('#yourDiv').html('Welcome'+data.username); //You can append or do anything that you wish
}
else
{
('#yourDiv').html.('Fail');
}
}
Get a simple JSONP object from a remote server php file using ajax (and jquery) embedded in javascript directly in my wordpress page
I'd solve this creating a Shortcode Plugin to handle this specific case. What a plugin like include-php-in-pages-and-posts
does is a Shortcode. And what you're trying is too complex to be laying together with the HTML content (and all sorts of code mangling can happen inside WP visual/text-editor).
Here there is a full plugin example on How to Use AJAX in a WordPress Shortcode?
rename the shortcode to your liking, e.g,
add_shortcode( 'teleduino', array( $this, 'shortcode') );
.your actual PHP code has to be adapted into the methods
shortcode()
andget_random_posts()
. Thisget_random_posts()
would be yourget_teleduino_response()
and responsible exclusively for getting the response and returning the data or an error message. Then inshortcode()
you process the result and do the actual output.the Shortcode also outputs a button that triggers the Ajax call that executes
get_random_posts()
again inquery_rand_post()
.in sum, you gotta adapt this three methods (functions inside a class) to your logic.
I think you can drop the
ob_start
and send the response back to jQuery withwp_send_json_success( $results );
, or do some pre-processing of the result and send back only relevant infomaybe instead of cUrl, you could use
wp_remote_get()
jQuery JSONP Call towards PHP backend: No HTTP response
This will obviously NOT work if you did not set up your SSL certificates properly.
This works properly when I transform the https to http: http://jsfiddle.net/eysEe/
var u = "test";
var p = 1234;
var symbols = false;
var pl = 16;
var secret = "c68f39913f901f3ddf44c707357a7d70";
$.ajax({
url: "http://serve.pin2pass.com?index.php",
dataType: 'jsonp',
type: 'GET',
data: {
p: p,
u: u,
s: symbols,
pl: pl,
secret: secret
},
contentType: "application/json; charset=utf-8",
async: false,
success: function(data) {
$('#test').text(data.message);
},
error: function(data) {
$('#test').text("SDf");
}
});
You can tell if you have bad SSL installation when "https://serve.pin2pass.com?index.php" leads to a risky page. Maybe you never intended to put it in https mode ?
simple JSONP & PHP example not working
The are two different issues here, with different answers
The reason it doesn't work when you use $.getJSON()
and put the name of the callback literally in the URL is because of the way in which jQuery works.
Firstly lets look at how jQuery detects that your $.getJSON()
call is expecting JSONP if you don't pass any options that indicate it explicitly in the settings object - it uses this regular expression:
/(=)\?(?=&|$)|\?\?/
This looks explicitly for either =?
in the query string or a query string consisting of nothing but a single ?
- in essence, the question mark is required for detecting that the URL will return JSONP.
Without it, jQuery makes an Ajax request using XHR and the correct data is returned by the server. What happens next depends on the Same Origin Policy. If, like the code you show, the server indicates via Access-Control-*
headers that the request is allowed, the data will be accessible just liek it would be with an Ajax request to the client's origin server. If these headers are not present, the data returned will not be accessible to the client code.
But, crucially, because it just makes a standard Ajax request and does not add a <script>
element to the DOM, it means that the response text is never evaluated as Javascript code - the crucial last-step in the JSONP mechanism.
The second version is a little trickier to answer and know that the answer is correct with the information provided, but with the HTML layout you show above I'm reasonably confident this is the reason: Your HTML elements are defined in the wrong order.
When processing the DOM on page load, processing halts at every <script>
element while the associated Javascript is synchronously loaded and processed. This is to ensure that all Javascript is executed in the intended order, and that any calls to things which directly modify the DOM in a location specific way - such as document.write()
(which you should never use, in case you don't know) - are honoured correctly.
The upshot of this is that if you placed the <script>
element in the DOM before the <p id="result">
tag, the result tag doesn't actually exist at the point where the process()
function is called. And because you used a jQuery selector instead of document.getElementById()
, it swallows the error that would have resulted if you had tried to modify it directly.
This is the reason that many Javascript developers (including myself) will now tell you that you should place your <script>
tags as the very last elements in the <body>
, as it gives a perceived performance improvement - even though in reality it takes exactly the same amount of network time to load and process all the page resources, it allows the browser to render the page quicker. Doing this also negates the need to use things like $(document).ready()
/DOMContentLoaded
events to delay execution (which, incidentally, would also solve this problem, but in a slightly messier way).
Creating A Simple AJAX / jQuery / PHP SELECT * / JSON
May be something like this with jQuery AJAX:
$.ajax({
type : 'POST',
url : 'path/to/your/file.php',
success : function(data){
console.log(JSON.parse(data));
},
});
Related Topics
Are PHP Variables Passed by Value or by Reference
Example of How to Use Bind_Result VS Get_Result
PHP Reading Shell_Exec Live Output
Preserving Session Variables Across Different Domains
Convert Dot Syntax Like "This.That.Other" to Multi-Dimensional Array in PHP
Achieve Hierarchy, Parent/Child Relationship in an Effective and Easy Way
Replace the Variable Price Range by the Chosen Variation Price in Woocommerce 3
How to Use a JavaScript Variable as a PHP Variable
How to Filter a Two Dimensional Array by Value
PHP/MySQL Insert Row Then Get 'Id'
PHP Code to Convert a MySQL Query to Csv
How to Set Http Header to Utf-8 Using PHP Which Is Valid in W3C Validator
Json_Encode PHP Array as Json Array Not Json Object
How to Loop Through Two Arrays At Once
Does PHP Have Short-Circuit Evaluation
Is There a PHP Function Like Python'S Zip
Call to a Member Function Prepare() on a Non-Object PHP Help