I have a problem with my http.responseText (is always empty). I post my code:
function bCheckName ()
{
// It checks if the browser can allow a http request
if ( window.XMLHttpRequest )
{
xhttp = new XMLHttpRequest();
}
else
{
// for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// It takes the name from the form
var firstName = document.getElementById("firstName").value;
var datastring = "firstName=" + firstName;
var datastring_escaped = encodeURIComponent ( datastring );
// It opens the request to thye server
xhttp.open ( "POST", "../form/formValidation.php", true );
// It sets the header
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// It sends the data to the server
xhttp.send( datastring_escaped );
// It takes the responde from the server
xhttp.onreadystatechange = function()
{
if ( xhttp.readyState == 4 && xhttp.status == 200 )
{
var string = xhttp.responseText.substr ( 0, 2 );
var response = xhttp.responseText.substr ( 5 );
if ( string == "OK")
{
document.getElementById("nameResponse").innerHTML = '<img src = "../img/pages/contact/true.png" alt = "correct answer" >';
document.getElementById("response").innerHTML = response;
}
else
{
document.getElementById("nameResponse").innerHTML = '<img src = "../img/pages/contact/error.png" alt = "wrong answer">';
document.getElementById("response").innerHTML = response;
}
}
}
return false;}
If I replace "xhttp.send( datastring_escaped );" with "xhttp.send( datastring );", everything will work as expected. How can I fix the problem. I post also the php code:
if ( isset( $_POST['firstName'] ))
{
echo( "OK - ".urldecode ( $_POST['firstName']) );
}
How can I solve the problem?
Thanks in advance!!!
Francesco
encodeURIComponent is only used for a part (component) of the URI.
encodeURIComponent("firstName=foobar")
will give you "firstName%3Dfoobar". There will be no firstName request parameter and you can't read it from $_POST['firstName'].
If you really need to encode it, then only encode the firstName variable:
var datastring_escaped = "firstName=" + encodeURIComponent(firstName);
Related
More explanation here :
Im importing products to my DB, and everytime a product is imported I display the percent calculated earlier:
//Progress bar
set_time_limit(0);
ob_implicit_flush(true);
ob_end_flush();
sleep(1);
$p = ($i/$count_product)*100; //Progress
$response = array( 'success' => true , 'message' => $p . '% ','progress' => $p);
$i++;
echo json_encode($response);
On my local everything is working fine :
Every time php echo json_encode() I get on XHR a new state 3, and display the response.
Code below:
var xhr = new XMLHttpRequest();
xhr.previous_text = '';
$param = 'id='+$(this).find('input').val();
xhr.onerror = function() {console.log(xhr.responseText) };
xhr.onreadystatechange = function() {
//try{
console.log(xhr.readyState);
console.log(xhr);
console.log(new_response);
if (xhr.readyState == 4){
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var result = JSON.parse( new_response );
if (result['message'] == '100' ) {
$('.progress_bar').html('<div><?=$this->translate->_("Imported succefully")?></div>');
$.when($('.full_screen_layer').fadeOut(2000)).done(function() {
location.reload();
});
}else{
$('.progress_bar').html('<div style="color:red">'+result['message']+'</div>');
setTimeout(function(){
$.when($('.full_screen_layer').fadeOut(2000)).done(function() {
location.reload();
});
}, 2000);
// alert('<?=$this->translate->_("Please try again")?>');
}
}
else if (xhr.readyState > 2){
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var result = JSON.parse( new_response );
if (result['success'] && result['end'] == undefined) {
$('.progress_bar').html('<div>'+result['message']+'</div>');
xhr.previous_text = xhr.responseText;
}else{
$('.progress_bar').html('<div style="color:red">'+result['message']+'</div>');
}
}
//}
// catch (e){
// alert("[XHR STATECHANGE] Exception: " + e);
// }
};
xhr.open("POST", action, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send($param);
But I'm trying to understand why it's not working on the server ( XHR state 3 is fired only once, at the end of the request ( so the json is malformed )
Here are the headers:
This just break my mind, if someone have an idea, even a bad one xD
(Btw there is a proxy on the server : VIA:1.1 Alproxy ) it could stop the response untill it end and then send it alltogether ?
I have a problem where the values entered (email and password) into my login form are not being parsed to my server php script.
My ajax request:
function signin(){
var loginEmail = gebi("loginEmail").value;
var loginPass = gebi("loginPass").value;
if(loginEmail == "" || loginPass == ""){
gebi("loginEmail").style.borderColor = "red";
gebi("loginPass").style.borderColor = "red";
} else {
gebi("signinBtn").style.display = "none";
//Declare ajax request variables
hr = new XMLHttpRequest();
url = "main.php";
vars = "email="+loginEmail+"&pass="+loginPass;
//Open the PHP file that is receiving the request
hr.open("POST", url, true);
//Set content type header info for sending url ecncoded variable in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Trim string data before sending it
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
//Access the onreadystatechange event for the XMLHttpRequest
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var responseText = hr.responseText.trim();
if (responseText != "signin_failed") {
console.log(responseText);
} else {
console.log(responseText);
gebi("signinBtn").style.display = "block";
gebi("loginEmail").style.borderColor = "red";
gebi("loginPass").style.borderColor = "red";
}
}
}
//Send the data to the PHP file for processing and wait for responseText
hr.send(vars);
}
}
and when the php script returns a value using this code:
if (isset($_POST["email"])) {
echo 'email = '+$_POST["email"];
}
the return value that is logged to the console is '0' even tho there is data present in the forms fields.
What is going wrong?
The problem is in your PHP script. If you are trying to concatenate string in PHP use dot .. + is used to concatenate string in languages like javascript.
echo 'email = ' . $_POST["email"];
Title is pretty explicit to what I'm trying to do. I want to retreive the variable vavlue in the URL and then send it to add.php.
The reason I don't simply put the PHP code in html is because of a FORM which also send var to add.php
PHP Code :
<?php
$id = $_POST["id"];
?>
Javascript in blabla.html?id=test
<script>
function getResults()
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("here").innerHTML=xmlhttp.responseText;
}
}
var id = getParameterByName("id");
var data = "id="+document.getElementById("id").value;
xmlhttp.open("POST","add.php",true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
}
</script>
<script>
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
var data = "id="+document.getElementById("id").value;
^^^^--string containing the letters 'i' and 'd'
should probably be
var data = "id="+document.getElementById(id).value;
^^-- variable named "id"
try this function
function getParameterByName( name ) {
var parts = window.location.search.substr(1).split("&");
var p_arr = {};
for( var i = 0; i < parts.length; i++ ) {
var temp = parts[i].split("=");
if ( decodeURIComponent( temp[0] ) != "" ) {
p_arr[decodeURIComponent( temp[0] )] = decodeURIComponent( temp[1] );
}
}
return p_arr[name];
}
function getResults() {
var xmlhttp;
if ( typeof XMLHttpRequest !== 'undefined' ) {
xmlhttp = new XMLHttpRequest();
}
else {
var versions = [ "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ];
for( var i = 0, len = versions.length; i < len; i++ ) {
try {
xmlhttp = new ActiveXObject( versions[i] );
break;
}
catch(e) {}
}
}
xmlhttp.onreadystatechange = function() {
if ( this.readyState === 4 && this.status == 200 ) {
document.getElementById( "here" ).innerHTML = xmlhttp.responseText;
}
};
var id = getParameterByName( "id" );
var data = "id="+document.getElementById( id ).value;
xmlhttp.open( "POST", "add.php", true );
xmlhttp.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
xmlhttp.send( data );
}
below is my code for uploading files using XMLHttpRequest send method
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
xhr.onreadystatechange = function()
{
if(xhr.status == 200 && xhr.readyState == 4){
on_upload_complete( filename,id,xhr);
}
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr.open("POST", queryString, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(file);
}
With the above function i wait for on_upload_complete to get called and then pass the second file object and one by one i am uploading. Can someone suggest how can i make it upload simultaneously i tried doing this below as
var xhr = Array();
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
xhr[filename] = new XMLHttpRequest();
xhr[filename].upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
xhr[filename].onreadystatechange = function()
{
if(xhr[filename].status == 200 && xhr[filename].readyState == 4){
on_upload_complete( filename,id,xhr);
}
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr[filename].open("POST", queryString, true);
xhr[filename].setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr[filename].setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr[filename].setRequestHeader("Content-Type", "application/octet-stream");
xhr[filename].send(file);
}
by doing this i xhr[filename] inside onreadystatechange is undefined because of loop and i want to keep track of every file upload progress and finish it . But as you can see the problem is only keeping track of onreadystatechange with a unique id and i am stuck here. Please can anyone throw light , suggestions and recommendations help is appreciated. thanks
You have deal with Javascript Closure. onreadystatechange see filename,id,xhr of the lastest invoke of send_file_to_server function. To change this rewrite your function like this:
var xhr = Array();
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
xhr[filename] = new XMLHttpRequest();
xhr[filename].upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
(function(localFilename, localId, localXhr){
localXhr[localFilename].onreadystatechange = function(){
if(localXhr[localFilename].status == 200 && localXhr[localFilename].readyState == 4){
on_upload_complete(localFilename, localId, localXhr);
}
}
})( filename,id,xhr)
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr[filename].open("POST", queryString, true);
xhr[filename].setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr[filename].setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr[filename].setRequestHeader("Content-Type", "application/octet-stream");
xhr[filename].send(file);
}
I want to make a php ajax post.(post value without refresh the page) here is my code. It can return the value and show in <div id="msg"></div>, But I also want to use this value.
In #benhowdle89 's help, I made $name= "<div id='msg'></div>". but when I use echo $name, in the source code, I can see <div id='msg'></div>(html tag), this is not a pure value, so I tried to use strip_tags, but the value lost. it seems the left the ajax pointed div tag, the value also gone. Still waiting for help...
index.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
</script>
</head>
<body>
<?php
echo $name="<div id='msg'></div>";
$name1=strip_tags($name);
$name2 = explode("|",$name1);
$namea=$name2[0];
$nameb=$name2[1];
?>
<form name="user_info" id="user_info" method="post">
<input name="user_name" type="hidden" value="abc|def" /><br />
<input type="button" value="abc|def" onClick="saveUserInfo()">
</form>
</body>
value.php
<?php
echo $_POST["user_name"];
?>
This is what I want. post value from index.php, then get the value by self without refresh the page. one botton with two values, I want explode them and finally get $namea and $nameb. I want use them in other php part.
You can put the ajax response into a javascript variable, then you can manipulate it from there:
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
alert( myPhpVariable );
Here is a working javascript example (full code):
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
The PHP file would look like:
$postVar = $_POST["user_name"];
$postVarArr = explode('|', $postVar);
// will show abc
//echo $postVarArr['0'];
// will show def
echo $postVarArr['1'];
by including $name= "<div id='msg'></div>" and calling echo $name, you're just telling the program to store "" in the $name variable and then print what is stored in that variable. That's why you're getting the unwanted output.
not sure if you're having problems posting the value or showing it in the value, but you need to echo the variable where the userName is stored, may need to send that from the ajax to the php and set it to $name.