why fail to request url in ajax when - javascript

this is my ajax code
function buatajax(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function checkout() {
var url = "index3.php";
url = url+"&sid="+Math.random();
ajaxku = buatajax();
ajaxku.onreadystatechange=checkoutisi;
ajaxku.open("GET",url,true);
ajaxku.send(null);
}
function checkoutisi() {
if(ajaxku.readyState == 4){
data = ajaxku.responseText;
document.getElementById('isiecon').innerHTML = data;
alert(data);
}
}
when i alert data as it's shown, it said that the requested url not found.
I'm using localhost server for now, instead of using jquery ajax, how to use ajax in my way? because i dont really understand the jquery ajax way.

Related

Handling POST Request

I'm creating a asynchronous upload element with the javascript code bellow:
$("#file-input").change(function(){
uploadImage(this.files[0]);
});
function uploadImage(imageFileHTMLInput) {
var xml = new XMLHttpRequest();
var data = new FormData();
data.append('file', cover);
xml.open('POST', url);
xml.send(data);
xml.onreadystatechange = function() {
if(xml.readyState === 4) {
if(xml.status === 200) {
var response = JSON.parse(xml.responseText);
// handle response
} else {
var error = JSON.parse(xml.responseText);
// handle error
}
}
};
}
How can I handle this post in a Symfony2 server? I need to save this file in the server and return the image url.
UPDATED:
I made some changes on my code to works fine. I have change all way to do the upload.
You will get the data from your POST request in the controller via
$request->files->get('your_file_identifier_name');
Server side, you'll get an instance of File

Ajax - Function to check if Url exists

I'm building a building a website using the Reddit API to display images from Reddit.
I'm getting the data via JSON then use it to build the page, using URLs provided as sources for the images.
Some of the URLs that I get don't go to images directly, but instead to image hosting sites (like imgur.com). Usually, adding '.jpg' at the end of the URL takes me to the right image.
So, doing that, I would like to check if the URL + '.jpg' exists before using it.
I tried to build a function to check the url.
function checkUrl(url){
var request = new XMLHttpRequest;
request.open('GET', url, true);
request.send();
request.onreadystatechange = function(){
if(request.readyState==4){
console.log(request.readyState);
return true;
}else{
return false;
}
}
};
//Then I use the function to check and append the data to the page
var url = url+'.jpg';
if(checkUrl(url)){
//work with the data
}else{
//do nothing
}
Nothing happens to the page, still I get the readyState logged into the console, so the checkUrl() function seems to be returning true.
What I am doing wrong ? I am pretty new to the whole Ajax thing, so some help would very appreciated.
Thank you
Your problem is that when request.readyState == 4 this means the request has completed, regardless of what the result of that request was. So even if the URL you request returns a "404 not found", you'll still see the XHR resolving itself to readyState 4.
To address what you're trying to do, I'd recommend checking the status code of the response. For example, using your code:
if(request.status==200){
return true;
}
Why your code won't work:
Your AJAX request is asynchronous, and if(checkUrl(url)){ will return null (false) as the function checkUrl() sends the AJAX request and immediately returns, before the AJAX call has completed.
Change
request.open('GET', url, true);
to
request.open('GET', url, false);
Also, move your request.send() to after the request.onreadystatechange() as now it is a non-async request.
request.onreadystatechange = function(){
if(request.readyState==4){
console.log(request.readyState);
return true;
}else{
return false;
}
}
request.send();
Or, you could simply place your check logic into the onreadystatechange function:
request.onreadystatechange = function(){
var url = url+'.jpg';
if(request.readyState==4){
//work with the data
}else{
//do nothing
}
}
I believe your problem is misunderstanding of AJAX; AJAX is basically asynchronous, and that's why the behavior you are describing.
I've used the following to get a simple true/false indication whether a URL is valid, in a synchronous manner:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
The usage is then trivial:
var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Hope this helps
The return value of request.reonreadystatechange is not the return value of checkUrl. Try this:
function checkUrl(url){
var request = new XMLHttpRequest;
request.open('GET', url, true);
request.send();
request.onreadystatechange = function(){
if(request.readyState==4){
console.log(request.readyState);
// perform your data manipulation here
// don't separate it with the request
}
}
};
On Safari, ActiveXObject will work fine, compared to XMLHttpRequest:
function isThere(url)
{
var req= new AJ(); // XMLHttpRequest object
try {
req.open("HEAD", url, false);
req.send(null);
//alert(req.status); //un-comment if need alert for status code
return req.status== 200 ? true : false;
}
catch (er) {
//alert ('ERROR:'); // un-comment if need alert for error
return false;
}
}
function AJAX()
{
var obj;
if (window.XMLHttpRequest) obj= new XMLHttpRequest();
else if (window.ActiveXObject)
{
try
{
obj= new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
catch(er)
{
try
{
obj= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(er)
{
obj= false;
}
}
}
return obj;
}

There is a delay before html textbox value gets updated after ajax function execution

I am using jcaptcha for image verification in my form. Before the form is submitted I make an ajax call using javascript to validate the text entered by the user corresponding to the image displayed. I get the result and update the value of a textbox(imageVerification). After the function that makes this ajax call is executed I pick up the value from this just updated textbox(imageVerification) for the result.
Here is the problem: I am not able to pick up the value from this textbox(imageVerification).
it always shows up as blank.
Catch: if I use an alert() before picking up the value, I am able to pick up the value correctly. I ran this in firebug debug mode and found out that it works in debug mode even without using the alert.
It seemed there is a delay before which the value in the textbox(imageVerification) gets updated. So i introduced a setTimeout() method and was able to pick up the value.
But I dont feel this is the right solution. I am assuming javascript executes sequentially. So why is my statement which is picking up the value after it has been updated by a method not able to get it immediately. Result is even though the image verification is successfull, my check fails since it is not able to pick up the result value from the textbox.
Also, if I use a simple function to update the textbox(imageVerification) instead of a ajax call, I dont face this problem.
Here is the code I am using for the ajax call.
function fetchContainerContent(url, containerid) {
var imageValue = document.forms['ratingForm'].elements['jcaptcha'].value;
var req = false;
var parameterString;
if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
return false;
}
req.onreadystatechange = function() {
requestContainerContent(req, containerid);
}
parameterString = "jcaptcha="+imageValue;
req.open('POST', url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(parameterString);
}
function requestContainerContent(req, containerid) {
if (req.readyState == 4 && (req.status==200 || window.location.href.indexOf("http")==-1)){
//document.getElementById(containerid).innerHTML = req.responseText
//document.getElementById(containerid).value=req.responseText;
document.forms['ratingForm'].elements[containerid].value = req.responseText;
}
}
This is the function for image verification:
function validateImage(){
if(isBlank(document.forms['ratingForm'].elements['jcaptcha'].value)){
showError('',"Please enter the text seen in the image above",'jcaptchaError');
return false;
}
fetchContainerContent('captchaController','imageVerification');
var obj = document.forms['ratingForm'].elements['imageVerification'];
//alert('val '+obj.value);
var vall = obj.value;
if(vall=='PASS'){
return true;
}
else{
showError('',"Image verification failed. Please refresh image and try again","jcaptchaError");
return false;
}
}
post my call to fetchContainerContent('captchaController','imageVerification'), the value for imageVerification textbox should be set. If I use the alert box which is commented after the fetchContainerContent('captchaController','imageVerification') call it works fine.
Please help me out. Thanks alot
UPDATED ANSWER: Misread program flow on first pass.
The basic problem is you're trying to get an immediate response from the validateImage() function (return true or false) when the XMLHttpRequest needs time to complete.
Move the actions taken based on the return to their own functions (validFunction, invalidFunction) and try this:
function validateImage() {}
if(isBlank(document.forms['ratingForm'].elements['jcaptcha'].value)){
showError('',"Please enter the text seen in the image above",'jcaptchaError');
return false;
}
var obj = document.forms['ratingForm'].elements['imageVerification'];
validReq = fetchContainerContent('captchaController','imageVerification');
validReq.onload = function () {
var validResp = this.reponseText;
if(validResp=='PASS'){
validFunction();
}
else{
showError('',"Image verification failed. Please refresh image and try again","jcaptchaError");
invalidFunction();
}
}
validReq.send(parameterString);
}
function fetchContainerContent(url, containerid) {
var imageValue = document.forms['ratingForm'].elements['jcaptcha'].value;
var req = false;
var parameterString;
if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
return false;
}
parameterString = "jcaptcha="+imageValue;
req.open('POST', url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return req;
}

How to send data from outside site to my server via AJAX?

I am written the bookmarklet, which takes pictures and videos from a site and must send it to my server via AJAX. The problem is in crossdomain AJAX request - I have got an error:
XMLHttpRequest cannot load http://mysite.com/community/bookmarklet/. Origin http://www.some-nice-site.com is not allowed by Access-Control-Allow-Origin.
How to solve data sending to my server from third-part sites?
Note: I use only plane javascript, this is the stipulation of development.
my code:
function getXmlHttp(){
var xmlhttp;
if (typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
} else {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
};
return xmlhttp;
};
function vote(data) {
var req = getXmlHttp();
req.onready = function() {
if (req.readyState == 4 & req.status == 200) {
alert('OK');
}
}
req.open('GET', 'http://mydomain.com/community/bookmarklet/');
req.send(JSON.stringify(data()));
};
function dataProcessing(){
//some processing
return data;
};
// I tried it, but not deeply understand.
function JSONPresponse(){
document.getElementById('popup_body').innerHTML = 'done!';
};
(function(){
function pasteIt(){
// this function is builds the form, which get data for dispatch to my server.
};
pasteIt();
document.getElementById('my_button').addEventListener('click', function() {vote(dataProcessing)}, false);
}());
It is quite clear... the site you are attempting is prohibiting connection from outside world. You can try by modifying your http headers in request. See:
Access-Control-Allow-Origin Multiple Origin Domains?
Cannot properly set the Accept HTTP header with jQuery
As #jakeclarkson told - JSON-P is the solution, not the only, but useful for me.
XMLHttpRequest is not needed anymore. Instead it vote(data) function creates the script to build URL with params:
function vote(data) {
var script = document.createElement('script'),
data = JSON.stringify(data());
script.type = 'text/javascript';
script.src = 'http://mysite.com/api/bookmarklet/?vids='+encodeURIComponent(data);
document.getElementsByTagName('head')[0].appendChild(script);
};
The script is fulfilled, so URL is called and params already in the server.

No response when using AJAX and JSON

function getIDs() {
alert("1");
var title = document.getElementById('title').value;
alert(title);
title = "http://www.imdbapi.com/?i=&t=" + title;
alert(title);
xmlhttp=new XMLHttpRequest();
alert("2");
xmlhttp.open("GET",title,true);
alert("3");
xmlhttp.send();
alert("4");
var imdbData = xmlhttp.responseText;
alert(imdbData);
var imdbJSON = JSON.parse(imdbData);
//document.getElementById('title').value = imdbJSON.Title;
alert(imdbJSON.Title);
document.getElementById('imdbid').value = imdbJSON.ID;
return true;
}
I'm trying to fetch the ID of a film based upon it's title, the function gets called successfully and the alerts are correct until the alert which returns "imdbData", which returns a blank alert, then no more alerts occur, I'm unsure where I'm going wrong here. Any assistance would be appreciated.
You're opening it asynchronously. To make it synchronous, change this:
xmlhttp.open("GET",title,true);
To this:
xmlhttp.open("GET",title,false);
A usually-considered-better way would be to make it work with asynchronicity:
function getIDs() {
alert("1");
var title = document.getElementById('title').value;
title = "http://www.imdbapi.com/?i=&t=" + title;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
var imdbData = xmlhttp.responseText;
var imdbJSON = JSON.parse(imdbData);
document.getElementById('title').value = imdbJSON.Title;
document.getElementById('imdbid').value = imdbJSON.ID;
}
};
xmlhttp.open("GET",title,true);
xmlhttp.send();
return true;
}
Additionally, you cannot request pages from other domains. You may need to switch to JSONP if the API you're using supports it, or use your web server as a proxy.
You are not allowed to do cross site scripting with JavaScript which is why you get nothing in return.
You need to be on the same domain as you post your AJAX call to.
Use a serverside script to parse the URL for you instead.

Categories