I am trying to read data from a JSON data by jQuery. Bus for some reasons it deosnt work.
Here is my JSON file: http://goo.gl/PCy2th
and this is my code to get data:
$.getJSON("http://goo.gl/PCy2th", function(data){
$.each(data.PlayListArray, function(key, val){
alert(val.URL);
});
});
Here is the demo:http://jsfiddle.net/SVk77/
Any idea to fix it?
you can create web service for getting all music urls
PHP code:
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
$array = array("https://soundcloud.com/danial-sabagh/mane", "https://soundcloud.com/ajamband/gole-iran", "https://soundcloud.com/bibakofficial/kooch", "https://soundcloud.com/bibakofficial/mohammad-bibak-in-niz-bogzarad","https://soundcloud.com/kaishakhay/whine-and-kotch-j-chapri-f","https://soundcloud.com/amirtataloo/merci","https://soundcloud.com/amirtataloo/bikhiyal");// you can also apply your business logic and get url from database
echo json_encode(array("PlayListArray"=>$array));
return;
?>
JQuery code for calling & getting response from php web service
Javascript code:
$.ajax({
url: 'getMusicURL.php',
type: "GET",
dataType:'json',
success:function(data){
console.log(data);//using object data you access all music array
for(var i=0;i<data.PlayListArray.length;i++){
console.log(data.PlayListArray[i]);
}
}
});
You can achieve using Cross-Origin XMLHttpRequest
I.e
$(document).ready(function(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://goo.gl/PCy2th", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// JSON.parse does not evaluate the attacker's scripts.
var resp = JSON.parse(xhr.responseText);
}
}
xhr.send();
});
It Seems that your server who is returning the json is not supporting the request.
Demo
Related
This is my getJSON:
$(function () {
var neededData;
$.getJSON('/ajax/connected-devices-data.php', function(jsonData) {
neededData = jsonData;
console.log(neededData);
});
});
And this is my php:
use NET2GRID\Data\CurrentlyConnectedDevices;
require_once __DIR__ . "/../vendor/autoload.php";
header('Content-type: application/json; charset=utf-8');
$cd = new CurrentlyConnectedDevices();
$data = $cd->getConnectedDevicesFromDatabase();
print json_encode($data);
When I look at my site where I run this the console remains empty but according to what I'm used to there should be a json object there.
This is the jsonresponse I get from the php code when I run it individually:
{"SUCCESS":[[1493642582000,912],[1493718591000,909]],"PING_NOT_RECEIVED":[[1493642582000,631],[1493718591000,635]],"TCP_CNX_FAILED":[[1493642582000,7],[1493718591000,7]]}
What am I doing wrong in this code?
Try following AJAX code..
$.ajax({
method: "GET",
url: "/ajax/connected-devices-data.php"
}).done(function( response ) {
alert( "Response received: " + response );
});
--- UPDATE ---
Above code was not the solution of the question asked. It was the error on the web server which has not configured properly with PHP.
I want to fetch data when onclick is invoked. I have four div in my form and I want only a particular div to be reloaded and fetch data. while loading it should not discard the form data. Anyone help. Thanks in advance for people who are going to help me in this.
my code looks something like this
<div id="fetch">
<?php
//query to fetch data
?>
</div>
<div id="data4">
//dynamic data
//Want to retain this data even after fetch
</div>
In this case you should use AJAX.
Onclick you can send a xmlhttprequest (JS) to a separate php file, which returns the data you need (for example as string / JSON), and insert it into your website with JS.
Example:
function test()
{
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if(xhr.readyState==4 && xhr.status==200)
{
result = xhr.responseText;
document.getElementById("test_field").innerHTML = result;
}
}
xhr.open("GET","your_ajax_file.php",true);
xhr.send();
}
your_ajax_file.php returns the data you want to insert.
You mentioned you have a problem with function call, but you did not give more information. so i will give you an example how to write an ajax request, then you can maybe give me more detailed info on where your problem is.
$.ajax({
url: 'ajax_file.php',
type: 'post',
data: {var1: 'value1', var2: 'value2'},
success: function( data ){
console.log('ajax request successful! data: '+data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
And in your ajax_file.php do something like this:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
echo $var1.', '$var2;
edit: typo, changed val2 to var2 in ajax request
This code will send request to post parameters to php file:
var param = //some parameters;
var url = file.php;
xhttp.open("POST", url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(params);
I got the response but the php file produce some output like <td><tr>.....
How to get this result of php in some div of my html?
Thanks,
You use onreadystatechange to get the response:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
$('#mydiv').html(xhttp.responseText);
}
};
XHR is pretty complicated without using a Framework. Just use jQuery it will make this 1000x easier.
$.ajax({
url: "myfile.php",
type: "POST",
data: {
/* Params */
},
success: function(response){
/* Use your response here */
}
});
http://api.jquery.com/jquery.ajax/
I know how to use jQuery well, but I don't know so much pure JavaScript.
This is my jQuery code:
$(document).ready(function() {
$.get('http://jsonip.com/', function(r){
var ip_address = r.ip;
my_function(ip_address);
});
function my_function(ip_address){
var url = "Url_to my server hosted on a different domain";
var data = {number:"1286", ip: ip_address};
$.ajax({
url: url,
type: "POST",
dataType: 'json',
crossDomain: true,
data: {data: data},
success: function (data) {console.log(JSON.stringify(data));},
error: function (xhr, error) {console.log("There was an error and data was not posted.");}});}
});
What it does: it is pasted in any website, then it picks any visitors ip address and send that as JSON to my server as variable data.
Problem: the code is working perfectly okay in some sites but not all the sites due to jQuery dependency. And I want to remove this and use pure JavaScript.
I am getting great answers but CORS is not working, there failing them. I am using different domains since the site we are sending data to is hosted on another server.
As mentioned in my commment above, you do not need the first ajax request as you can get this information from the request headers (PHP Example below) from your AJAX request.
To make sure that your website(s) have jQuery loaded you can run a check in your script and load it in dynamically. Using some code from this answer. See below for an example:
// Anonymous "self-invoking" function
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 100);
}
};
// Start polling...
checkReady(function($) {
var url = "Url_to my server hosted on a different domain";
var data = {number:"1286", ip: ip_address};
$.ajax({
url: url,
type: "POST",
dataType: 'json',
crossDomain: true,
data: {data: data},
success: function (data) {console.log(JSON.stringify(data));},
error: function (xhr, error) {console.log("There was an error and data was not posted.");
});
});
})();
To get the IP Address from your ajax request: (PHP) Source
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
The annoying part is that you need to do a cross-domain POST to send your data. There's a W3C standard for this called Cross-Origin Resource Sharing (CORS). Check out this tutorial for more info.
You'll want to put this at the bottom of the page. Different browsers handle ready state change events differently, so let's just avoid them.
<script>
// Once the JSONP script loads, it will call this function with its payload.
function getip(ipJson) {
var method = 'POST';
var url = 'URL of your server';
// The XMLHTTPRequest is the standard way to do AJAX. Try to use CORS.
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
// Create your request body. It has to be form encoded. I'm not sure
// where you get `number` from, so I've hard-coded it.
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send('number=1286&ip=' + ipJson.ip);
}
</script>
<!-- Get the IP using JSONP so we can skip implementing that. -->
<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>
This probably only works in modern browsers, but it should work in most modern browsers.
Replace $.ready(function...) with document.addEventListener('DOMContentLoaded', function..., false).
Replace $.ajax with XMLHttpRequest:
var xhr = new XMLHttpRequest();
//var data = {number:"1286", ip: ip_address};
var data = new FormData();
data.append("number", "1286");
data.append("ip", ip_address); // As stated by Scriptable in the question comments, your server should be able to get it from the request headers.
xhr.onload = function() { console.log(JSON.stringify(this.response)); };
xhr.onerror = function() { console.log("There was an error and data was not posted.") };
xhr.open("POST", "URL to your server");
xhr.send(data);
How can I pass a a javascript array vArray to File.php , and retrieve the two values from vArray.
I tried:
<input type="button" id="button" onClick = "send_V();" >
<script>
// Creat Array with Values from checkboxes
$('input[type=checkbox]:checked').each(function() {
vArray.push($(this).val());
});
// Set array to only 2 values ( disable checkboxes)
var n = $('input[type=checkbox]:checked').length >= 2;
$('input[type=checkbox]').not(':checked').attr('disabled',n);
// Send array to File.php where I can manipulate its value1, and value2 to query db
function send_V(vArray)
{
$.ajax({
type: "POST",
url: "File.php",
beforeSend: function () {
$("#result").html("<option>Loading ...</option>");
},
data: "vArray="+vArray,
success: function(msg){
$("#result").html(msg);
}
});
}
</script>
and on the php side ( File.php)
$value = $_POST['vArray'];
var_dump(vArray);
but I am not able and sure how to manipulate a javascript variable. can someone show me a simple and effective method ?
What is wrong in this logic?
Thanks
Use json. Encode array in js (How do I encode a javascript object as JSON?), decode it in php (http://php.net/manual/ro/function.json-decode.php).
If you set up the ajax call with an object for the "data" parameter:
$.ajax({
type: "POST",
url: "File.php",
beforeSend: function () {
$("#result").html("<option>Loading ...</option>");
},
data: { vArray: vArray }, // here
success: function(msg){
$("#result").html(msg);
}
});
Then jQuery will create HTTP request parameters like this:
vArray[]=first value
vArray[]=second value
etc. On the server side, when you access
$vArray = $_POST['vArray'];
you'll get the array back. You don't have to explicitly mess with JSON if you don't want to, in other words.
Pure javascript for modern browser (needs support for formData & xhr2)(chrome,safari,ios,android,ie10)
js
var vArray=['a','b','c'],
json=JSON.stringify(vArray);//this converts the array to a json string
function ajax(a,b,e,d,c){ //Url,callback,method,formdata or{key:val},placeholder
c=new XMLHttpRequest;
c.open(e||'get',a);
c.onload=b;
c.send(d||null)
}
function whatever(){
console.log('json posted',this.response)
}
ajax('page.php',whatever,'post',{'json':json});
page.php
<?php
print_r(json_decode($_POST['json']));//converts the json string to a php array
?>
Another solution is to post the whole form
html
<form>
<input name="a" value="x">
<input type="radio" name="b" value="x">
//and many other input & text fields
</form>
js
function ajax(a,b,e,d,c){ //Url,callback,method,formdata or{key:val},placeholder
c=new XMLHttpRequest;
c.open(e||'get',a);
c.onload=b;
c.send(d||null)
}
function whatever(){
console.log('form posted',this.response)
}
var form=document.getElementsByTagName('form')[0],
fd=new FormData(form);
ajax('page.php',whatever,'post',fd);
php
<?php
print_r($_POST);
?>
xhr2
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
formData
https://developer.mozilla.org/en-US/docs/Web/API/FormData
I have tried the following that seems to work fine :
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
It is working really well for me. Code taken from http://www.developphp.com/view.php?tid=1185
Answers by #Pointy and #Cocco might be correct, I could not manage to implement it right with Jquery, neither wanted to use a Form.. Hope this helps someone