Getting value from ajax calling using xmlhttp request - javascript

I am making a request using post method. I am not able to find the value of response text. May be i lack the knowledge on how to get the response text. If a data exist in a database i am trying to tell the user that he is able to post the data otherwise he will get an alert that he need to change the name.
Here is my ajax call:-
function checkAddedNew(univ_name,term_no,dept_name,uid,year)
{
var getName=document.getElementById("add_new_name").value;
var getTitle=document.getElementById("add_new_title").value;
var hasSpace=getTitle.indexOf(' ');
if(hasSpace >= 0)
{
alert("Please fill up the title without space");
}
else
{
if(getName&& getTitle)
{
var r=confirm("Do you want to add?");
}
else if(!getName && getTitle)
{
alert("Please fill up the name");
}
else if(getName && !getTitle)
{
alert("Please fill up the title");
}
else
{
alert("Please fill up the form.");
}
if (r==true )
{
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)
{
alert(http.responseText);
location.reload();
}
}
xmlhttp.open("POST","../addnew/check",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("title="+getTitle+"&name="+getCourseName+"&name="+univ_name+"&term_no="+term_no+"&department_name="+dept_name+"&uid="+uid+"&year="+year);
}
}
}
and i am here getting the response xmlhttp.readyState==4 && xmlhttp.status==200 .And here is my controller :-
function check()
{
$title = $this->input->post('title');
$name=$this->input->post('name');
$university_name=$this->input->post('university_name');
$term_no=$this->input->post('term_no');
$department_name=$this->input->post('department_name');
$uid = $this->input->post('uid');
$year=$this->input->post('year');
$CI =& get_instance();
$log_username=$CI->session->userdata('username');
$now = time();
$human = unix_to_human($now);
$this->load->model('model');
$isUnique=$this->model->checkNew($name,$title,$log_username,$human,$term_no,$university_name,$year,$department_name,$uid);
if($isUnique)
{
$this->course_model->insertNewCourse($course_name,$course_title,$log_username,$human,$term_no,$university_name,$year,$department_name,$uid);
}
}

The variable http is not defined, it should be xmlhttp
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
//or
//alert(this.responseText);
location.reload();
}
}

You have alert(http.responseText); but you never define http. Your object is called xmlhttp.

Related

Get string from javascript on the same page

Problem is that i have dynamic changing script for mysql query
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
I need to get str from this code to php.
from the html point of view i get string from
<select name="users" onchange="showUser(this.value)">
adn in the other file getuser.php I have
$q = $_GET['q'];
$sql="SELECT * FROM articles WHERE type = '".$q."'";
The biggest problem is that i put onchange this parameters so i can get values to my page without refreshing it. But now i cant get value from combobox to php.
How can i do this ???
Thanks in advance

Cannot click on the content which is loaded through ajax function

Currently, I cannot load the second content using ajax. Actually, I have loaded the first content using ajax. In order to go to the second content, i need to call the ajax function but after i click to load the second content using ajax it does not work. I have checked my code, its working fine if i directly call the second ajax function, unless i call the first ajax function after that the ajax is not working again. Are there any ways to solve this problem.
This is the first ajax code:
function showMusic(str) {
if (str == "") {
document.getElementById("albums").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("albums").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAlbums.php?q="+str,true);
xmlhttp.send();
}
}
The above function works. The above function is at another php file
This is the second ajax code:
$(document).ready(function(){
function showArtistDetails(str) {
if (str == "") {
alert("hi");
document.getElementById("artist").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
alert("hi1");
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
alert("hi2");
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("artist").innerHTML = xmlhttp.responseText;
alert("hi3");
}
};
xmlhttp.open("GET","getArtist.php?title="+str,true);
alert("hi4");
xmlhttp.send();
alert("hi5");
}
}
$("#clickme").click(showArtistDetails);
});
This is the php code which is at another php file:
echo "<td id=\"clickme\">" . $row['CDTitle'] . "</td>";
I have been trying to solve this for the past 2 days but i am unable to solve it. Some are saying its a bug. But i really i dont know what causes this problem. Thanks in advance.

how to compare ajax response text with some string without jQuery

I am trying to get a value back through if it found value in database sends/echo result value in it does found sends back/echo 'not_found'.
When I try to compare in the following script it always goes inside if, and never goes to else.
I also tried NULL, FALSE instead not_found does not work.
function showHint(str) {
var xmlhttp;
var url= "check_album.php?q="+str;
document.getElementById("txtHint1").innerHTML=(url);
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.readyState.responseText !='not_found') {
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
} else {
document.getElementById("txtHint3").innerHTML='no result';}
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
and this is check_album.php code which sending result back
require_once('../php/classes/class.add_album.php');
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$album_name = $_GET["q"];
//make new object
$objfile = new add_album();
//call object method with post method value we got and save result in result
$file_found=$objfile->find_album($album_name);
if ($file_found)echo $file_found;
else echo 'not_found';
}
Try this.
if(xmlhttp.responseText !='not_found' ){
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
} else
{
document.getElementById("txtHint3").innerHTML='no result';
}
This is because response text may have unwanted spaces Try to trim that response
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
if(xmlhttp.responseText.trim() !='not_found' ){
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
}else{
document.getElementById("txtHint3").innerHTML='no result';
}

Using Ajax to pass Json variable and decode

I have a AJAX script which i was using previously and was able to retrieve data from viewCommentsJson.php as such[{"comments":"Greta"},{"comments":"John"}]. I was wondering if its able to decode the return value such that it display it properly ?
Thanks in advance
Greta John
Main.php
<a onclick="showUser('.$row['ID'].')" method = "POST" action= "viewCommentsJson.php">Show Comments</a>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("Post","viewCommentsJson.php?q="+str,true);
xmlhttp.send();
}
</script>
viewCommentsJson.php
$com = $_REQUEST["q"];
include 'connectDatabase.php';
//opening sql table
$selected = mysql_select_db("2000",$dbhandle)
or die("Could not select 2000");
$arr = array();
$data = mysql_query("SELECT comments FROM comment WHERE ID = '$com'");
$rows = array();
while($r = mysql_fetch_assoc($data)) {
$rows[] = $r;
}
print json_encode($rows);
Since you don't mind a jQuery solution, here is how it can be done
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
$.ajax({
type:'post',
url: 'viewCommentsJson.php',
data:{q:str},
success:function(data)
{
data = $.parseJSON(data);
var response;
$.each(data, function(index, value){
response += value+'<br />';
});
$('#txtHint').html(response);
}
});
}
You can refer $.ajax and $.parseJSON for more information.
Note: Your SELECT comments FROM comment WHERE ID = '$com' is prone to SQL injection. At the very least, you should sanitize all incoming data before using it in your query directly.
<a onclick="showUser('1')" href="#?">Show Comments</a>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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) {
data = eval(xmlhttp.responseText);
for(i=0;i<data.length;i++){
document.getElementById("txtHint").innerHTML = document.getElementById("txtHint").innerHTML + data[i].comments;
}
}
}
xmlhttp.open("Post","viewCommentsJson.php?q="+str,true);
xmlhttp.send();
}
</script>
<div id="txtHint"></div>
First of all remove method and action from A tag and used above code now. Removed some typos

Javascript XmlHttpRequest bad connection

I keep running the following code but keep getting the "Bad connection" alert pop up, meaning I didn't get a successful response code.
Does anyone see anything wrong with the following script?
function process(){
URL = document.getElementById("userInput").value;
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) {
document.getElementById("Response").innerHTML=xmlhttp.responseText;
alert("Successful connection!");
}
else {
alert("Bad connection!");
}
}
xmlhttp.open("GET", URL, true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
The readyState passes through a number of other states (opened, sent, headers received, loading) before reaching state 4 (done). Each time the event fires, you'll get the Bad Connection alert until it is successful.
You probably want something more like:
if (xmlhttp.readyState==4) {
if (xmlhttp.status==200) {
document.getElementById("Response").innerHTML=xmlhttp.responseText;
alert("Successful connection!");
} else {
alert("HTTP error: " + xmlhttp.status);
}
}

Categories

Resources