Using Ajax to pass Json variable and decode - javascript

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

Related

Onchange stops display in Datalist

<?php
//connect to database
$conn = mysqli_connect("localhost", "root", "", "inventory");
if(mysqli_connect_errno($conn)) {
echo "Unable to connect to database server";
}
//query database for items to populate
$sql = "SELECT ITEM_NAME, ITEM_ID FROM item";
$query = mysqli_query($conn, $sql);
echo '<input type="text" id="item1" list="itemname1"/>';
echo '<datalist id="itemname1" name="itemr1" onchange="showitem1(this.value); showecost1(this.value); showuom1(this.value);">'; //change select to datalist
echo '<option value="">Select item</option>';
while($selectedItem = mysqli_fetch_assoc($query)) {
echo "<option value='".$selectedItem['ITEM_NAME']."'>{$selectedItem['ITEM_ID']}</option>";
}
echo '</datalist>'; //change select to datalist
if (isset ($_POST['submit'])) {
$selectedItem = $_POST['desc1'];
}
?>
I have this codes to call the data from the database and display it to the datalist, but the problem is that the onchange event is not working, it supposedly display automatically the other data by choosing a data from the datalist. It is working if I'm just using select tag, but I want to use the datalist, so that the user can input data that is not in the database.
Here is the JS Code:
<script>
function showitem1(str) {
if (str=="") {
document.getElementById("desc1").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("desc1").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?a="+str,true);
xmlhttp.send();
}
function showecost1(str) {
if (str=="") {
document.getElementById("ecost1").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp1=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4 && xmlhttp1.status==200) {
document.getElementById("ecost1").innerHTML=xmlhttp1.responseText;
}
}
xmlhttp1.open("GET","gethint1.php?b="+str,true);
xmlhttp1.send();
}
function showuom1(str) {
if (str=="") {
document.getElementById("uom1").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function() {
if (xmlhttp2.readyState==4 && xmlhttp2.status==200) {
document.getElementById("uom1").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","gethint2.php?c="+str,true);
xmlhttp2.send();
}
</script>
you can use input event
$(document).on('change', 'input', function(){
var options = $('datalist')[0].options;
var val = $(this).val();
for (var i=0;i<options.length;i++){
if (options[i].value === val) {
alert(val);
break;
}
}
});
input event has better support than datalist element, there is indeed no reason to not use it if you are already using datalist element.

Ajax returning blank response

I'm working on a simple script where I just want to see request and response that is sent to server and then recieved at client via Ajax. The server is always returning Status 500. What am I doing wrong?
Below is my script.
Javascript:
<script>
function loginJs()
{
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.open("GET","http://my-website.com/ajax_exp.php",true);
xmlhttp.onreadystatechange=function()
{
alert("State "+xmlhttp.readyState+" Status "+xmlhttp.status);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
}
</script>
ajax_exp.php
<?php
header('Access-Control-Allow-Origin: http://my-website.com/ajax_exp.php');
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action()
{
$username = 'username';
$password = 'password';
echo $username;
die();
}
?>
1) try removing
header('Access-Control-Allow-Origin: http://my-website.com/ajax_exp.php');
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
replacing with
my_action();
You can easily trace the error;
2) Check console log for any javascript errors.
Path is the problem provide your server path ajax/ajax_exp.php
<script>
function loginJs()
{
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.open("GET","ajax/ajax_exp.php",true);
xmlhttp.onreadystatechange=function()
{
alert("State "+xmlhttp.readyState+" Status "+xmlhttp.status);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
}
</script>
If anyone else is having the same issue, this is what I did and now it works!
Javascript
Replaced xmlhttp.send(); with xmlhttp.send(null);
PHP
<?php
$username = "user";
$password = "password";
print $username;
?>

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';
}

Getting value from ajax calling using xmlhttp request

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.

sending data to php with ajax.send

Can someone help me with sending this data to a .php page where I could receive it on my PHP page
javascript:
postToSql(){
var ajax;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
alert(ajax.responseText); //receiving response
}
};
var name = $("#entry_1274804157").val();
//alert(name);
var company= $("#entry_1828184698").val();
var phone=$("#entry_2039177352").val();
var email=$("#entry_1545475878").val();
var comments=$("#entry_1846523632").val();
var params = {
"name":name,
"company":company,
"phone":phone,
"email":email,
"comments": comments
};
//var jsonText = JSON.stringify(params);
ajax.open("POST", "view/templates/includes/insertgoogle.php", false);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send("totalJsonStr="+params);
//alert(totalJsonStr);
// alert(params);
return true;
}
</script>
HTML:
<form action="https://docs.google.com/asgsasdfasg/formResponse" method="POST" id="" target="_self" onsubmit="return postToSql();">
EDIT:
This is how I am receiving it:
if(isset($_POST['totalJsonStr']))
{
$jsonVal = json_decode($_POST['totalJsonStr']);
$jsonVal2 = json_decode($jsonVal);
var_dump($_POST['totalJsonStr']);
var_dump($jsonVal);
var_dump($jsonVal2);
$name = $jsonVal2->{'name'};
$company= $jsonVal2->{'name'};
$phone= $jsonVal2->{'name'};
$email= $jsonVal2->{'name'};
$comments= $jsonVal2->{'name'};
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
mysql_query("INSERT INTO `testgoogle` ( Name, Company, Phone, Email, Comments )
VALUES ('$name','$company', '$phone', '$email', '$comments')");
Print "Your information has been successfully added to the database.";
return;
}
else
{
die("No Data Found");
}
Where do you create the "ajax" object?
var ajax;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
from here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp
If you want to use $_GET then,
Remove:
ajax.open("POST", "view/templates/includes/insertgoogle.php", true);
Add:
ajax.open("GET", "view/templates/includes/insertgoogle.php", true);
Helpful link: http://www.degraeve.com/reference/simple-ajax-example.php
Using POST Method,
The perfect solution would be, store all values in an array and send the array as a json request using json.stringify().
In php, Use json_decode() to decode your json string.
UPDATE
Add this to your javascript,
<script type="text/javascript">
function postToSql(){
var ajax;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
alert(ajax.responseText); //receiving response
}
}
var name = "1234";
var company= "1234";
var phone="1234";
var params = {
"name":name,
"company":company,
"phone":phone,
};
var jsonText = JSON.stringify(params);
ajax.open("POST", "view/templates/includes/insertgoogle.php", true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send("totalJsonStr="+jsonText);
}
</script>
<form action="https://docs.google.com/asgsasdfasg/formResponse" method="POST" id="" target="_self" onsubmit="postToSql();return false;">
Add this to php
<?php
if(isset($_POST["totalJsonStr"]))
{
$jsonVal = json_decode($_POST["totalJsonStr"]);
print $jsonVal->{'name'};
print $jsonVal->{'company'};
print $jsonVal->{'phone'};
}
else
{
die("No Data Found");
}
?>
since nothing was working for me, I finally used jquery ajax which worked.

Categories

Resources