Javascript AJAX POST Method not posting values to the submitted page - javascript

I am using Javascript AJAX to send request a php page and receiving the output from php page. When I use GET method in AJAX, its working. but the same is not working when i use POST method.
here is my code:
<script>
function verifyMobile(mobileNo,code,emailKey)
{
alert(mobileNo+'-'+code+'-'+emailKey); //alerts proper value here...
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)
{
alert(xmlhttp.responseText); //alerts empty value here...
}
xmlhttp.open("POST","verification.php",true);
xmlhttp.send("mobileNo="+mobileNo+"&code="+code+"&emailKey="+emailKey);
}
</script>
verification.php
<?php
$mobile_number=trim($_POST['mobileNo']);
$sms_code=trim($_POST['code']);
$email_key=trim($_POST['emailKey']);
echo $mobile_number." - ".$sms_code." - ".$email_key;
?>

Try setting the headers and see if it helps.
var params = "mobileNo="+encodeURIComponent(mobileNo)+"&code="+encodeURIComponent(code)+"&emailKey="+encodeURIComponent(emailKey);
xmlhttp.open("POST","verification.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);

Related

HTTPRequest ajax error with slesh in end of Uri in codeigniter

Help guest...
i make web using framework Codeigniter and also using ajax XMLHttp Request to load some data from DB.
if i open the link Like this
localhost/web/topsales
every things is OK like this. Images
but if i add slash in end of url
localhost/web/topsales/
the result is error. Ajax load and duplicate the pages view like this image
i use AJAX XMLHttp Request for load the data:
function showdata()
{
var idunit = document.getElementById('idunit').value;
var month = document.getElementById('month').value;
var year = document.getElementById('year').value;
var xmlhttp;
document.getElementById("result").innerHTML = "<div class='text-center'>Loading...</div>"; //xmlhttp.responseText
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("result").innerHTML = xmlhttp.responseText; //xmlhttp.responseText
}
}
xmlhttp.open("POST","showresult",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("idunit="+idunit+"&month="+month+"&year="+year);
}
please i need help, thanks so much for some advice.

save url responce into variable with javascript / html

in a webpage i would like to collect a response from another web server at a given URL address.
let's say someone else has a server at http://mysite/123 that responds with a simple string. (without headers and stuff).
what is the most SIMPLE way to get javascript on my webpage to collect a url's raw response in preferably a byte array variable? though i would except an answer that saves in string to get me going. this is an exact copy paste from my html document and its not working for me.
thanks!
<script>
var txt = "";
txt=httpGet("https://www.google.com");
alert(txt.length.toString());
function httpGet(theUrl) {
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) {
return xmlhttp.responseText;
}
}
xmlhttp.open("GET", theUrl, false);
xmlhttp.send();
}
</script>
So I'd have to say your best bet would be to look into making an HTTP (or XHR) request from javascript.
check: Return HTML content as a string, given URL. Javascript Function
function httpGet(theUrl)
{
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)
{
return xmlhttp.responseText;
}
}
xmlhttp.open("GET", theUrl, false );
xmlhttp.send();
}

Ajax returning blank response

I'm working on a simple script where I just want to see request and response that is sent to server and then recieved at client via Ajax. The server is always returning Status 500. What am I doing wrong?
Below is my script.
Javascript:
<script>
function loginJs()
{
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://my-website.com/ajax_exp.php",true);
xmlhttp.onreadystatechange=function()
{
alert("State "+xmlhttp.readyState+" Status "+xmlhttp.status);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
}
</script>
ajax_exp.php
<?php
header('Access-Control-Allow-Origin: http://my-website.com/ajax_exp.php');
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action()
{
$username = 'username';
$password = 'password';
echo $username;
die();
}
?>
1) try removing
header('Access-Control-Allow-Origin: http://my-website.com/ajax_exp.php');
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
replacing with
my_action();
You can easily trace the error;
2) Check console log for any javascript errors.
Path is the problem provide your server path ajax/ajax_exp.php
<script>
function loginJs()
{
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","ajax/ajax_exp.php",true);
xmlhttp.onreadystatechange=function()
{
alert("State "+xmlhttp.readyState+" Status "+xmlhttp.status);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
}
</script>
If anyone else is having the same issue, this is what I did and now it works!
Javascript
Replaced xmlhttp.send(); with xmlhttp.send(null);
PHP
<?php
$username = "user";
$password = "password";
print $username;
?>

ajax php call not returning anything

I want php to return a value to ajax. I'm following W3 schools example but no joy.
Here is the javascript/ajax code:
function createReport() {
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("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
I have the following call inside an event handler that I know is triggering (other stuff it does is working fine)
createReport();
and later in the body section of the html I have:
<div id="report">Report will be placed here...</div>
If I run test.php by itself, it correctly shows "return this to ajax" so I know that's working. Here is the php code:
<?php
echo 'return this to ajax';
?>
My understanding is that "Report will be placed here..." will be replaced with "return this to ajax". But nothing happens. I don't see any errors listed in the firefox or IE consoles either. Any ideas?
I personally do not think the w3cschools a good place to learn ( see http://www.w3fools.com/ ).
It may be that the problem occurs because of the order that you set the ajax, you did:
XMLHttpRequest/onreadystatechange/open/send
is preferable (if you do not follow this order may occur several flaws in older browsers):
XMLHttpRequest/open/onreadystatechange/send
Note: do not worry, the "open(...)" does not start listeners.
Listeners only work after the "send(...)"
Another reason may be that you did not create "error handling" of XMLHttpRequest.status, it serves to verify faults in the server response.
Try this:
<script>
function XHR(){
if(window.XMLHttpRequest){//outers browsers
return new XMLHttpRequest();
} else if(window.ActiveXObject){//IE
try{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch(ee) {//IE
try{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(ee) {}
}
}
return false;
}
function createReport(){
var xhr = XHR();// call ajax object
if(xhr){
xhr.open("GET", "test.php", true);//setting request (should always come first)
xhr.onreadystatechange = function(){//setting callback
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("report").innerHTML=xhr.responseText;
} else {//if the state is different from 200, is why there was a server error (eg. 404)
alert("Server return this error: " + String(xhr.status));
}
}
};
xhr.send(null);//send request, should be the last to be executed.
} else {
alert("Your browser no has support to Ajax");
}
}
</script>
<div id="report">Report will be placed here...</div>
<script>
createReport();//prefer to call the function after its div#report
</script>
To prevent cache, replace:
xhr.open("GET", "test.php", true);
by
xhr.open("GET", "test.php?nocache="+(new Date().getTime()), true);
At first glance I don't see anything wrong on your js code, so I bet it will probably be a problem locating test.php in your folder structure.
With firebug check the call your javascript AJAX it's doing, and check if the file test.php is being correctly assesed.
I did not find anything wrong with W3Schools' Ajax example, after testing the code that follows (which was pulled from their Website).
Possible factors:
Missing <script></script> tags
Make sure you have JS enabled.
Make sure your browser supports it.
You may have forgotten to change the button's call to the proper function.
Working and tested code using FF 26.0 and IE version 7
Pulled from W3 Schools Website (example) and slightly modified to prove this works.
Result when clicking on the Change Content button:
return this to ajax - as per your PHP code.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="report"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
PHP used: (test.php)
<?php
echo 'return this to ajax';
?>
Other possible factors:
If on a local machine, your server doesn't support PHP or is not parsing PHP properly, or is either not installed or configured properly.
If on a hosted service, make sure PHP is available for you to use.
Files are not in the same folder as executed from.
try{
request = new XMLHttpRequest();
}catch(trymicrosoft){
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(othermicrosoft){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request = false;
}
}
}
if(!request)
{
alert("Error initializing XMLHttpRequest!");
}
function Create_Ajax_Query(LinkToFile,Parametrs)
{
window.document.body.style.cursor='progress';
request = new XMLHttpRequest();
var url = LinkToFile;
var params = Parametrs;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = newinfo;
request.send(params);
}
function newinfo()
{
if(request.readyState==4 && request.status == 200){
window.document.body.style.cursor='default';
alert(request.responseText);
}
}
Hope its useful!
The code looks correct. it runs just fine on a local environment.
I would advise to look at the "Network" tab in the developer tools to detect any errors may occurs on the server side. You can also use console.log() to follow the javascript actual flow:
function createReport() {
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() {
console.log(xmlhttp); //to show the entire object after statechage.
console.log(xmlhttp.readyState); //to show specific parameter.
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}

sending image as a parameter in xmlhttprequest Post method failed

I am new to JavaScript. In this first i sent successfully some data as a parameters in xmlhttprequest post method. But after that i am trying to send Image as a parameter but this time the post method fails.Here i am using content-type as a multipart/form-data
I am successfully sent image as a parameter in post method.But this time i used <form> tag.
Please any one tell me about this? why my first procedure fails?
function store(){
var pname=document.getElementById("pname").value;
var price=document.getElementById("price").value;
var discount=document.getElementById("discount").value;
var desc=document.getElementById("desc").value;
var heading=document.getElementById("heading").value;
var image=document.getElementById("image").value;
var params="pname="+pname+"&price="+price+"&discount="+discount+"&desc="+desc+"&heading="+heading+"&image="+image;
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)
{
var txt=xmlhttp.responseText;
var obj = eval ("(" + txt + ")");
if(obj.success)
{
userlogin(obj.username,obj.password);
}
else
document.location.href="Userregistration.jsp";
//document.getElementById("countryname").innerHTML=obj.CurrencyById[0].country;
alert("Registered");
}
}
xmlhttp.open("POST","Newproduct",true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send(params);
}

Categories

Resources