how to set a dynamic URL to the XHR POST parameter? - javascript

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 )

Related

How to get PHP variable from JS AJAX request?

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

Request JSON by AJAX in two ways

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

Using AJAX GET request to pass the value of <option> tags to the URL

I want to pass options' values to the URL whenever the users select an option. For example these are the options:
Option 1
Option 2
Option 3
And this is the URL: http://example.com/products
When he selects an option among those 3, the URL changes into this: http://example.com/products?option=option1
I tried vanilla Javascript XMLHttpRequest for this, and this is my code:
function ajaxFormValidate(_method, _url, _callback, _fallback, _sendItem) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState < 4) {
return;
}
if(xmlHttp.status !== 200) {
_fallback(xmlHttp.response);
return;
}
if(xmlHttp.readyState === 4) {
_callback(xmlHttp.response);
}
};
xmlHttp.open(_method, _url, true);
xmlHttp.send(_sendItem);
} //Set a function for AJAX Request
//Actual performance
window.addEventListener('load', function(){
var _sort = document.getElementById('sort'), _filter = document.getElementById('filter'); //Get the elements
_sort.addEventListener('change', function(){ //If the value of the field changes
var _frmData = new FormData(); //Create a new FormData object
_frmData.append('sort', _sort.value); //Append the value to this object
ajaxFormValidate('GET', location.href, function(response){
//Perform the redirection here (without reloading the page)
}, function(response){
alert("Request cannot be sent!");
}, _frmData);
}, false);
});
Recently, I don't have any ideas for this. Any help is appreciated. Thanks
This is a good way of using GET in pure Javascript:
var ajax = new XMLHttpRequest();
ajax.open("GET", "example.com/products.php?option=YOUR OPTION VALUE GOES HERE", true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
console.log(data);
}
}
And this is the jQuery way (my preferred method):
var myOption = $('.your-elenet-calss-name').val();
var myurl = "http://example.com/products.php";
var dataString="&option="+myOption+"&check=";
$.ajax({
type: "GET",
url: myurl,
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function(){//Do some stuff here. Example: you can show a preloader///},
success: function(data){
if(data =='success'){
alert('done deal...');
}
}
});

Why wikipedia ajax call is not working

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);
}
});

the opposite function for the done function in ajax/jQuery

I want to send a form via Ajax, with jQuery.
On submitting the form, a loading image will be shown on the data transferring.
In pure JS I used this code :
var myForm = document.getElementById('myForm');
var xhr = new XMLHttpRequest();
myForm.addEventListener('submit', function(e){
var formData = new FormData(myForm);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200) {
loading.style = "visibility:hidden;";
alert('Authentification réussi.\n' + xhr.responseText );
}else{
loading.style = "visibility:visible;";
}
};
xhr.open("GET", "authentification.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(formData);
e.preventDefault();
}, false);
And this is what I tried using jQuery :
var jqxhr = $.ajax({
type : $('#myForm').attr('method'),
url : $('#myForm').attr('action'),
data : $('#myForm').serialize(),
dataType : 'html'
});
$(function(){
$('#myForm').submit(function(event){
jqxhr.done(function(data){
$('#loading').hide();
alert(data);
});
//Here the other method
});
event.preventDefault();
});
The problem is I don't know what it the function that will be executed on sending data, in pure JS I just used the else statement for : xhr.readyState == 4 && xhr.status == 200.
So, what is the function which is responsible for that ?
Edit :
The solution was to use the attribute beforeSend as the following :
jqxhr = $.ajax({
type : $(this).attr('method'),
url : $(this).attr('action'),
data : $(this).serialize(),
dataType : 'html',
beforeSend : function(){
$('#loading').show();
},
complete : function(){
$('#loading').hide();
}
})
You need to sent the ajax request within the submit handler... when you say $.ajax(..) the ajax request is sent and the since you have placed the code in global context this refers to the window object.
var jqxhr;
$(function () {
$('#myForm').submit(function (event) {
jqxhr = $.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'html'
}).done(function (data) {
$('#loading').hide();
alert(data);
}).always(function () {
jqxhr = undefined;
});
//Here the other method
});
event.preventDefault();
});
It might work. You can use beforeSend to show your loading image and hide it on done.

Categories

Resources