GET data not being sent with AJAX call - javascript

I need to add some data to a page using AJAX. I have written the following code for the purpose. The problem is that the call is not returning any data.
The PHP file is just for test purposes as of now. Obviously, some actually functionality will be added to it.
Javascript:
<script type="text/javascript">
function addprod(prodid) {
var xmlHttp;
if (prodid="") {
document.getelementbyID("newprod").innerhtml="";
return;
}
if (window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else{
xmlHttp=new ActiveXObject("Microsoft.XMLHttp");
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readystate==4 && xmlHttp.status==200){
document.getelementbyID("newprod").innerhtml=xmlHttp.responseText;
}
}
xmlHttp.open("GET","add_row.php?q="+prodid,true);
xmlHttp.send();
}
</script>
HTML:
<span id="newprod"></span>
<form>
<input type="text" name="addprodbyid" class="form-control" placeholder="Enter Product ID" onkeyup="addprod(this.value)" />
</form>
add_row.php:
<?php
$prod_id=$_REQUEST['q'];
echo $prod_id;
?>
I tried checking with Firebug. The AJAX call is working, but no data is being sent to the PHP file. The URL that gets called everytime is add_row.php?q=.

mistakenly assign inside if condition
if (prodid = "") {
document.getelementbyID("newprod").innerhtml="";
return;
}
correct is
if (prodid == "") {
document.getelementbyID("newprod").innerhtml="";
return;
}

Why not with jquery simple
function addprod(prodid) {
$.ajax({
url: "add_row.php",
type: "post",
data: {'q':prodid},
success: function(data){
$("#newprod").html(data);
},
error:function(){
$("#newprod").html('There is error while submit');
}
});
}
add_row.php:
$prod_id=$_POST['q'];
echo $prod_id;

If
xmlHttp.readystate
is not a type, then correct it as (s => S)
xmlHttp.readyState

If you still curious about why your variant may not work: first of all, move your onreadystatechange function below xmlhttp.send(). Also try to change onreadystatechange a little
xmlHttp.open("GET","add_row.php?q="+prodid,true);
xmlHttp.send();
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState != 4) return
if (xmlHttp.status == 200) {
document.getelementbyID("newprod").innerhtml=xmlHttp.responseText;
}
}
It's seems no change from your variant, but that is the one that helped me one day.

Related

ajaxStart() and ajaxStop() functions not getting fired

I am building a Q/A website. When the user clicks on a particular question, he is redirected to the question page where the user can post answers.
Now, the issue is while the user clicks on "Answer" link, few things are processing in the background like updating db, sending mail, etc. I am trying to display a load indicator in the UI but the AJAX function is not getting triggered.
Here is my code:
HTML:
<span id="msg"><img src="ajax-loader.gif"/></span>
<a id="sub-link" href="javascript:void(0)" onclick="loadAnswerList(document.getElementById('user-ans').value,<?php echo $qid; ?>,'<?php echo $posted_by; ?>')">Answer</a>
JS:
$(document).ajaxStart(function () {
$('#msg').show();
}).ajaxStop(function () {
$('#msg').hide();
});
AJAX request
function loadAnswerList(ans,qid,postedBy,page) {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("ans_container").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","load_answers.php?ans="+ans+"&qid="+qid+"&postedBy="+postedBy+"&page="+page,true);
xmlhttp.send();
}
I also tried adding $(document).ready(function() { .... }); above the ajax but still it is not working. Am I missing anything?
Am using jQuery version 3.2.1
jQuery does not work with the native XMLHttpRequest object. The ajaxStart and ajaxEnd lines you are using deals with their api. So in order to use it, you need to use jQuery's .ajax() or .get() methods.
Thanks for the details.
This is the modified function:
function loadAnswerList(ans,qid,postedBy,page) {
var answer=ans;
var qstnid=qid;
var postby=postedBy;
var pg=page;
var request = $.ajax({
type: "GET",
url: "load_answers.php?ans="+ans+"&qid="+qid+"&postedBy="+postedBy+"&page="+page",
data: {ans: answer, qid: qstn_id, postedBy: postby, page: pg},
dataType: "html"
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
Please correct me if am wrong. One more thing - I want to display the response from the php page to a particular div as I have done in my previous ajax request.
document.getElementById("ans_container").innerHTML = this.responseText;
How do I do it here?

How to trigger a variable/method in python from a html file with javascript

I want to have a hyperlink on a html page run a variable that is defined in my python file. The variable is going to clear my database. Here is the code I am trying to use.
Python
#app.route('/log')
def log():
cleardb = db.session.delete()
return render_template('log.html', cleardb=cleardb)
Html
<a onclick="myFunction()">Clear database</a>
Javascript
<script>
function myFunction()
</script>
I don't know what javascript I need to run the variable. I want to make the cleardb get triggered so that it will delete the database.
Thanks
You need to make an ajax request with javascript to /log, it would look something like this:
function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//Do Success functionality here
}
else if (xmlhttp.status == 400) {
//Handle 400 errors here
}
else {
//All other errors go here
}
}
};
xmlhttp.open("GET", "/log", true);
xmlhttp.send();
}

HTTP(S) Request With Javascript and receive JSON data

since I'm new on http(s) request case, I have one case here that must be written on Javascript, hope someone could help me because I've searched everywhere and couldn't find the answer. Here is the case:
However, when the connection rate goes up to 5, I will have to wait until one of them is finished corresponding before sending a request, so that 2 or more of them are not over 5.
In addition, when the response code is not 200, I will retry 3 times. If the response code is still not 200 after retrying 3 times, the error function will pursue. I also must receive the Json data of the response body as an argument function.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
else if (xmlhttp.readyState==4 && xmlhttp.status!=200){
document.write("Error");
}
}
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
Please help on comment below or you can suggest me links that could help me with this case. Thanks.
Something like this?
Concerning the connection rate, you can go multiple directions with this, since it isn't 100% clear what you want. The easiest solution would be to have your asp page return a 'fake error' as a json object and have the success function check if the response contains this 'fake error'. If so, resend the request to the server. Or you could have the asp page only send a response, if the connection rate < 5, but that might mean your user ends up waiting longer that expected.
var getJSON = function getJSON( resource, success, failure ) {
var xmlhttp = (window.XMLHttpRequest) ? xmlhttp=new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
retry = 0;
success(xmlhttp.responseText, 200);
}
else failure(xmlhttp.status);
}
xmlhttp.open("GET", resource, true);
xmlhttp.send();
},
retry = 0,
success = function success( response, status ) {
document.querySelector("#myDiv").textContent = response;
},
failure = function failure( status ) {
if (retry < 3) {
retry += 1;
getJSON("demo_get.asp", success, failure);
}
else console.log('ERROR');
};
document.querySelector('button').addEventListener('click', function( event ) {
getJSON("demo_get.asp", success, failure);
});

Flag Query PHP to JavaScript

I have that
JavaScript
flagQuery = session.reponseText;
alert(flagQuery);
flagQuery = JSON.parse(flagQuery);
contentElt.innerHTML = "valeur FLAG" + flagQuery;
My javascript must receive a flag sent from php.
The code above is the treatment of flag when it is received.
In my php I declare the variable flag to true.
I want to treat this with Ajax, if it's possible.
I don't know what to add in the PHP to get the flag in JavaScript?
I should prefer not to have to overload my code with a jQuery bookshop that I will use it for half a score line of code.
I assume want to access php value through ajax request. And you can do that liek below;
PHP: flag.php
<?php
$flag = "Your flag value";
echo $flag;
JS:
$.ajax({
url: "flag.php",
type: "get",
success: function(data){
alert("Flag value is: " + data);
},
error:function(){
alert("Error occured!");
}
});
Pure JS:
<script>
function getFlagValue() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState==4 && xmlHttp.status==200) {
alert(xmlHttp.responseText);
}
}
xmlHttp.open("GET","flag.php",true);
xmlHttp.send();
}
</script>
Hello. Try this and see if it's you need.
//PHP File
<?php
echo json_encode(array("one","two"));
?>
//Js File
$.get("page.php", function(data){
alert(data)
})

Ajax call not successful

I am making a javascript function call on onclick of any checkbox like this:
function getPGCountList(pageNo) {
var url = "someJsp.jsp?" + pageNo;
alert(1);
if (window.XMLHttpRequest) {
alert(2);
xmlhttp = new XMLHttpRequest();
} else {
alert(3);
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
alert(4);
xmlhttp.onreadystatechange = function () {
alert(5);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(6);
document.getElementById("searchForPage").innerHTML = xmlhttp.responseText;
}
};
alert(7);
xmlhttp.open("GET", url, true);
alert(8);
xmlhttp.send();
}
The alert output I am getting is at my hosted site:
1-2-4-7-5-8-5-5-5
But in my local system it is:
1-2-4-7-5-8-5-5-5-6
I need to execute alert 6 also to change the content.
I am not sure where is the problem?
Your code looks fine to me. Check the path to someJsp.jsp
It's obviously not returning a normal response from the ajax call otherwise it would enter your if block and fire alert 6.
Just a thought too, but if you alert xmlhttp.readyState and xmlhttp.status maybe it'll help you find your problem. IF they are undefined, or refer to an object that is undefined, then your new XMLHttp requests failed. IF they give you results, you can see what the responses mean

Categories

Resources