How to pass AJAX variables to PHP - javascript

I understand I can't pass AJAX Vars directly to PHP, being a client versus server side script. But that being said, here's my code:
setInterval(function()
{
//do something after you receive the result
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("message_area").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","messages.txt",true);
xmlhttp.send();
}
I know I can indirectly process AJAX variables by POSTing them to a PHP page using AJAX, like so:
$.ajax (
{
type: "POST",
url: "decode.php",
});
I just need to know how to pass the contents of the "messages.txt" file used in the xmthttp.open call to a PHP file for further processing.
How can I do this?

If you are using pure javascript:
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
or if you're using jquery, simply:
$.ajax (
{
type: "POST",
url: "decode.php",
params: {param1: "val1", param2: "val2"}
});

Hope this helps :
$.get( "messages.txt", function( data ) { //Fetching contents of messages.txt file.
$.ajax ({
type: "POST",
url: "decode.php",
data: data, //passing contents of messages.txt file to decode.php
success: function(result){
alert(result);//Getting result from decode.php
}
});
});
cheers

Are you using jquery? You first code block is regular js, the second is jQuery's ajax short hand.
That said, if you want to POST data with ajax using jQuery, you would do something like the following.
var PostData = "something";
$.ajax({
type: "POST",
url: "someurl",
data: PostData
}).done(function(returnData) {
//process data returned from server, if there is any
});

Related

Converting native JS Ajax snippet to JQuery alternative?

I am updating historic JS code from another author but having problems converting the below to the JQuery alternative:
var xhr = new XMLHttpRequest();
xhr.open('GET', songurl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
document.getElementById('songdiv').innerHTML = '';
song.src = (window.webkitURL ? webkitURL : URL).createObjectURL(this.response);
}
}
xhr.send();
This is more so to aide consistency, Chrome - developer tools is also suggesting the code to be re-factored.
Here is what I have started with (appreciate it's not much!), the issue I'm having is checking the status code and returning the response if the status code is 200.
$.ajax({
url: songurl,
method: 'GET'
);
You want to attach a function for success.
$.ajax({
url: songurl,
method: 'GET',
success: function(response){
//do stuff with response
}
})
ajax(), or the shorthand get(), will do all that for you. There's a success() function that's only called on a successfull, 200-status request:
$.get( songurl,
function(data) {
document.getElementById('songdiv').innerHTML = '';
song.src = (window.webkitURL ? webkitURL : URL).createObjectURL(data);
},
'blob'
);

Different behavior for empty XML response between IE and Firefox

I'm using jQuery to read an XML file. Sometimes the XML is empty, and I expect the error function (no_info) is executed because the file is not formatted according to the dataType.
In IE 10 the Error function is executed. But in Firefox (40.0.2) the success function (parse) is executed. Why both browsers behave differently and which one is correct?
$.ajax({
url: '/~play/shout.xml',
dataType: "xml",
success: parse,
error: no_info
});
Looks like there's a bug in IE
how about you handle it yourself?
function parseXml(xml) {
if ($.browser.msie) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "XML_file.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
xml = xmlDoc;
}
return xml;
}
previous answer
which JQuery version do you use? I use the most actual and with my ajax function I couldn't encounter any issues. That's my code
function sync(arg, callback){ //ajax result
$('.loader').show();
$.ajax({
method: 'GET',
url: 'liveSearch.php',
data: arg, // send argument and update
success: function(data, status, xhr){
$('.loader').hide();
callback(data);
},
error: function(xhr, ajaxOptions, thrownError){
console.log(thrownError);
}
});
}
function onCallback(data) {
result = data;
}
dataType parameter merely indicates what "Content-Type" header you are expecting.
As long as the file exists and served with a valid Content-Type Success function should be triggered.
instead of just /~ try passing the whole URL from which you want to retrieve the XML file.

Jquery Ajax function is not working while calling the Servlet

I am facing some problem while calling ajax. Can anyone look at my code and suggest something to solve my problem
function search(file,input){
$.ajax({url:'/Searchandhighlight?name='+input+'&file='+file,type:"post",
success:function(){
$("#bodyy").html();
}
});
}
I am using ajax to call the servlet and servlet changes some contents of database and after success I am trying to refresh my "#bodyy" div.
Thanks in advance
Firstly let us know what file variable holds.
Normally Ajax call with parameters goes like this. dataType depends on what kind of response you are expecting.
$.ajax({
type: "POST",
url: "/Searchandhighlight",
dataType: "json",
data: {"name" : input, "file" : file},
success:function(data){
if(data){
alert("success");
}
},
error:function(){
alert('failed');
}
})
I finally solved my issue by following code
function search(file,input){
if(input != "") {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Searchandhighlight?name=" + input + "&file=" + file, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location.reload();
}
}
xmlhttp.send(null);
}
}

Javascript AJAX call to Jquery Call

In order to have my code written almost fully written in Jquery, I want to rewrite an AJAX call in Jquery.
It's a call from a webpage to a Tomcat servlet.
Similar code of my present situation:
var http = new XMLhttpRequest();
var url = "http://example.com/MessageController?action=send";
http.onreadystatechange = function ()
if (http.readyState == 4)
{
if (http.status == 200){ var response = http.responseText;}
else {/*code2*/}
};
http.async = false;
http.open("POST", url, true);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(string);
Which would be the best way to do this? .ajax or .post? Could you help me with some pseudo code to start this?
Use .ajax or (as you are using POST) .post:
$.ajax({
url: "http://example.com/MessageController",
type: "POST",
data: { action: "send", yourStringName: "something" },
async: false, // make sure you really need it
contentType:'application/x-www-form-urlencoded'
}).done(function(response) {
console.log(response);
});
It doesn't matter which one you use, because .post is shorthand for .ajax.
You can use jQuery post.
var url="MessageController"
$.post(url, { action : "send"} ,function(data){
//response from MessageController is in data variable
//code 1
alert(data)
}).error(function(){
alert("error"); //code 2
})
Assuming MessageController is some url in your domain and you are aware of the same origin policy

How do I know when an ajax request is completed

How to know when all ajax calls are complete?,now I just use a delay timeout to wait the request complete,these is a better way?i want make sure ajax requests are completed...
The XMLHttpRequest object has readyState property and onreadystatechange that you can manipulate like that:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) { // xmlhttp.status==200 == successful request
// What you want here
}
}
xmlhttp.open("GET", "foo_url.php", true);
xmlhttp.send();
}​
You can do it simpler with jQuery, if you're using that library:
$.ajax({
url: 'foo_url.php',
complete: function() {
// What you want here
}
});
If you're using jQuery's AJAX, it has a complete option, see docs
$.ajax({
url: 'foo.php',
complete: function(jqXHR, textStatus) {
alert('AJAX call complete');
}
});
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// This is when your Ajax request is complete
}
}
that is depend on your library; ex, if you are using jquery then you can use success: parameter and if javascript then you can use if (xmlhttp.readyState==4 && xmlhttp.status==200) statement.
If you are using xmlhttp object for ajax call then when xmlhttp.readyState==4 then it is consider as ajax request is completed.
$.ajax({
url: 'abc.php',
data: "&id=" + id ;
complete: function(data) {
alert(data.responseText);
}
});

Categories

Resources