Ajax POST never gets sent? - javascript

I'm having an issue with my ajax POST for some reason the POST is never made! can't for the life of me work it out?
yeah so I used the network debug tool in firefox to check the POST request but the POST request never gets made..
The function is definitely getting called too as I have added an alert alert("start") to the beginning of the function which does run.
AJAX
<script>
function updateContentNow(pid2, status2) {
var mypostrequest = new ajaxRequest();
mypostrequest.onreadystatechange = function() {
if (mypostrequest.readyState == 4) {
if (mypostrequest.status == 200 || window.location.href.indexOf("http") == -1) {
document.getElementById("livestats").innerHTML = mypostrequest.responseText;
} else {
alert("An error has occured making the request");
}
}
}
var parameters = "cid=clientid&pid=6&statusinfo=approve";
mypostrequest.open("POST", "http://mydomain.com.au/content-approval/ajax.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
</script>
UPDATED WORKING: thanks peps..
<script>
function updateContentNow(pid2,status2)
{
var mypostrequest=new XMLHttpRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("livestats").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var parameters="cid=<?=$clientID?>&pid="+pid2+"&statusinfo="+status2;
mypostrequest.open("POST", "http://mydomain.com.au/content-approval/ajax.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
</script>

Are you using some external Ajax classes, at least ajaxRequest() object doesn't exist in plain JavaScript. Try to substitute this line
var mypostrequest = new ajaxRequest();
by that:
var mypostrequest=new XMLHttpRequest();
Then even calling your method with
updateContentNow("","");
at least makes the POST request as you easily can see with Firebug.

Related

Using AJAX to execute a PHP script through a JavaScript function

I have an anchor link with no destination, but it does have an onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
But clicking the link just changes the URL to http://localhost/.
I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Can you please provide your : del_post.php file?
Normally you can show a text or alert in a
<div id="yourname"></div>
by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("yourname").innerHTML = xmlhttp.responseText;
}
This response is coming from your PHP file for example :
function remove_record(ARG){
if ($condition==true)
echo "TRUE";
else
echo "FALSE";
}
You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:
<script>
function deletePost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Do something if Ajax request was successful
}
};
xhttp.open("GET", "del_post.php", true);
xhttp.send();
}
</script>
You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.
Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:
What file to call
What to do with the response from the file you called
What to do if an I/O error happens
So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) - and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
//textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}
function ohNo()
{
//stuff like URL not found, etc.
alert("I/O error");
}
And now that you're armed with that, this is how you compose the real call inside the function you called at the <a>:
function functionThatReallyCallsAjax()
{
//there are probably many scenarios but by having this extra function,
//you can perform any processing you might need before the call
doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}
One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the 'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)

Sending values to a server to be stored in a database and recording space presses

I have two questions.
First: would this actually work? I'm trying to record every time someone presses and releases the space bar.
Second: if it works, what would I need to do next to get everything that is stored in RecordKey sent to a server to be stored on a database? (I already have mysql and php "up" and "running" ).
Thanks
window.addEventListener("keydown", keyPressed, false);
window.addEventListener("keyup", keyReleased, false);
var RecordKey=[];
function keyPressed(space) {
if (space.charCode == "32") {
RecordKey[space.keyCode] = true;
}
}
function keyReleased(space) {
RecordKey[space.keyCode] = false;
}
Here is an example how to send it to example server.
JS Fiddle: http://jsfiddle.net/xv3d9rfj/
This is the function to send the data:
function sendToExampleServer(data_to_send){
var x=new XMLHttpRequest
x.open('GET','http://httpbin.org/get?' + data_to_send)
x.send()
x.onreadystatechange=function(){
if(x.readyState==4)
alert(x.responseText)
}
}
The function receives data to send, and send it to a server.
The are some issues with you code, but this is the complete code:
function sendToExampleServer(data_to_send){
var x=new XMLHttpRequest
x.open('GET','http://httpbin.org/get?' + data_to_send)
x.send()
x.onreadystatechange=function(){
if(x.readyState==4)
alert(x.responseText)
}
}
sendToExampleServer('up')
window.addEventListener("keydown", keyPressed, false);
window.addEventListener("keyup", keyReleased, false);
var RecordKey=[];
function keyPressed(space) {
if (space.charCode == "32") {
RecordKey[space.keyCode] = true;
sendToExampleServer('keyDown')
}
}
function keyReleased(space) {
RecordKey[space.keyCode] = false;
sendToExampleServer('keyUp')
}
You can use simple ajax i am providing example for POST method you can also do it with GET method
function keyPressed(space) {
if (space.charCode == "32") {
var ajax = new XMLHttpRequest();
ajax.open("POST", "recordKey.php", true);
ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var response = ajax.responseText;//recordKey.php response from echo function
//console.log(response);
}
else{console.log(response);}
}
};
document.getElementById("status").innerHTML = "...";
ajax.send("key=B");//data you want to send like you do with GET/POST forms
}
}
I am assuming you are probably new to this so i would recommend to you learn how ajax work. You can learn here http://www.w3schools.com/ajax/default.asp
After that you can see here how to work with php and ajax http://www.w3schools.com/php/php_ajax_intro.asp

Ajax call with javascript fails with internet explorer

OK here is my code which i am using to call a remote site for a list of data objects which i want to display on another site.
This works fine with Chrome and Firefox but throws error in IE "Permission denied"
I also added the request for Access-Control-Allow-Origin and headers but the issue persist in IE....
I can't use jQuery because the site on which I'll put this might not have jQuery. Does it have to something with cross domain request?
<script id= "sc1" type="text/javascript">
function ajaxRequest() {
var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
if (window.ActiveXObject) {
for (var i = 0; i < activexmodes.length; i++) {
try {
return new ActiveXObject(activexmodes[i])
} catch (e) {
}
}
} else if (window.XMLHttpRequest) return new XMLHttpRequest()
else return false;
}
var contentDiv = document.createElement("div");
contentDiv.id = 'contentJobsoid';
document.getElementById('sc1').parentNode.appendChild(contentDiv);
(function(){
var mygetrequest = new ajaxRequest()
if (mygetrequest.overrideMimeType) mygetrequest.overrideMimeType('text/html')
mygetrequest.onreadystatechange = function () {
if (mygetrequest.readyState == 4) {
if (mygetrequest.status == 200 || window.location.href.indexOf("http") == -1) {
var data = mygetrequest.responseText;
document.getElementById("contentJobsoid").innerHTML = data;
} else {
console.log("An error has occured making the request");
}
}
}
mygetrequest.open("GET", "http://www.demo.com/demo/dee0c7fe-867d-408d-a00f-d9bed4b169a7", true);
mygetrequest.send(null);
return false;
}());
</script> -->
I just passed the data from the server in form of string in the script src tag and it solved my problem very easily

xmlHttpRequest.send(Params) not working in tomcat 7

I am trying to send some parameters through xmlHttpRequest.send(params) written in a JS file to my servlet where I try to get the parameters by req.getParameter("some_Parameter"); it returns null on the servlet. though if i send the parameters by appending them in url it works fine. but when the url will be large it will break the code. so please someone help me out.
Thanks in advance.
function doHttpPost(theFormName, completeActivity)
{
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
var xmlMessage = buildPOST(theFormName, completeActivity);
var responseTxt;
try {
xmlhttp.Open(document.forms[theFormName].method, document.forms[theFormName].action+'?'+xmlMessage, false);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
responseTxt = xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
enableDisableLinks(true);
setPointer();
xmlhttp.Send();
if(xmlhttp.Status != 200) {
alert("Post to server failed");
}
} catch (e) {
responseTxt = "Exception while posting form data: Error No: " + e.number + ", Message: " + e.description;
}
resetPointer();
enableDisableLinks(false);
var expectedTxt = "Form Data had been successfully posted to the database."
if(responseTxt.toString() == expectedTxt.toString()) {
// MNP: New requirement from Jeanne, should not refresh CM page, commenting it off for now
//if(completeActivity) {
// if (typeof (ViewCaseDetailBtn) != 'undefined') {
// ViewCaseDetailBtn.click();
// }
//}
return true;
} else {
alert (responseTxt);
}
return false;
}
BUGS
//IE only - shooting yourself in the
// Not all IE versions use ActiveX!
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); foot.
//JavaScript case sensitive, open !== Open
xmlhttp.Open(document.fo...
//JavaScript case sensitive, send !== Send
xmlhttp.Send();
//JavaScript case sensitive, status !== Status
xmlhttp.Status
AND if you are using synchronous, it does not call the onreadystatechange.
If you are using POST, the value needs to be in send("valuestosendup") not on the querystring.
This code shows why you should really use a framework to make Ajax calls and to not roll your own.

jsp with ajax two simultaneous requests only getting one response

I have a jsp page where I'm trying to send multiple (two currently) ajax requests at once, but I only seem to get the second response. This guy described my problem exactly, but his solution didn't work for me.
Here is my js code:
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
} else if(window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
//Error for an old browser
alert('Browser error');
}
return req;
}
function sendRequest(method, url, d){
var http = createRequestObject();
var div = d;
if(method == 'get' || method == 'GET'){
http.open(method, url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById(div).innerHTML = response;
}
}
};
http.send(null);
}
}
And here is how I call that code:
QC1 Status: <div id='qc1'>blah</div>
<br />UAT2 Status: <div id='uat2'>blah2</div>
<a onclick="sendRequest('GET','index.jsp?qc1.properties=true','qc1'); " href="#">qc1</a>
<a onclick="sendRequest('GET','index.jsp?uat2.properties=true','uat2'); " href="#">uat2</a>
<a onclick="sendRequest('GET','index.jsp?qc1.properties=true','qc1'); sendRequest('GET','index.jsp?uat2.properties=true','uat2'); " href="#">both</a>
When I call one at a time they work as expected, but the "both" link only updates with the second request, even though I know it runs the index.jsp code for both.
EDIT: Ok, after fixing the obvious mistake that BalusC pointed out, it works. Fixed it in this post too.
You're indeed sending two requests on the same URL and updating the same div. Shouldn't the first one go to the qc1 one and update the qc1 one?

Categories