changing the text of a button in ajax - javascript

I Have list confirmation buttons generated dynamically using PHP.When I click a button i want it change to "approved".But it is not doing so?Nothing changes though the query is submitted successfully.Any help please.Here is my js code snippet:
function appr ($ref) {
var job_id= $ref;
var resp;
var buttons=$('.confirm');
buttons.click(function(){
var $this=$(this);
$this.text=('approved');
});
if (window.XMLHttpRequest) {
resp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
resp = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "job_id="+job_id
resp.open("POST",
"approve.php",
true);
resp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
resp.send(data);
resp.onreadystatechange = display_data;
function display_data() {
if (resp.readyState == 4) {
if (resp.status == 200) {
document.getElementById("myDiv").innerHTML=resp.responseText;
} else {
alert('Request not successful.');
}
}
}
}

you can do it like that
$this.html("approved");

Related

Send and process FormData

I've been struggling for hours with following code without success. In my html I have several inputs (type=text, type=date and selects), and a button calling a js function: onclick=SendNewData().
The JS function is something like the following:
function SendNewData() {
var MyData1=document.getElementById("id1").value;
var MyData2=document.getElementById("id2").value;
var MyData3=document.getElementById("id3").value;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', 'Handler.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("FormNuevaCom").innerHTML = xmlhttp.responseText;
}
}
var data = new FormData;
data.append('DATA1', MyData1);
data.append('DATA2', MyData2);
data.append('DATA3', MyData3);
xhr.send(data);
}
and the Handler.php is something like the following:
if(isset($_POST['DATA1'])) {
$MyVar=$_POST['DATA1'];
echo "Hi there! ".$MyVar." received...";
}
I canĀ“t get any response. Anyone can spot the problem?

How do I have the text and xml files open in a new window/tab?

Here is the code. I am fairly new to JavaScript and I'm learning more every day. This code is from an example from a textbook. Thank you for your responses. Another question I'd like to ask is how can I display the returned text in an unordered list? Would that be something to include in the html side of things or can it be done within the JavaScript file?
window.addEventListener("load",initAll,false);
var xhr = false;
function initAll() {
document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false);
document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false);
}
function getNewFile(evt) {
makeRequest(this.href);
evt.preventDefault();
}
function makeRequest(url) {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
if (xhr) {
xhr.addEventListener("readystatechange",showContents,false);
xhr.open("GET", url, true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}
function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]);
}
else {
var outMsg = xhr.responseText;
}
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
function getText(inVal) {
if (inVal.textContent) {
return inVal.textContent;
}
return inVal.text;
}
}
By the looks of it, you are making an AJAX request and are receiving XML.
In this case, I would:
Open up a new page with window.open()(returns a new Window object)
And then change the document.body.innerHTML of that new page to the XML you have
If you had a webpage that held the XML(maybe the server you are requesting to has one), you can just do:
window.open("page.xml");

How to resolve the conflict two ajax request at a same time

I have one nominal.jsp page,which includes header.jsp.Here i am using Ajax for the first time, for the request in header.jsp,then for the second time Ajax request is called to the nominal.jsp,i am facing the conflict issue in the Ajax request. Because of this issue,my preferred drop-down list is not displayed. Sometimes when response is entered in the JavaScript, the drop-downs are displayed and if the response are not entered in the JavaScript, the drop-downs are not displayed. Tried my level best to resolve the issue, but could not resolve it. Please help me guys
thank u,
My header.jsp code:
<script>
headerDisplay();
function headerDisplay()
{ var url ='<%=request.getContextPath()%>/summary?operation=header';
transactionRequest(url);
}
function transactionRequest(url)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
req.onreadystatechange = transactionResponse;
try
{
req.open("POST", url, true); //was get
}
catch(e)
{
alert("Problem Communicating with Server\n"+e);
}
req.send(null);
}
else if (window.ActiveXObject)
{
// IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = transactionResponse;
req.open("POST", url, true);
req.send();
}
}
}
function transactionResponse()
{
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{ var servletVal = req.responseText;
var myObject = eval('(' + servletVal + ')');
var userId = myObject.userId;
}}}......
</script>
And,this is my nono.jsp code:
<%#include file="/pages/common/header.jsp"%>
<script>
function displayNominal()
{
document.getElementById("ajaxLoading").style.display="block";
var url ='<%=request.getContextPath()%>'+'/nominalList';
postRequest(url);
}
function postRequest(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = nominalSelect;
try {
req.open("POST", url, true); //was get
} catch (e) {
alert("Problem Communicating with Server\n" + e);
}
req.send(null);
} else if (window.ActiveXObject) {
// IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = nominalSelect;
req.open("POST", url, true);
req.send();
}
}
}
function nominalSelect() {
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{
var servletVal = req.responseText;
var myObject = eval('(' + servletVal + ')');
var userId = myObject.userId;
if (userId == null || userId == "") {
window.location = '/accounts1/?status=session';
}
}}..
</script>
<body class="bodystyle" onload="displayNominal()">
<% if("N".equals(roleDemoStatus))
{%>
<!-- /#demo Header -->
<div style="top: 0px; display: block;" id="header" class="fixed">
<div class="outer">
<h1 class="blog-title" style="text-align:center;margin-top:10px;"><span style="font-weight: normal; color:#777777; font-size: 30px;">accounts<font color="#5DA915">1</font>.co</span> Demo Only - <font color="red">Click Here</font> To Use For Free Forever</h1>
</div><!-- .outer -->
<div style="display: block;" class="shadow"></div>
</div>
<!-- /#Demo Header -->
<%} %>
</body>
Again thanks for advance.
Use a single callback and a try/catch block to enforce the request order:
function transactionResponse()
{
// Check whether this is the initial callback or a subsequent one
if (!!transactionResponse.state)
{
try
{
//POST data from the GET request
}
catch(e)
{
//Get data from the GET request
}
}
// Set state after the initial callback reference
else
{
transactionResponse.state = this;
}
}
References
Long Polling Experiment

Passing response from multiple XMLHttpRequests to div

I am querying a PostGIS database based on where a user clicks on a google map. I am then parsing the JSON response into a googleMaps infoWindow. This has been working great but I'd now like to query multiple urls and use those responses to fill in the infoWindow. Below is an example of the functions I've used that work great. Note: please disregard the url provided as I just made it up for this example.
var clickLoc;
function queryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var loUrl = 'http://www.myspatialdataset.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = clickResponse;
try {
req.open("GET", loUrl, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = clickResponse;
req.open("GET", loUrl, true);
req.send();
}
}
}
function clickResponse(){
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
var clickPingBack = JSON.parse(req.responseText);
var loResponse = clickPingBack;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
fillWithClicked(loResponseParsed);
}
else
{
var loResponseParsed=' other';
fillWithClicked(loResponseParsed);
}
}
}
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(loResponseParsed){
infowindow.setContent(loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
How could I now do this for multiple url requests and pass those responses to the same, fillWithClicked function that fills in the infoWindow?
The code below is obviously wrong but may better explain what I am trying to do i.e. multiple URLS and filling the infoWindow with the response from two url requests. This sometimes works but is totally wrong
var clickLoc;
function distQueryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var distUrl = 'http://www.myspatialdataset.com/sql/?q=select%20district%20from%20mt_elk%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
distReq = new XMLHttpRequest();
distReq.onreadystatechange = loQueryAct(clickLoc);
try {
distReq.open("GET", distUrl, true);
} catch (e) {
alert(e);
}
distReq.send(null);
} else if (window.ActiveXObject) { // IE
distReq = new ActiveXObject("Microsoft.XMLHTTP");
if (distReq) {
distReq.onreadystatechange = loQueryAct(clickLoc);
distReq.open("GET", distUrl, true);
distReq.send();
}
}
}
function loQueryAct(clickLoc){
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var loUrl = 'http://www.myspatialdataset.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
loReq = new XMLHttpRequest();
loReq.onreadystatechange = distClickResponse;
try {
loReq.open("GET", loUrl, true);
} catch (e) {
alert(e);
}
loReq.send(null);
} else if (window.ActiveXObject) { // IE
loReq = new ActiveXObject("Microsoft.XMLHTTP");
if (loReq) {
loReq.onreadystatechange = distClickResponse;
loReq.open("GET", loUrl, true);
loReq.send();
}
}
}
function distClickResponse(){
if (distReq.readyState == 4 && loReq.readyState == 4) { // Complete
if (distReq.status == 200 && loReq.status == 200) { // OK response
var distPingBack = JSON.parse(distReq.responseText);
var distResponse = distPingBack;
var loPingBack = JSON.parse(loReq.responseText);
var loResponse = loPingBack;
if (distResponse.rows.length>0)
{
var distResponseParsed=distResponse.rows[0].district;
}
else
{
var distResponseParsed=' other';
}
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
}
distFillWithClicked(loResponseParsed,distResponseParsed);
}
}
var infowindow = new google.maps.InfoWindow;
function distFillWithClicked(distResponseParsed,loResponseParsed){
infowindow.setContent(distResponseParsed+loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
I figured it out. Using getJSON instead of XMLHttpRequest was the key. I know this could be cleaner but it does work.
var clickLoc;
function queryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var toFillArray=Array();
var loUrl='http://www.mypostgis.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
var distUrl='http://www.mypostgis.com/sql/?q=select%20district%20from%20mt_elk%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
$.getJSON(loUrl,function(tmpLoDat){
if (tmpLoDat.rows.length>0)
{
var tempCat=tmpLoDat.rows[0].ownercateg;
toFillArray.push(tempCat);
}
else
{
var tempCat='other';
toFillArray.push(tempCat);
}
otherFunction(toFillArray,distUrl);
})
}
function otherFunction(toFillArray,distUrl){
$.getJSON(distUrl,function(tmpDistDat){
if (tmpDistDat.rows.length>0)
{
var tempDist=tmpDistDat.rows[0].district;
toFillArray.push(tempDist);
}
else
{
var tempDist='Other';
toFillArray.push(tempDist);
}
fillWithClicked(toFillArray);
})
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(toFillArray){
infowindow.setContent(toFillArray[0]+toFillArray[1]);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
If you want the data to grow your element, let's try something like that :
function fillWithClicked(loResponseParsed){
document.getElementById("regulations").innerHTML += loResponseParsed;
}
If the calls of your function are not in the same page, you'll need to use a cache file and a user_id (session id, cookie id or IP adress...):
// js & jquery for example
function fillWithClicked(loResponseParsed,user_id)
{
$.post('cachecreate.php',{content:loResponseParsed,user_id:user_id},
function()
{
$.get('cachefile_'+user_id+'.html',
function(data)
{
document.getElementById("regulations").innerHTML=data;
});
});
}
// cachecreate.php for example
<?php
$cache = "cachefile_".$_POST['user_id'].".html";
ob_start();
if(file_exists($cache))
{
include($cache);//or readfile(); i forgot...
echo "<hr/>".$_POST['content'];// Strip <hr/> for JSON
}
else
{
echo $_POST['content'];
}
$page_content=ob_get_contents();// if JSON needed : json_encode($page_content);
ob_end_clean();
file_put_contents($cache, $page_content);// PHP 5+ function
?>
I hope that it may help you, or bring you to the solution.
EDIT regarding your new details
Try something like this (I lighten your code...).
With this you can add as multiple urls as you want.
var clickLoc;
function queryAct(event)
{
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var url=Array();
var data=null;
url['loUrl'] ="url1";
url['distUrl'] ="url2";
url['otherUrl'] ="urlx";
for(page in url)
{
data+=getJSON(page);
}
fillWithClicked(data);
}
function getJSON(url)
{
if (window.XMLHttpRequest)
{req = new XMLHttpRequest();}// Non-IE
else if (window.ActiveXObject)
{req = new ActiveXObject("Microsoft.XMLHTTP");}// IE
if(req)
{
req.open("GET", url, true);
req.send(null);
req.onreadystatechange = function() {
if(req.readyState == 4)
{
if (req.status == 200)
{ // OK response
var clickPingBack = JSON.parse(req.responseText);
var loResponse = clickPingBack;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
return loResponseParsed;
}
}
}
}
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(loResponseParsed)
{
infowindow.setContent(loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
EDIT -> External domain files
httpRequest doesn't work with files in another domain.
You can use one of those solutions, I may use the second for me.
PHP Solution
// In your js file, change the urls like this
url['url_x'] ='myphppage.php?url=url_x_to_parse';
// myphpage.php script that displays the content of the external file
<?php
if(isset($_GET['url'])) {
header("Content-type: text/json");
echo file_get_contents(urldecode($_GET['url']));
}
?>
JQUERY solution (better one)
// change the name of getJSON function cause jquery uses the same name...
function getURLcontent(url)
{
$.get(url,function(data){
var clickPingBack = JSON.parse(data.responseText);
var loResponse = clickPingBack;
loResponse=data;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
return loResponseParsed;
});
}
download jquery library http://code.jquery.com/jquery-1.7.1.min.js
include jquery plugin in the head of your page with <script src="jquery-1.7.1.min.js"></script>

JavaScript data post

I am working in PHP I have created a page here I have 2 combo box when I select first combo box item the second one is filled according the first combobox using JavaScript the problem I am facing is where I am trying to save the data of second combo box in database I found null value. transition_party_id is the combobox that fill dynamically here I code
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getparty(category) {
var strURL="../admin/get_partyname.php?category="+category;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('partydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
req.open("GET", strURL, true);
req.send(null);
You send 'null' post data by "GET" method.
Or you waiting data in get?

Categories