Here is the deal... I need to make an AJAX save script. I have a whole system built on php and every action needs a refresh... I'm trying to minimize the refresh count by using AJAX ... I can't seem to find a way how to send a WYSIWYG editor output without loss to the PHP script...
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
function save(){
xmlhttp.open('POST','action.php',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", document.getElementById('output').value.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(document.getElementById('output').value);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status==200){
$('#ajaxresult').css('opacity', 0.1);
$('#ajaxresult').stopAll().pause(1000).fadeTo(400,1);
$('#ajaxresult').stopAll().pause(3000).fadeTo(400,0, function(){$(this).hide();});
document.getElementById('ajaxresult').innerHTML=xmlhttp.responseText;
}
}
}
While this script works fine I can't seem to find the way what kind of array to give the send option... what is the syntax or is there something I don't know?
BTW I'm a beginner in JS...
I'd look into using jQuery and it's Ajax library:
http://api.jquery.com/jQuery.ajax/
Instead of doing all that you'd simply do:
$.post({url: 'action.php',data: output,success: function() { /* do something here */ }});
create custom parameter in the javascript code like below:
var jspNameParam = "content="+escape(document.getElementById('output').value);
function myFunction() {
if (xmlhttp) {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
/* want to accsess some data written from action.php */
}
};
xmlhttp.open("POST", "action.php", true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send(jspNameParam);
}
}
Now in action.php you will get whole content with the parameter name content.
Related
When a div is clicked on my site, I want the contents of another html file to be added to the existing html. I've tried many methods and cannot find a solution. I don't want to use iframe or object or jquery or php.
function loadhtmlfile(filename, filetype, location){
var fileref=document.createElement('link');
fileref.setAttribute("rel", "html");
fileref.setAttribute("type","text/html");
fileref.setAttribute("href", filename);
document.getElementById("parentDiv").appendChild(fileref);
}
loadhtmlfile("my.html", "html", "parentDiv");
This adds a link for the html file. It doesn't add the actual content of the html file.
Also from what I've read, it sounds like it may be best to do this using a server application. I'm using node.js. If it's best doing this server side, how do I do this using node.js?
Also I will be using websockets so I suspect this will change answers.
You just could use XMLHttpRequest with javascript to load HTML content :
function loadFile(file) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file);
xhr.addEventListener('readystatechange', function() { // load the page asynchronously
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { // if the file is correctly loaded
document.getElementById('yourelement').innerHTML = xhr.responseText;
}
});
xhr.send(null);
}
I'm trying to require a script that is firewalled with a header authentication system and trying to find a way around it.
So far it's pretty evident that you can't add custom headers to the script tag its self but I have seen something about customizing the headers on the page before requesting or on the server side.
Until this point, I can't say I've seen any solid answers.
You can load it via xhr and eval() it in-page. For example with jQuery, you can use:
http://api.jquery.com/jquery.ajax/ - see beforeSend to set headers; use this to retrieve the file content.
Then use https://api.jquery.com/jquery.globaleval/ globalEval() to eval the gotten content in-page.
You could achieve the same with vanilla HttpRequest and eval(), but I was always too lazy to do it that way. Or maybe not... I just found a piece of code in the project I'm working:
var evalScript = function(e) {
var h = evalScript.node,
s = document.createElement("script");
s.type = "text/javascript";
s.text = e;
h.appendChild(s);
h.removeChild(s);
};
evalScript.node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];
// TODO: make async
function loadJs(js) {
var req = new XMLHttpRequest();
req.open("GET", js, false);
req.send(null);
evalScript(req.responseText);
}
Just add the headers to this.
Here's a simple Ajax function you could use to get the contents of the script:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
Since you need to set custom headers, you'd also use the request.setRequestHeader method, like this:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
// BEGIN: CUSTOM HEADERS
request.setRequestHeader("Header-Name", "header/value");
request.setRequestHeader("Other-Header", "other/value");
// END: CUSTOM HEADERS
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
And finally, you'd use the function, like this:
get("url/to/your/script", function(response) {
// perform checks...
window.eval(response);
});
WARNING: be very, VERY careful when using eval, don't ever eval something you don't trust and remember eval can be evil.
I want to wait for the XHR to open after I continue with the program but synchronous XHR is deprecated in chrome api. How can I get around this?
Using a callback to continue execution seems like the best method. Without a clear example of your project here's a generalized option:
function performRequest() {
// ... Some code
var xhr = new XMLHttpRequest();
xhr.open("GET", "/bar/foo.txt", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
useRequest(xhr.responseText);
}
};
}
function useRequest(data) {
// Continue with your application
}
performRequest();
hi frnd form last 2 days i am trying to send JSON data to server but is not working i am posting my js file and check if any error. and i am try to send json data by using xmlHttprequest. and if any other function and any change i have to do then plz tell me. i am developing cordova project in eclipse.and if any other thing and any file also have to change then tell me
this is my js file and on click registration button i am calling this method.
function get() {
alert("function is called");
var name_field_value=document.getElementById("name_field").value;
var email_field_value=document.getElementById("email_field").value;
var password_field_value=document.getElementById("password_field").value;
var phone_field_value=document.getElementById("phone_field").value;
var JSONdata= {
"name": name_field_value,
"mobile_number": phone_field_value,
"email": email_field_value,
"password": password_field_value
}
var request = new XMLHttpRequest();
request.open("POST", "http://www.jiyonatural.com/AccountManagements/insert_new_user", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
alert(request.status);//this alert is working and getting 0 status
if (request.status == 200 || request.status == 0) {
// -> request.responseText <- is a result
/*var tweets = JSON.parse(request.responseText);*/
alert(request.responseText);//this alert is not working//
//if i make other alert then it works
}else{
alert("function is called3");}
}
}
request.send(JSON.stringify(JSONdata));
}
Looks like your question is incomplete.
In my experience the error probably lies in server code friend.
And you should use ajax method in jquery for communication with server.its easier than XMLhttpRequest.
I'm trying to get JSONP working with a server running on an Arduino.
This is my JS code:
window.onload = init;
function init()
{
//alert("Test");
SendRequest();
}
function SendRequest()
{
alert("Sending request");
var url = "http://192.168.1.177";
var request = new XMLHttpRequest();
request.open("GET", url);
request.error = function(e) {
alert("ERROR");
};
request.send(null);
}
function ArduinoJSONP()
{
alert("Callback received!!!");
}
The callback function is never reached.
But if I just direct my browser directly to the Arduino IP I see the following displayed in the browser:
ArduinoJSONP({"data": 12345})
So it seems the server is sending the response with correct JSONP format but somehow the function is not invoked. Is there anything else I need to for JS to call the function? I even tried moving the function to the HTML body but it didn't help either.
Thank you.
You are not handling server response at all. If you doing it without any libraries you need to eval result that was returned by the server.
And actually JSONP implementation is not XHR, you have to inject it as a script tag into html with correct src attribute.
Just use a library that already have all this logic abstracted for you.
Simply inject script tag into HTML tree:
function SendRequest()
{
var element = document.createElement('script');
var s = document.getElementsByTagName('script')[0];
element.type = 'text/javascript';
element.async = true;
element.src = 'http://192.168.1.177';
s.parentNode.insertBefore(element, s);
}
You can mark it with unique id. Hookup to onload event and once executed remove that script.