ajax function not working fine - javascript

I have a text field in which i am getting a string like that
say name / contact / address
and i get this value on button click function when i pass this value to php function via ajax. it returns nothing, i don't know what is wrong with my code.
here is the ajax function:
$("#load").click(function()
{
//alert("this comes in this");
var data1 = $("#country_id").val();
$.ajax({
alert("ajax start");
url: 'ajax_submit.php',
type: 'Post',
dataType: 'json',
data:{getRespondents:"getRespondents", data:data1},
success: function(e){
alert(e);
$("#rCategory").val(e.respondents[0]['category']);
$("#gender").val(e.respondents[0]['gender']);
$("#rAddress").val(e.respondents[0]['address']);
$("#rContact").val(e.respondents[0]['contact']);
alert("In this");
}
});
});
and in ajax_submit.php function is like that:
if($_POST["getRespondents"] == "getRespondents"){
$regionID= $_POST["data"];
$obj = new controller();
$result = $obj->getRespondents($regionID);
$json = array("respondents"=>$result);
echo json_encode($json);
exit();
}
In class function is written as:
function getRespondents($a){
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("demon", $connection); // Selecting Database
list($number1, $number2, $number3) = explode('/', $a);
//$sql = "SELECT r.id, r.name, r.contact, r.address from respondent as r ORDER BY r.name";
$sql = "SELECT * FROM respondent as r WHERE r.name = '".$number1."' and r.contact = '".$number2."' and r.address = '".$number3."' "
$rsd = mysql_query($sql);
$row= array();
$i=0;
while($rs = mysql_fetch_array($rsd)) {
$row[$i]["id"] = $rs ['id'];
$row[$i]["name"] = $rs ['name'];
$row[$i]["contact"] = $rs ['contact'];
$row[$i]["address"] = $rs ['address'];
$row[$i]["category"] = $rs ['category'];
$row[$i]["gender"] = $rs ['gender'];
$i++;
}
return $row;
}
I want to populate those values in given select boxes when user selects something from autocomplete function.
what are possible soultions to this problem? thanks

First of all why you use alert at the beginning of ajax? remove that alert because it might give you JavaScript error.

Related

I want to update value from DB. but my code won't work

Main
public function update_sample(){
$id3 = sanitize($this->input->post('id3'));
$sample3 = sanitize($this->input->post('sample3'));
if($this->session->userdata('position_id') != ""){
$username = $this->model->get_users($this->session->userdata('user_id'))->row()->username;
$query = $this->model->update_sample($data);
$data = array(
"success" => 1,
"message" => 'Note: You have successfully updated');
}else{
$this->logout();
}
generate_json($data);
}
model
public function update_sample($sample){
$sql = "UPDATE test SET sample=? WHERE id=? AND enabled= 1";
$data = array($sample);
return $this->db->query($sql, $data);
}
js
$("#table-grid").delegate(".btnUpdate", "click", function(){
var id = $(this).data('value');
$.ajax({
type: 'post',
url: base_url+'Main/view_details',
data: {'id3': id},
success: function(data){
var res1 = data.result1;
if(data.success==1){
document.getElementById("sample3").value = res1[0].samples;
$('#update').modal();
}
}
});
});
I want to update Data from database I've been stuck here for long.
I don't know how your class is created, but it looks like your function only returns true for query execution, you'll need to check for "affected_rows".
Try the code below, with a little luck it may work, otherwise you have to check the $result variable and modify the code corresponding to the result.
public function update_sample($sample){
$sql = "UPDATE test SET sample=? WHERE id=? AND enabled= 1";
$data = array($sample);
$result = $this->db->query($sql, $data);
return $result && $result->affected_rows > 0 ? true : false;
}

How to get an value from a php page with js

I am trying to capture a value that is calculated on a PHP page called "classes_day.php" at the same time as I pass a value per GET, "? Day = YYYY-mm-dd" to it. How do I do this with JS or JQuery?
<?php
// aulas_dia.php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT * FROM `task` WHERE `dia` LIKE ".$data."";
$result = mysqli_query($link,$query);
$soma = 0;
while ($row = mysqli_fetch_assoc($result)) {
$soma = $soma+$row['duration'];
}
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
?>
I already tried using an iframe and contentwindow, but iframe gets the value and the contentwindow is empty (weird isn't it?).
Following Barmar's tip, I'm using $ .get, but I don't know why this loop is not working, can anyone help me?
for (i = 0; i < num_days; i++) {
x = (first_day+i)%7;
y = (first_day+i-x)/7;
h_dia(String(y)+String(x),i+1);
data_c = ano+"-"+mes+"-"+String(i+1);
$.get("aulas_dia.php?data="+data_c, function(data){
console.log(String(y)+String(x)+" - "+data_c+" - "+data);
set_aulas_fun(String(y)+String(x),data);
});
}
Use $.get() to send an AJAX request.
$.get("classes_day.php?data=YYYY-MM-DD", function(response) {
console.log(response);
});
BTW, you can add up all the durations in the SQL query instead of using a PHP loop. And you should use a prepared statement to prevent SQL injection.
<?php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT SUM(duration) AS total FROM `task` WHERE `dia` LIKE ?";
$stmt = $link->prepare($query);
$stmt->bind_param("s", $data);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$soma = $row['total'];
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}

Ajax database insert isnt working

I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}

Ajax Javascript Get JSON value

Hi I am developing an app in phonegap, where I am getting a particular value from server by connecting php file the value I need to pass is a string value 'pmnno'suppose whose value is '2' I need to get the value of '2' in column name 'personalnumber'.. So I am giving my code below
var jsonData;
$.ajax({
type: 'GET',
url: 'http://xxxx.com/app/get_pday1_number.php',
data: { pmnno: '2' },
dataType: 'html',
success: function (response) {
jsonData = response;
alert(jsonData);
}
});
php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pone"]))
{
$pone = $_GET['pone'];
// get a product from products table
$result = mysql_query("SELECT *FROM pdaynew WHERE pone = $pone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pone"] = $result["pone"];
$product["personaldayone"] = $result["personaldayone"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am getting a success mesage that means connection is succesful but ineed the value of '2' in column 'personalnumber' for that where I need to add that code..If anyone knows pls help me...
Instead of using * use personaldayone:
$result = mysql_query("SELECT personaldayone FROM pdaynew WHERE pone = $pone");

ajax cannot pass datastring to php

I can't receive the data value on my php script, the ajax success fires but the data on my database is not changed when I send this.
$.ajax({
type: "POST",
url: "database/clientpanel/agent_panel/notiffolder/notifedit.php",
data: {
email: email,
number: number,
emailon: emailon,
texton: texton,
email_delay: emaildel,
ext_delay: textdel,
timezone1: zone1,
timezone2: zone2
},
cache: false,
success: function(html){
$("#upnotif").show();
$("#errnotif").hide();
$("#errnotif1").hide();
$("#errnotif2").hide();
}
});
php
<?php
session_start();
include("../../../dbinfo.inc.php");
$query=" select * from tele_panel_notification where client='".$mysqli->real_escape_string($_SESSION['clientid'])."'";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$client = $row['client'];
if($client == ""){
$query = "insert into tele_panel_notification set
emailon = '".$mysqli->real_escape_string($_POST['emailon'])."',
texton = '".$mysqli->real_escape_string($_POST['texton'])."',
timezone = '".$mysqli->real_escape_string($_POST['timezone'])."',
timezone2 = '".$mysqli->real_escape_string($_POST['timezone2'])."',
email = '".$mysqli->real_escape_string($_POST['email'])."',
email_delay = '".$mysqli->real_escape_string($_POST['email_delay'])."',
text_delay = '".$mysqli->real_escape_string($_POST['text_delay'])."',
number = '".$mysqli->real_escape_string($_POST['number'])."',
client='".$mysqli->real_escape_string($_SESSION['clientid'])."'";
//execute the query
if( $mysqli->query($query) ) {
//if saving success
echo "true";
}else{
//if unable to create new record
printf("Errormessage: %s\n", $mysqli->error);
}
}
else{
$query = "UPDATE tele_panel_note SET
emailon = '".$mysqli->real_escape_string($_POST['emailon'])."',
texton = '".$mysqli->real_escape_string($_POST['texton'])."',
timezone = '".$mysqli->real_escape_string($_POST['timezone'])."',
timezone2 = '".$mysqli->real_escape_string($_POST['timezone2'])."',
email = '".$mysqli->real_escape_string($_POST['email'])."',
email_delay = '".$mysqli->real_escape_string($_POST['email_delay'])."',
text_delay = '".$mysqli->real_escape_string($_POST['text_delay'])."',
number = '".$mysqli->real_escape_string($_POST['number'])."'
where client='".$mysqli->real_escape_string($_SESSION['clientid'])."'";
//execute the query
if( $mysqli->query($query) ) {
//if saving success
echo "true";
}else{
//if unable to create new record
printf("Errormessage: %s\n", $mysqli->error);
}
}
//close database connection
$mysqli->close();
?>
Take a look at your PHP part,
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$client = $row['client'];
if($client == ""){
You should verify directly with your row if you want to be able to know if the row already exists:
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
//$client = $row['client'];
if(!$row){
And then your client variable is useless.

Categories

Resources