Here i want to pass the 'q' value from ajax to controller function in codeigniter.
ajax code:
function getdata(str)
{
if (str == "") {
document.getElementById("yer").innerHTML = "";
return;
} else {
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) {
document.getElementById("bus").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","<?php echo site_url('money_c/taxcalculator1'); ?>?q="+str,true);
xmlhttp.send();
window.location="<?php echo site_url('money_c/taxcalculator'); ?>"
}
}
controller:
function taxcalculator1()
{
$bt=$_GET['q'];
echo $bt;
}
Here i want to pass the 'q' value from ajax to controller function in codeigniter.
As soon as you have started the Ajax request sending with this:
xmlhttp.send();
You leave the page with this:
window.location="<?php echo site_url('money_c/taxcalculator'); ?>"
… which aborts the Ajax request, removes the place you are trying to edit with innerHTML and destroys the JavaScript that would be trying to do that anyway.
If you want to use Ajax then:
Put the data you want to show to the user the response from taxcalculator1
Use onreadystatechange to show it to the user
Don't leave the page before that happens (remove the window.location line).
If you want to load an entirely new page:
Don't use Ajax
Just submit a form to a URL
Display the data you want the user to see (in the form of an HTML document) in the response to that request
Related
I am having a simple html page for login. The html will look like,
<form action="createUsers.html" method="post" onsubmit="return loginValidation();">
I am using the ajax for it. if the user is not available, it will display error msg in the login page. else it will navigate the user to createUsers.html page.
The javascript file will look like and it will call the servlet,
if((document.getElementById("user").value !="")&& (document.getElementById("pass").value != "")){
var params = "&user=" + uname + "&pass=" + upwd;
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)
{
var result = xmlhttp.responseText;
}
}
xmlhttp.open("POST","login",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params);
alert(result)
if(result=="success"){
return true;
}
else if(result=="failure") {
document.getElementById("errormsg").innerHTML=xmlhttp.responseText;
return false;
}
}
This ajax call will check for the user in the database and it will return success if the user is available.
The problem is that, always the code is calling the else if statement, even if the value of result is success. Even the alert statement is also displayed as success. I am not sure why it is not comparing the result=="success" statement ?
AJAX are by default asynchronous calls...
Your callback function is actually returning value (true/false) to xmlHttp object through onreadystatechange but not to your validation function which is associated to HTML window DOM object. Your validation function simply returning true to your form submit event and that's why you anyway make it navigate/submit to next page...
You should call form.submit from your callback function itself on success result, you just need to retrieve form element object in your callback. And add "return false" in 'onSubmit' to avoid form getting submitted automatically.
Hope you understood the problem.
if ((document.getElementById("user").value != "") && (document.getElementById("pass").value != "")) {
var params = "&user=" + uname + "&pass=" + upwd;
// declare it here
var result;
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) {
// accessing to parent scope`s variable
result = xmlhttp.responseText;
callback(result);
}
}
xmlhttp.open("POST", "login", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
function callback (data){
var result = data;
alert(result)
if (result == "success") {
return true;
}
else if (result == "failure") {
document.getElementById("errormsg").innerHTML = xmlhttp.responseText;
return false;
}
}
}
Your callback function is actually returning value (true/false) to onreadystatechange but not to your validation function. Your validation function simply returning true to your form submit event and that's why you anyway make it navigate/submit to next page...
You should call form.submit from your callback function itself on success result, you just need to retrieve form element object in your callback. And add "return false" in 'onSubmit' to avoid form getting submitted automatically.
Hope you understood the problem.
So I have this program in which the user enters a city and a country. The program looks in the database to see if the city doesn't already exists, if it does I show a warning message using ajax, if not i add the city to the database.
This is the form:
<form action="addCity.php" method="get" onsubmit="return validateCityInfoForm();">
onsumbit I call the javascript function validateCityInfoForm() that looks like this:
function validateCityInfoForm() {
var xmlhttp;
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)
{
if (xmlhttp.responseText == "true") {
document.getElementById("checkIfCityExistsWarning").style.display = "block";
document.getElementById("checkIfCityExistsWarning").innerHTML = "This city already exists!";
return false;
}
}
}
xmlhttp.open("GET", "checkIfCityExists.php?city=" + cityInput + "&country=" + countryInput, true);
xmlhttp.send();
}
checkIfCityExists.php echoes "true" if the city already exists in the database and "false" otherwise.
The problem is that it always adds the city in the db even though the city already exists.
checkIfCityExists.php returns "true" but it doesn't seem to matter.
I really don't know what the problem is, any help would be greatly appreciated.
Thanks!
here is checkIfCityExists.php:
<?php
include ('database_connection.php');
$city = mysqli_real_escape_string($dbc, $_GET['city']);
$country = mysqli_real_escape_string($dbc, $_GET['country']);
//check if the city and country already exists in the database
$query_verify = "SELECT * FROM city WHERE name = '$city' AND country = '$country'";
$result_verify = mysqli_query($dbc, $query_verify);
if(mysqli_num_rows($result_verify) == 0) { //if the city does not appear in the database
echo "false";
}
else {
echo "true";
}
?>
You are trying to make an asynchronous call to do validation. By the time the call comes back it is too late because the form already is submitted.
Tha Ajax call does not pause the code execution, it makes the call and the rest of the code happens.
What you would need to do it break it up into two steps, make the Ajax call and when the onreadystatechange comes back, submit the form.
The problem is, your onsubmit has no return.
So validateCityInfoForm() returns undefined which does not prevent the Browser from executing the action. validateCityInfoForm() should return false to prevent the Browser from submitting the form. And then in the onreadystatechange call form.submit() if necessary.
There's a form users fill out and click the submit button. The data gets sent back to the server and based on the servers server's response the form is submitted or not (and the page is redirected or not). The problem is the form always submits and the page redirects before the server's response is received.
function SubmitForm(name, data1)
{
var result;
var checkResult = function(result)
{
alert("final value is: "+result)
return result
}
var xmlhttp
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)
{
if(xmlhttp.responseText)
{
result = true
}
else
{
document.getElementById("report").innerHTML = "blah blah blah"
result = false
}
checkResult(result)
}
}
xmlhttp.open("POST", "Checkdata1.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send("name="+encodeURIComponent(name.value)+"&data1="+encodeURIComponent(data1.value))
//return false
}
Here's the HTML for the form that calls the above JavaScript function.
<form onsubmit="return isPasswordCorrect(document.getElementById('name'), document.getElementById('txtField1'))" action="nextpage.php" method="GET">
I know the idea is for the function to return false to prevent the form from being submitted, but how do I get it to wait long enough for the server to reply through Ajax? By the way, I haven't needed JQuery and if it's not necessary I'd prefer not to start using it now.
I would use a <button> that doesn't submit the form (the type isn't "submit"):
<form ...>
...
<button onclick="SubmitForm(...)">Submit</button>
</form>
Then at the end of SubmitForm, you can put:
document.querySelector("form").submit();
When you want to submit the form.
I want to add html variables : "<script>var var1 = new CalendarPopup();</script>" according to a number that the user chooses. At the moment I have an ajax setup that is suppose to change my tag to add the variables by changing the inner html like so :
<div id="calVar">
<script>
var cal1 = new CalendarPopup();
var cal2 = new CalendarPopup();
</script>
</div>
function addRespDropDownAjax(currentNumberOfDropDown)
{
//Prepare a new ajaxRequest.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//Ajax receiving the response in this function
xmlhttp.onreadystatechange = function()
{
//state 4 is response ready.
//Status 200 is page found.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('calVar').innerHTML = '<script>var cal3 = new CalendarPopup();</script>';
alert(document.getElementById('calVar').innerHTML);
}
};
//Send the Ajax request.
xmlhttp.open('GET','mainServlet?command=ajax.AddRespDropDown&NUMBER_OF_DROP_DOWN=' + currentNumberOfDropDown, true);
xmlhttp.send();
}
The last alert :document.getElementById('calVar').innerHTML return nothing and my varaibles are not created. any ideas?
Thanks alot!!
HTML doesn't have variables, and any that are defined in a <script> without deeper nested scope can be simple defined off the window object.
Instead of trying to insert HTML, just use:
window.cal3 = new CalendarPopup();
then any other script can access this variable now or later.
I've got a client side js/ajax script like this:
<p>server time is: <strong id="stime">Please wait...</strong></p>
<script>
function updateAjax() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==3 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
}
if (xmlhttp.readyState==4) {
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
}
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
window.setTimeout("updateAjax();",100);
</script>
And a on the server side:
<?php
echo 6;
for ($i=0; $i<10; $i++) {
echo $i;
ob_flush(); flush();
sleep(1);
}
?>
After first 'open' and 'send' it works ok, but when the server finishes the script and xmlhttp.readyState == 4 then the xmlhttp resends the request but nothing happens.
Instead of re-using the same XHR object all the time, try repeating the function with a new object. This should at least fix incompatibility issues as you listed.
Try re-calling your Ajax function inside the callback of it, if you want to loop it infinitely.
if (xmlhttp.readyState==4) {
updateAjax(); //or setTimeout("updateAjax();",100); if you want a delay
}
I'd also suggest putting your .innerHTML method inside the .readyState==4, which is when the requested document has completely loaded, and .status==200 which means success. Like this:
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
updateAjax(); //or setTimeout("updateAjax();",100);
}
Also, if you want your Ajax to be cross-browser, you should test if the browser supports the XHR object which you're using:
var xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
I just typed the code above but it should work just fine to add compatibility with older versions of IE and other browsers.