I make an AJAX request:
//javascript
var rq = new XMLHTTPrequest();
rq.open('POST','test.php', true);
rq.send(JSONString);
In "test.php" I make something like:
//php
$data = "Hello";
And I want to return $data back to my JS (via rq.responseText I suppose) how should I do it?
You can use XMLHttpRequest.response to get the response.
Please see the following code snippet and check out the documentation for details.
var url = 'test.php'; //A local page
function load(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.response);
}
}
xhr.open('POST', url, true);
xhr.send(JSONString);
}
You can return JSON from PHP. EX
in javascript:
$.ajax({
url : url_api,
method : 'GET',
dataType : 'json',
data : {},
success : function (data) {
var hello = data.data;
}
});
In PHP:
<?php
$array = ['data' => 'hello'];
echo json_encode($array);
Dammit, the problem was that I did
rq.onload = alert(rq.response);
Instead of
rq.onload = function()
{
alert(rq.response);
}
Sorry pals
Related
I don't know why but when I do request JSON in this way console log prints nothing:
var xhr = new XMLHttpRequest();
function elenco_studenti() {
var url = "/controller?action=student_list";
xhr.responseType = 'text';
xhr.open("GET", url, true);
xhr.onreadystatechange = print();
xhr.send(null);
}
function print(){
console.log(xhr.responseText);
}
Instead when I do request JSON in this way, it works:
$(document).ready(function(){
$.ajax({
url: '/controller?action=student_list',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
});
Can you help me? Thank you very much.
Assign the function reference instead of invoking the function
xhr.onreadystatechange = print();
to
xhr.onreadystatechange = print;
and wait for the actual response to be ready
function print() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
link to docs
var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&search=' + search;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url);
ourRequest.onload = function() {
var data = JSON.parse(ourRequest.responseText);
console.log(data);
};
ourRequest.send();
Can someone tell me why i am not able to get parsed data in my console.
You need to add one more parameter to your url variable to make this request work -
origin=*. Add it and your code will be fine.
Check how I've changed the url variable. Wikipedia API requires the request origin included in the parameters string.
document.getElementById('do-search').addEventListener('click', search);
function search(){
var search = document.getElementById('search').value;
var url='http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search='+search;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url);
ourRequest.onload = function() {
var data = JSON.parse(ourRequest.responseText);
document.getElementById('results').innerHTML = data;
};
ourRequest.send();
}
<input id="search" type="text">
<button id="do-search">Search</button>
<div id="results"></div>
Well i made it to work with the following code.
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});
i have a simple ajax script that sends 3 variables to an external php script, it then adds them into an array and sends the array back, and i want it to output it in the javascript console, so that i can check that the variables are being passed back successfully, however when i run the script nothing appears in the console, only that
XHR finished loading: "http://localhost/blank/scripts/ajax/profile_password_submit.php".
Here is the ajax
$("#pro_content_password").submit(function() {
var url = "scripts/ajax/profile_password_submit.php"; // the script where you handle the form input.
var js_array=new Array();
$.ajax({
type: "POST",
url: url,
data: $("#pro_content_password").serialize(), // serializes the form's elements.
success: function(data){
js_array=data;
console.log(js_array);
},
dataType: 'json'
});
return false; // avoid to execute the actual submit of the form.
});
Here is the external php script
session_start();
include '../../connect.php';
$user_id = "";
$user_id = $_SESSION['userId'];
echo $user_id;
if(empty($_SESSION['userId'])){
echo "user id session not set";
exit;
}
$old_password = $_POST['pro_content_password_old'];
$new_password = $_POST['pro_content_password_new'];
$new_password1 = $_POST['pro_content_password_verify'];
$password_array = array("old"=>$old_password,"new"=>$new_password, "new1"=>$new_password1);
echo json_encode($password_array);
Any ideas? Also i am using Google Chrome console
It looks like you're not outputting a proper JSON object. I don't know for a fact, since you haven't shared what your PHP script is outputting, but I have a feeling that this line in that is what's causing your problem:
echo $user_id;
You're not just outputting a JSON encoded PHP array, you're also outputting the $user_id variable.
jQuery's ajax success callback only fires if it receives a properly formatted JSON object, which yours is not. It probably looks something more like this:
1234{"old": "oldpass", "new": "newpass", "new1": "newpass1"}
You need JSON.stringify :
$("#pro_content_password").submit(function() {
var url = "scripts/ajax/profile_password_submit.php"; // the script where you handle the form input.
var js_array=new Array();
$.ajax({
type: "POST",
url: url,
data: $("#pro_content_password").serialize(), // serializes the form's elements.
success: function(data){
js_array=JSON.stringify(data);
console.log(js_array);
},
dataType: 'json'
});
return false; // avoid to execute the actual submit of the form.
});
Here is the final working version now, its a lot different to my original but it works a lot better
<script type="text/javascript">
function submit_profile_password(){
//var results = document.getElementById("results");
var result_error = document.getElementById("pro_content_error_password");
var old_error = document.getElementById("pro_password_old_comment");
var new_error = document.getElementById("pro_password_new_comment");
var new1_error = document.getElementById("pro_password_new1_comment");
var oldPass = document.getElementsByName("pro_content_password_old")[0].value;
var newPass = document.getElementsByName("pro_content_password_new")[0].value;
var new1Pass = document.getElementsByName("pro_content_password_verify")[0].value;
var vars = "oldPass="+oldPass+"&newPass="+newPass+"&new1Pass="+new1Pass;
var hr = new XMLHttpRequest();
hr.open("POST", "scripts/ajax/profile_password_submit.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
//results.innerHTML = "";
for(var obj in data){
if(obj == "old"){
old_error.innerHTML = "";
old_error.innerHTML = data[obj];
}else if(obj == "new"){
new_error.innerHTML = "";
new_error.innerHTML = data[obj];
}else if(obj == "new1"){
new1_error.innerHTML = "";
new1_error.innerHTML = data[obj];
}else if(obj == "result"){
result_error.innerHTML = "";
result_error.innerHTML = data[obj];
}
//alert("Key = "+obj+"value = "+data[obj]+"");
}
}
}
hr.send(vars);
//results.innerHTML = "requesting...";
return false;
}
</script>
Thanks all for the help
hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy
Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});
Try this :-
$data = json_decode($_POST['data'], TRUE);
I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});
Note : Please note the question may be silly as I've just begun client-side development.
I need to make an XHR POST request to a dynamic link retrieved through JSONP. However for some reasons it doesn't work. Basically the POST url "youtube_url_upload" becomes undefined. xhr.open("POST", youtube_url_upload);
Here is the code snippet :
var get_youtube_service_url ="http://video.example.com/youtubeupload?jsoncallback=?";
$.ajax({
type: "GET",
url: get_youtube_service_url,
dataType: "jsonp",
cache : false,
success: function(data) {
// get youtube
// var y_url = data.url;
var token = data.token;
var youtube_url_upload = data.url + "?nexturl="+encodeURIComponent("http://selling.example.com/youtube.html");
calltoken(token);
uploadFile(youtube_url_upload);
}
});
var bytesUploaded = 0;
var bytesTotal = 0;
......
function uploadFile(youtube_url_upload) {
var xhr = new XMLHttpRequest(youtube_url_upload);
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", youtube_url_upload);
xhr.send(fd);
intervalTimer = setInterval(updateTransferSpeed, 500);
}
.....
the success callback get the a string as "data", not object
it's may be a json so use
$.parseJSON ( data )