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 );
}
Related
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);
I am working on Codeigniter, i am facing one problem i have to show the user error message when he is uploading any other file type to server using ajax. I do not want to load view again to show the error message. My code is as follows:
Please help me to solve my problem.'
View:
function upload_video_Data(a)
{
var fd = new FormData(document.getElementById('posting_comment_'+a));
fd.append("file_m_id",a);
var bar = $('.bar');
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById("nameTest").value=xhr.responseText;
}
}
xhr.open("POST", "Dashboard/do_upload_video");
xhr.send(fd);
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
$("#status").animate( { width: percentComplete.toString()+"%"}, 5);
}
}
}
Controller:
public function do_upload_video()
{
$lecture_id=$_POST['file_m_id'];
$output_dir = "./uploads/";
$fileName = $_FILES["save_movie_".$lecture_id]["name"];
if(!move_uploaded_file($_FILES["save_movie_".$lecture_id]["tmp_name"],$output_dir.$fileName))
{
echo '0';
}
else
{
echo '1';
}
}
Use this code before your ajax to validate the extension of file
var ext = $('#my_file_id').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
Now your code look like this
function upload_video_Data(a)
{
var ext = $('#my_file_id').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
return false;
}
var fd = new FormData(document.getElementById('posting_comment_'+a));
fd.append("file_m_id",a);
var bar = $('.bar');
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById("nameTest").value=xhr.responseText;
}
}
xhr.open("POST", "Dashboard/do_upload_video");
xhr.send(fd);
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
$("#status").animate( { width: percentComplete.toString()+"%"}, 5);
}
}
}
I want to know where is gsmarena.com put ajax url when they do a search. I tried to explore the source of it and I found this function:
function autocompleteLoadList() {
if (AUTOCOMPLETE_LIST !== null) return;
AUTOCOMPLETE_LIST = false;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP")
} catch (x) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
} catch (x) {
AUTOCOMPLETE_LIST = null
}
}
}
xhr.open("GET", AUTOCOMPLETE_LIST_URL, true);
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4)
if (xhr.status == 200) {
var data;
if (window.JSON) {
data = JSON.parse(xhr.responseText)
} else {
data = eval("(" + xhr.responseText + ")")
}
AUTOCOMPLETE_MAKERS = data[0];
AUTOCOMPLETE_LIST = data[1];
if (typeof AUTOCOMPLETE_CALLBACK != "undefined") AUTOCOMPLETE_CALLBACK()
} else {
AUTOCOMPLETE_LIST = null
}
};
xhr.send(null)
}
http://cdn2.gsmarena.com/w/js/autocomplete.js?ver=2
I do not know where they put the url to doing a search.
when I open the network tab in Google Chrome console there is also no url to POST or GET. how could they do it?
I'm calling a PHP file with XMLHttpRequest, but now the call doesn't complete and I
have no idea why. The req.readyState isn't 4, and I don't know why because the PHP file is okay and does exactly what supposed to (just echo a string).
Can anyone see what I can not see?
function processAjax(id, option) {
if (option == "lpath") url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?id=" + id;
else url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?cat=" + id;
//create AJAX request
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv();
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv();
req.open("GET", url, true);
req.send();
}
}
}
//this function handles the response from the ajax request
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
//all of the code below doesn't happen because its not the option
if (option == "lpath") {
var response = req.responseText.split('##');
var articles = response[0].split(';');
var quizes = response[1].split(';');
document.getElementById("article_id").innerHTML = "";
document.getElementById("quiz_id").innerHTML = "";
for (var i = 0; i < articles.length; i = i + 2) {
if ((i + 1) <= articles.length) {
var option = new Option( /* Label */ articles[i + 1], /* Value */ articles[i]);
document.getElementById("article_id").options.add(option);
}
}
for (var i = 0; i < quizes.length; i = i + 2) {
if ((i + 1) <= quizes.length) {
var option = new Option( /* Label */ quizes[i + 1], /* Value */ quizes[i]);
document.getElementById("quiz_id").options.add(option);
}
}
delete req, articles, quizes;
} else {
document.getElementById("catdiv").innerHTML += req.responseText;
document.getElementById("allchildren").value = req.responseText;
}
} else { //failed to get response
alert("Problem: " + req.statusText);
}
}
document.getElementById("catdiv").innerHTML += "Y U NO COMPLETE?!";
}
req.onreadystatechange = targetDiv();
should be
req.onreadystatechange = targetDiv;
The original code calls targetDiv() immediately after that line of code is run, which is probably not what you wanted to do. The fixed code calls the function correctly, after the Ajax request is received.
I have to show a bunch of markers on the map after the map has been dragged. How do i pass the current map center from javascript to my php code to get the data? The latlng is not getting updated.
var CHANGE_MARKERS = false;
var CITY_MAP_CENTER_LAT= '12.971598';
var CITY_MAP_CENTER_LNG= '77.594569';
var CITY_MAP_ZOOMING_FACT= 15;
var CITY_MAP_VIEW_TYPE = '';
var LAT = "";
var LNG = "";
var LATLNG = "";
var A1,A2,A3,A4;
var map;
var mgr;
var mc = null;
var markerClusterer = null;
var showMarketManager = false;
var infoWindow;
var markersarray = [];
var allmarkers = [];
function setLatLng(){
if(CHANGE_MARKERS == false){
LAT = '12.971598';
LNG = '77.594569';
}
else{
var ctr = map.getCenter();
LAT =ctr.lat();
LNG =ctr.lng();
}
}
function setMarkers(){
allmarkers.length = 0;
allmarkers = [];
var markers = [];
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(<?php echo $_SESSION['center']; ?>);
//var markersData = xmlhttp.responseText;
//alert(markersData);
markers = {'data':[
<?php
?>
]};
for (var level in markers) {
//alert(markers[level].length);
}
}
}
xmlhttp.open("GET","../subscriber_listing/google.php?center=" + map.getCenter(),false);
xmlhttp.send();
if (markers) {
for (var level in markers) {
//alert(markers[level].length);
for (var i = 0; i < markers[level].length; i++) {
var details = markers[level][i];
//alert(details.name);
var image = new google.maps.MarkerImage(details.icons,new google.maps.Size(PIN_POINT_ICON_WIDTH, PIN_POINT_ICON_HEIGHT));
var myLatLng = new google.maps.LatLng(details.location[0], details.location[1]);
var newmarker = createMarker(details.name,myLatLng,image);
allmarkers.push(newmarker);
}
mgr.addMarkers( allmarkers, 0 );
}
mgr.refresh();
}
}
function doSearch(){
display();
CHANGE_MARKERS = true;
initialize();
}
function createMarker(name,latlng,image){
var marker = new google.maps.Marker({
title: name,
position: latlng,
icon: image,
clickable: true,
draggable: false,
flat: true
});
return marker;
}
function display(){
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)
{
}
}
xmlhttp.open("GET","../subscriber_listing/google.php?center=" + map.getCenter(),false);
xmlhttp.send();
}
if(CITY_MAP_CENTER_LAT=='')
{
var CITY_MAP_CENTER_LAT = 34;
}
if(CITY_MAP_CENTER_LNG=='')
{
var CITY_MAP_CENTER_LNG = 0;
}
if(CITY_MAP_CENTER_LAT!='' && CITY_MAP_CENTER_LNG!='' && CITY_MAP_ZOOMING_FACT!='')
{
var CITY_MAP_ZOOMING_FACT = 13;
}else if(CITY_MAP_ZOOMING_FACT!='')
{
var CITY_MAP_ZOOMING_FACT = 3;
}
var PIN_POINT_ICON_HEIGHT = 32;
var PIN_POINT_ICON_WIDTH = 20;
if(CITY_MAP_VIEW_TYPE=='TERRAIN')
{
var maptype= google.maps.MapTypeId.TERRAIN;
}else
if(CITY_MAP_VIEW_TYPE=='SATELLITE')
{
var maptype= google.maps.MapTypeId.SATELLITE;
}else
if(CITY_MAP_VIEW_TYPE=='')
{
var maptype= google.maps.MapTypeId.ROADMAP;
}
if(MAP_DISABLE_SCROLL_WHEEL_FLAG)
{
var MAP_DISABLE_SCROLL_WHEEL_FLAG = 'No';
}
function initialize() {
setLatLng();
var myOptions = {
zoom: CITY_MAP_ZOOMING_FACT,
center: new google.maps.LatLng(LAT, LNG),
mapTypeId: maptype
}
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
mgr = new MarkerManager(map);
infoWindow = infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(mgr, 'loaded', function(){
setMarkers();
});
google.maps.event.addListener(map, "dragend", function() {
doSearch();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Getting the lat/lng values in JavaScript API v3:
map.getCenter().lat() // latitude in degrees
map.getCenter().lng() // longitude in degrees
To retrieve those values after the map has been dragged, add a listener for the center_changed and/or dragend events.
Since all this happens after the map has been rendered--that is, after any server-side PHP has already run--you'll need to use AJAX or some other technology to send the values to the server if you need to process them with PHP for whatever reason.