How to send a string to php with POST [duplicate] - javascript

This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 8 years ago.
I'm sending a string via xmlhttp in javascript using the following code:
function SendPHP(str, callback) {
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) {
callback(xmlhttp.responseText); //invoke the callback
}
}
xmlhttp.open("GET", "testpost.php?q=" + encodeURIComponent(str), true);
xmlhttp.send();
}
and some test php:
$q = $_GET['q'];
echo $q;
That worked fine until I started sending a larger string in which case I get the "HTTP/1.1 414 Request-URI Too Long" error.
After a bit of research I found out I need to use "POST" instead. So I changed it to:
xmlhttp.open("POST", "sendmail.php?q=" + str, true);
And:
$q = $_POST['q'];
echo $q;
But this does not echo anything when using POST. How can I fix it so it works like when I was using GET but so it can handle a large string of data?
edit I'm now trying it with:
function testNewPHP(str){
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}

You should not provide your href with URL parameters, instead of this you should send() them. For addition, you should always encode your parameters with encodeURIComponent() (At least when your request is using the Content-type "application/x-www-form-urlencoded").
your javascript function :
function testNewPHP(){
var str = "This is test";
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}

javascript :
function testNewPHP(){
var str = "This is test";
xmlhttp = new XMLHttpRequest();
str = "q=" + encodeURIComponent(str);
alert (str);
xmlhttp.open("POST","testpost.php", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert (xmlhttp.responseText);
}
}
};
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(str);
}
testpost.php in your home directory :
<?php
var_dump($_POST);
OUTPUT :
array(1) {
["q"]=>
string(12) "This is test"
}

Related

How can I send more than one variable to a php file using ajax and a get request?

I am trying to send an I.D. value and a name value to a php file using ajax. I can send just the I.D. variable just fine but when I try to add the name variable, the function stops working. How can I send both?
This works:
function click() {
var name = clickedelement.getElementsByTagName('input')[0].value;
var id = clickedelement.getElementsByTagName('input')[1].value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("popupBox").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "friends2.php?id="+id, true);
xmlhttp.send();
};
But when I try to add the name variable, it dosnt work.
function click() {
var name = clickedelement.getElementsByTagName('input')[0].value;
var id = clickedelement.getElementsByTagName('input')[1].value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("popupBox").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "friends2.php?id="+id"&name="+name, true);
xmlhttp.send();
};
change to "friends2.php?id="+id+"&name="+name you just have a missing +
"friends2.php?id="+id+"&name="
// missing plus sign here ^

Javascript does not return servlet response

I have wriiten welcome screen which basically use below javascript to call creditCheck servlet. Within servlet, there is method which will check the username and password. Servlet returns value properly. alert is not getting generated after servlet excutation within javascript.
however if execute simple servlet ( not doing anything, just printing variables), it will generate alert.
below is my javascript within JSp file:
############################################
<script type="text/javascript">
function getXmlHttpRequestObject(){
var xmlHttp = false;
if (window.XMLHttpRequest){
return new XMLHttpRequest(); //To support the browsers IE7+, Firefox, Chrome, Opera, Safari
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP"); // For the browsers IE6, IE5
}
else {
alert("Error due to old verion of browser upgrade your browser");
}
}
var xmlhttp = new getXmlHttpRequestObject(); //xmlhttp holds the ajax object
function servletPost() {
if(xmlhttp) {
var username = document.getElementById("uname");
var password = document.getElementById("pass");
xmlhttp.open("POST","CredCheck",true);
xmlhttp.onreadystatechange = handleServletPost;
req.onreadystatechange = callback;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("uname=" + username.value + "&pass=" + password.value );
}
}
function handleServletPost() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Ajax calling error");
}
}
}
</script>
#
I have changed xmlhttp.open("POST","CredCheck",true); to
xmlhttp.open("POST","CredCheck",false);
xmlhttp.onreadystatechange = handleServletPost;

Preload image doesn't always appear

I have created a simple ajax request:
var params = "postdata=" + mydata;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("data").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "data.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
And this is the HTML code:
<div id="data">
<img src="/images/preload.gif" />
<b style="color:#9ca6dc;font-size:12px;">Wait</b>
</div>
The problem is that the preload.gif and "Wait" text appears only sometimes and not always.
Why ? How can I resolve that ?
The only explanation is that AJAX request works too quickly to see the content (as Alessandro Pezzato said). If you don't see it the readyState of XMLHTTP request had to change.
Or you have some other Javascript which runs asynchronously and does changes on the same content.

Simple XMLHttpRequest (Google Weather)

Hello I want to get xml from Google Weather
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.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.send(null);
xmlDoc=xmlhttp.responseXML;
It`s not working . Thanks
XMLHttpRequest is asynchronous. You need to use a callback. If you don't want to use a full-fledged library, I recommend using Quirksmode's XHR wrapper:
function callback(xhr)
{
xmlDoc = xhr.responseXML;
// further XML processing here
}
sendRequest('http://www.google.com/ig/api?weather=london&hl=en', callback);
If you absolutely insist on implementing this yourself:
// callback is the same as above
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState != 4) return;
if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
callback(xmlhttp);
};
xmlhttp.send(null);
Edit
As #remi commented:
I think you'll get a cross domain access exception : you can't make an ajax request to an other domain than your page's. no ?
Which is (for the most part) correct. You'll need to use a server-side proxy, or whatever API that Google provides, instead of a regular XHR.
You can't do this via javascript to to it being a cross-domain request. You'd have to do this server-side.
In PHP you'd use CURL.
What you are trying to do can't be done with Javascript.
Ok here is the code :
<html>
<body>
<script type="text/javascript">
var xmlhttp;
var xmlDoc;
function callback(xhr)
{
xmlDoc = xhr.responseXML;
// further XML processing here
}
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState != 4) return;
if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
callback(xmlhttp);
};
xmlhttp.send(null);
alert(xmlDoc);
</script>
</body>
</html>
It doesn`t returns any errors but alert returns undefined.

How can I re-write this code without jQuery?

How can I rewrite this code without using jQuery? I need to do it in a mobile app where I can't use jQuery.
$.ajax({
type: "POST",
url:"../REST/session.aspx?_method=put",
data: JSON.stringify(dataObject, null,4),
cache: false,
dataType: "json",
success: onSuccessLogin,
error: function (xhr, ajaxOptions){
alert(xhr.status + " : " + xhr.statusText);
}
});
You can try this:
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) {
// What you want to do on failure
alert(xmlhttp.status + " : " + xmlhttp.responseText);
 }
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// What you want to do on success
onSuccessLogin();
}
}
xmlhttp.open("POST", "../REST/session.aspx?_method=put", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Cache-Control", "no-cache"); // For no cache
xmlhttp.send("data=" + JSON.stringify(dataObject, null,4));
As for how to do more stuff with only javascript without jQuery library take a look at W3Schools AJAX Tutorial or Mozilla - Using XMLHttpRequest
And as duri said, you will have to find a way to convert dataObject to string, as not all browsers support JSON object.
try this
var xmlHttp = createXmlHttpRequestObject();
//retrieves the xmlHttpRequest Object
function createXmlHttpRequestObject()
{
//will store the refrence to the xmlHttpRequest Object
var xmlHttp;
//if running in internet explorer version below 7
if(window.ActiveXObject)
{
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
xmlHttp = false;
}
}
else
{
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Error Creating the xmlHttpObject");
else
return xmlHttp;
}
function callThisFunction()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
var queryString = JSON.stringify(dataObject, null,4);
var url = "../REST/session.aspx?_method=put";
xmlHttp.open("POST", url, true);
//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", queryString.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = checkHandleServerResponse;
xmlHttp.send(queryString);
}
}
function checkHandleServerResponse()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var JSONFile = 'jsonFormatData = '+xmlHttp.responseText;
eval(JSONFile);
if(jsonFormatData.description == 'Success')
{
//showDialog('Success','Login Successful','success',3);
location.href='default.aspx';
//setTimeout(function(){location.href='myGrupio.php';},3000);
}
else
showDialog('Error','You Need a Valid Login.','error',3);
}
else if(xmlHttp.status == 400)
{
setTimeout( function()
{
alert('you have error');
},3000);
}
else
alert("Error Code is "+xmlHttp.status)
}
}
For the Ajax request itself, have a look at the XMLHttpRequest object (special treatment for IE).
To parse the JSON response (dataType: 'json'), use JSON.parse (you might need the json2.js library).
jquery is already javascript. It's a library, entirely written in javascript. So you can use it within every javascript project. If you want to write a rest client yourself, you might look at this article
You may also consider using jQuery Mobile edition - very light - 17KB minified. 1.0 is alpha now, but I think it will be more stable and portable than self-baked code.

Categories

Resources