AJAX not working (call php and get the result back) - javascript

I am trying to make a checkbox calls php code then get back the results to be printed in textarea.
Now, the problem is that the php file doesn't print the result on the textarea or maybe the Ajax not working. I am sure that there is nothing wrong with MySQL code.
this is form.php code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var checkbox = document.getElementById('subscribers').checked;
//Check if checkbox is checked
if (checkbox === true) {
//Read databank for Results
document.getElementById("to").value = "result should be here.";
$.ajax({
type: 'POST',
url: 'sms/readSubscriber.php',
data: {'variable': dataPhp},
complete: function(r){
var subscriberNumbers = r.responseText;
document.getElementById('to').innerHTML = subscriberNumbers;
}
});
} else {
document.getElementById("to").value = "";
}
});
function doalert() {
//Check if checkbox is checked
var checkboxElem = document.getElementById("subscribers").checked;
if (checkboxElem === true) {
//Read databank for Results
document.getElementById("to").value = "result should be here.";
$.ajax({
type: 'POST',
url: 'sms/readSubscriber.php',
data: {'variable': dataPhp},
complete: function(r){
var subscriberNumbers = r.responseText;
document.getElementById('to').innerHTML = subscriberNumbers;
}
});
} else {
document.getElementById("to").value = "";
}
}
</script>
</head>
<body>
<fieldset style="width:50%;margin:auto" dir=ltr>
<form action="" method="POST">
<table border="0" cellspacing="3" cellpadding="3">
<tr>
<td>Your Balance</td>
<td><input type="text" class="form-control" name="Balance" size="20" disabled="disabled" value="<?php
echo $Credits;
?>"></td>
</tr>
<tr>
<td>Mobile No.</td>
<td><textarea textarea class="form-control" id="to" name="Mobile" cols="30" rows="5"></textarea><br></td>
<td>
<div class="checkbox">
<label><input type="checkbox" value="subscribers" onchange="doalert()" id="subscribers" checked>Subscribers</label>
</div>
</td>
</tr>
<tr>
<td>Message</td>
<td><textarea class="form-control" name="Text" cols="30" rows="5" required></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Go" value="Send SMS" /></td>
</tr>
</table>
</form>
</fieldset>
</body>
</html>
and this is the readSubscriber.php
<?php
require_once('../db_functions.php');
// Connect to the database
$connection = db_connect();
//if connection fails, stop script execution
if (mysqli_connect_errno()) {
echo "Error: " . $sql . "Connect failed: " . mysqli_connect_error();
} else {
$query = "SELECT * FROM phoneSubscribers";
// Query the database
$result = db_isExist($query);
if ($result) {
$result = db_fetch($query);
echo json_encode($result);
} else {
echo "No result";
}
}
?>

Set value of the textArea (instead of innerHTML)

Change like this. It will works. You cannot replace variable ('variable') as value
And You need to declare variable with value.
<script>
function doalert() {
var checkboxElem = document.getElementById("subscribers").checked;
if (checkboxElem === true) {
//Read databank for Results
document.getElementById("to").value = "result should be here.";
var dataPhp = '';
$.ajax({
type: 'POST',
url: 'sms/readSubscriber.php',
data: {variable: dataPhp},
success : function(r){
var subscriberNumbers = r.responseText;
document.getElementById('to').innerHTML = subscriberNumbers;
}
});
} else {
document.getElementById("to").value = "";
}
}
</script>

It done as I want
in my form:
$(document).ready(function() {
var checkboxElem = document.getElementById("subscribers").checked;
if (checkboxElem === true) {
//Read databank for Results
var resp = $("#response");
$.ajax({
type: 'POST',
url: 'assets/php/readSubscriber.php',
success: function(data) {
document.getElementById('to').value = data;
}
});
} else {
document.getElementById("to").value = "";
}
});
function doalert() {
var checkboxElem = document.getElementById("subscribers").checked;
if (checkboxElem === true) {
//Read databank for Results
var resp = $("#response");
$.ajax({
type: 'POST',
url: 'assets/php/readSubscriber.php',
success: function(data) {
document.getElementById('to').value = data;
}
});
} else {
document.getElementById("to").value = "";
}
}
in the called php file:
<?php
require_once('db_functions.php');
// Connect to the database
$connection = db_connect();
//if connection fails, stop script execution
if (mysqli_connect_errno()) {
echo "Error: " . $sql . "Connect failed: " . mysqli_connect_error();
} else {
$query = "SELECT * FROM phoneSubscribers";
// Query the database
$result = db_isExist($query);
if ($result) {
$result = db_fetch($query);
$jsonData = array();
while ($row = $result->fetch_assoc()) {
$jsonData[] = $row['phone'];
}
array_walk_recursive($jsonData, function($key, $value)
{
echo $key . ', ';
});
} else {
}
}
?>

Related

ajax in codeigniter showing only false message even when the value exist in database

I am trying to check if value exist in database in my CodeIgniter website using AJAAX. I have written the following code:
<input id="username" name="pincode" type="text" class="form-control" placeholder="Enter Pincode">
<input id="prodid" name="prodid" value="<?php echo $prodid;?>" type="hidden">
<button type="button" onclick="check_if_exists();" class="btn btn-primary">Check</button>
function check_if_exists() {
var username = $("#username").val();
var prodid = $("#prodid").val();
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>index.php/homecontroller/filename_exists",
data: {
username: username,
prodid: prodid
},
success: function(response) {
if (response == true) {
$('#msg').html('<span style="color: green;">' + msg + "</span>");
} else {
$('#msg').html('<span style="color:red;">Delivery Not Available at ' + username + '</span>');
}
}
});
}
function filename_exists()
{
$username = $this->input->post('pincode');
$prodid = $this->input->post('prodid');
$exists = $this->product->filename_exists($prodid);
if ($exists) {
return true;
} else {
return false;
}
}
function filename_exists($prodid)
{
$this->db->select('*');
$this->db->where('id', $prodid);
$this->db->from('product');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
I am only getting the message that the value doesn't exist even if the value is there in database.
You are using AJAX not the form submission method, so in back-end post() method won't work
To transfer a value from server in php, one method is echo, but return is wrong here.
Please rewrite your code like this
View
function check_if_exists() {
var username = $("#username").val();
var prodid = $("#prodid").val();
var transfer = [username,prodid];
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>index.php/homecontroller/filename_exists",
data: {result: JSON.stringify(transfer)},
success: function(response) {
if (response) {
$('#msg').html('<span style="color: green;">' + msg + "</span>");
} else {
$('#msg').html('<span style="color:red;">Delivery Not Available at ' + username + '</span>');
}
}
});
}
Controller
function filename_exists()
{
$post = json_decode($_POST['result']);
$username = $post[0];
$prodid = $post[1];
$exists = $this->product->filename_exists($prodid);
echo $exists;
}
Modal
function filename_exists($prodid)
{
$this->db->select('id');
$this->db->where('id', $prodid);
$this->db->from('product');
$query = $this->db->get();
if($query->num_rows()) return true;
}
enter code here

How to autofill city name by giving pin code using javascript and php?

I am not able to autofill city by giving pincode even though database connection successfull.
Below is the code:
pin.php
<body>
<form>
<label >Pincode </label>
<input type="text" class="form-control" placeholder="Enter Pin Code" name="pin_value" id="pin" maxlength="6" pattern=".{6,6}" title="Exacty 6 digits" onkeypress="return isNumberKey(event)" onkeypress="set_city()" required="">
<label >City </label>
<input type="text" class="form-control" placeholder="Enter City" name="city_value" id="city" onkeypress="return isCharacterKey(event)" >
<?php
include("configs.php");
$pin = $_POST['pin'];
$query = $conn->query("SELECT cityname FROM pincodes WHERE pincode = '$pin'");
while($row = $query->fetch_assoc()) {
?>
<option> <?php echo $row["cityname"];?></option>
<?php
}?>
</form>
<script>
function set_city(){
var pin = document.getElementById("pin").value;
$.ajax({
url: "load_pincode.php",
method: "post",
data: {pin: pin},
success: function(response){
if(response == ""){
alert("please enter pincode");
}
else{
$("#city").val(response);
}
}
});
}
</script>
</body>
load_pincode.php
<?php
#ob_start();
session_start();
include("configs.php");
$pin = $_POST['pin'];
if($_POST["pin"])
{
$uid = $_SESSION['user_id'];
$user_type = $_SESSION["user_type"];
if($user_type=="lite"){
$cur_uid = $uid;
$uid = $_SESSION["ad_id"];
}
$cur_bid = $_SESSION["default_business_id"];
$q = $conn->query("SELECT user_pin FROM business WHERE year = '$curr_year' AND user_id = '$uid' AND business_id = '$cur_bid'");
$c;
while($r=$q->fetch_assoc()){
$c = $r["user_pin"];
}
$qg = $conn->query("SELECT cityname FROM pincodes WHERE pincode = '$pin' ");
while($rg = $qg->fetch_assoc()) {
$p = $rg["cityname"];
}
}else{
echo "prob";
}
?>
Its neither displaying error nor output.I am stuck in this auto-filling not able to move further.
How will I get to know whether it is passing value of pin to load_pincode.php ?
I am not going through your whole code but
First of all you are getting the value of city name according to the pincode but not returning it ,
$qg = $conn->query("SELECT cityname FROM pincodes WHERE pincode = '$pin' ");
while($rg = $qg->fetch_assoc()) {
$p = $rg["cityname"];
}
echo json_encode($p); // here getting the city name
You need to return json array of the result and modify the ajax script to display the city. Please see below.
load_pincode.php
<?php
#ob_start();
session_start();
include("configs.php");
$pin = $_POST['pin'];
if($_POST["pin"])
{
$uid = $_SESSION['user_id'];
$user_type = $_SESSION["user_type"];
if($user_type=="lite"){
$cur_uid = $uid;
$uid = $_SESSION["ad_id"];
}
$cur_bid = $_SESSION["default_business_id"];
$q = $conn->query("SELECT user_pin FROM business WHERE year = '$curr_year' AND user_id = '$uid' AND business_id = '$cur_bid'");
$c;
while($r=$q->fetch_assoc()){
$c = $r["user_pin"];
}
$qg = $conn->query("SELECT cityname FROM pincodes WHERE pincode = '$pin' ");
while($rg = $qg->fetch_assoc()) {
$p = $rg["cityname"];
}
echo json_encode(array('city' => $p)); exit();
}else{
echo "prob";
}
?>
-------------------------------------------------
$.ajax({
url: "load_pincode.php",
method: "post",
data: {pin: pin},
success: function(response){
if(response == ""){
alert("please enter pincode");
}
else{
$("#city").val(response.city);
}
}
});

Email Live Checking PHP and Mysql

I have an issue im stuck for 3 days. Im trying to check in DB if the email the user is entering is already registered and avoid registering in duplicate. But this doesn't seem to work fine
here is my code:
This is in the HTML
<script type="text/javascript">
$(document).ready(function() {
$("#cf_email").keyup(function(e) {
var uname = $(this).val();
if (uname == "")
{
$("#msg").html("");
$("#Submit").attr("disabled", true);
}
else
{
$("#msg").html("Verificando, espere...");
$.ajax({
url: "check_availability.php",
data: {Email: uname},
type: "POST",
success: function(data) {
if(data.status == true) {
$("#msg").html('<span class="text-danger">Email ya registrado!</span>');
$("#Submit").attr("disabled", true);
} else {
$("#msg").html('<span class="text-success">Email Disponible para Registrar!</span>');
$("#Submit").attr("disabled", false);
}
}
});
}
});
});
</script>
<right><form id="register" action="contact.php" method="post">
<p><label>E-mail para Registro</label></p>
<input type="text" name="cf_email" id="cf_email" title="Email" class="demoInputBox" placeholder="Email Valido" required><div id="msg" class="form-group"></div>
</form></right>
this is the check_availability.php
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST["cf_email"]) && $_POST['cf_email'] != '')
{
$response = array();
$cfmail = mysqli_real_escape_string($con,$_POST['cf_email']);
$sql = "select Email from Bares where Email='".$cfmail."'";
$res = mysqli_query($con, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'email already exists.';
}
else
{
$response['status'] = true;
$response['msg'] = 'email is available.';
}
echo json_encode($response);
}
?>
it doesn't matter which email i introduce in the textfield because always says its available even if the email is registered already in the database
In your JS you're processing a string, not an object. You need to parse it:
success: function(data) {
dataObj = JSON.parse(data);
if(dataObj.status == true) {
....
This is an Example with mysqli OOP try it will work without Problem:
PHP:
<?php $mysqli=new mysqli($host, $user, $pass, $db); mysqli_set_charset($mysqli,'utf8');
if (!empty($_POST['cf_email'])){
extract($_POST);
$sql=$mysqli->query("select Email from Bares where Email='".$cf_email."'");
if($sql->num_row>0){
$status=1;
}
else{
$status=0;
}
echo $status;
die;}
?>
HTML:
<right>
<form id="register" action="contact.php" method="post">
<p><label>E-mail para Registro</label></p>
<input type="text" name="cf_email" id="cf_email" title="Email" class="demoInputBox" placeholder="Email Valido" required>
<input type="submit" id="submit">
<div id="msg" class="form-group"></div>
</form>
</right>
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#cf_email").keyup(function(e) {
var uname = $(this).val();
if (uname == "") {
$("#msg").html("");
$("#submit").attr('disabled', true);
} else {
$.ajax({
url: "check_availability.php",
data: $(this).serialize(),
type: "POST",
success: function(data) {
if (data == 1) {
$("#msg").html('<span class="text-danger">Email ya registrado!</span>');
$("#submit").attr('disabled', true);
} else {
$("#msg").html('<span class="text-success">Email Disponible para Registrar!</span>');
$("#submit").attr('disabled', false);
}
}
});
}
});
});
</script>

PHP and jQuery insert into MySQL

I am trying to insert data into mySQL using jQuery. The code does not return any error and no any result as well. Please help me to sort this out.
$(document).ready(function() {
$("#submit").click(function() {
var data;
var eid = 101;
data = "eid=" + eid;
for (i = 0; i <= 10; i++) {
data += "&Text_" + (i + 1) + "=" + $("#Text_" + (i + 1)).val();
data += "&Amount_" + (i + 1) + "=" + $("#Amount_" + (i + 1)).val();
}
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: data,
dataType: "json",
success: function(response) {
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
<tr>
<td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td>
<td><input type="text" value="1001.00" name="Amount[]" id="Amount_1" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td>
<td><input type="text" value="1002.00" name="Amount[]" id="Amount_2" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td>
<td><input type="text" value="1003.00" name="Amount[]" id="Amount_3" /></td>
</tr>
I am adding the process.php snippet also in order to know where is the error.
process.php
$eid=$_POST['eid'];
$length = sizeof($_POST["Text"]);
$i=1;
while ($i<=$length){
if(!empty($_POST['Text'][$i])) {
$Text = $_POST['Text'][$i];
$Amount = $_POST['Amount'][$i];
$msg = array('status' => !$error, 'msg' => 'Failed! updation-1');
if(!$error) {
$sql = "UPDATE TblCustom SET Text='" . $Text . "', Amount='" . $Amount ."' WHERE ID='$eid'";
$status = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$msg = array('error' => $error, 'msg' => 'Success! updation : '. $sql );
}
else {
$msg = array('error' => $error, 'msg' => 'Failed! updation-2 ');
}
}
echo json_encode($msg);
}
Thanks
You have 3 problems.
Problem number one and two are related. Firstly, you are specifying dataType: 'json', but you are passing your data in application/x-www-form-urlencoded format. Secondly, your php script expects data to be in the following format:
$_POST = [
'Text' => ['text_1', 'text_2', 'text_3'],
'Amount' => ['amount_1', 'amount_2', 'amount_3']
];
While your data looks something like this:
$_POST = [
'Text_1' => 'text_1',
'Text_2' => 'text_2'
// and so on
];
The single fix to this problem is as follows:
$(document).ready(function() {
$("#submit").click(function() {
const data = {
// we are grabbing all inputs with name=Text[]
// and mapping them to array containing their values.
// The `...` is a spread operator introduced
// with the new js standard (ES6),
// that converts jQuery object to regular javascript
// array of inputs.
// you can do all of this with a for loop, but the map way
// is prefered
Text: [...$('input[name="Text[]"]')].map(input => input.value),
Amount: [...$('input[name="Amount[]"]')].map(input => input.value)
}
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: data,
dataType: "json",
success: function(response) {
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
The third problem is that have created an SQL Injection vulnerability. That means some bad guy can inject and SQL statement into Text variable, which then you are putting directly into your sql update, thus he can do whatever he wants (for example drop all database).
More on SQL Injection
The solution is simple: use PDO and bindValue method.
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$conn = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
// 500 means internal server error
// that's handy information for the client-side
http_send_status(500);
echo json_encode([
'error' => [
'message' => 'Unable to connect to database'
]
]);
exit;
}
$eid = $_POST['eid'];
$Text = $_POST['Text'][$i];
$Amount = $_POST['Amount'][$i];
$sql = "UPDATE TblCustom SET Text = :text, Amount = :amount WHERE ID = :id";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':text', $Text);
$stmt->bindValue(':amount', $Amount);
$stmt->bindValue(':id', $eid);
if (!$stmt->execute()) {
// 400 means something went wrong when updating
// also a handy information for the client-side
http_send_status(400);
echo json_encode([
'error' => [
'message' => 'Unable to update'
]
]);
exit;
}
// 204 measn everything went okay, and we don't return anything
http_send_status(204);
exit;
Hint: if you are sending correct status codes the jQuery lets you handle errors like this:
$.ajax({
// ...
success: function(response) {
// this code will be executed
// only when status code == 2xx
},
error: function(response) {
// this code will be executed
// only when status code == 4xx | 5xx (if I remember correctly)
},
always: function(response) {
// this code will be executed no matter what
// as the name implies
},
});
So there is no need for additional if statements.
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="form_signup" name="form_signup">
<tr>
<td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td>
<td><input type="text" value="1001.00" name="SAmount[]" id="Amount_1" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td>
<td><input type="text" value="1002.00" name="SAmount[]" id="Amount_2" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td>
<td><input type="text" value="1003.00" name="SAmount[]" id="Amount_3" /></td>
</tr>
<input type="submit" name="signup" value="Sign Up!"/>
</form>
<script>
$(document).ready(function() {
$("#form_signup").click(function() {
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: $(this).serialize(),
success: function(response) {
alert(response);
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
</script>
</body>
</html>
process.php
<?php
print_r($_POST);
?>

Edit button inside table row only works in consecutive order

I am using php and javascript in order to display data from mysql in a table where each row must have an update button.
It seems to be working fine but i'm getting a weird behavior: it works when i click the buttons in consecutive order (#1 then #2 then #3..) but when i click them randomly (starting with #2 or #3...) it does nothing, just reloads the page.
Can you help me find what am i doing wrong, here's my code so far...
Thanks!
list.php:
<?php
$q= "SELECT * FROM list WHERE id = $f ORDER BY id";
if ($query = mysqli_query($db_con, $q)) {
$y=1;
echo '<table>'.
'<tr>'.
'<th>#</th>'.
'<th>Name</th>'.
'<th>Edit</th>'.
'</tr>';
while ($reg= mysqli_fetch_row($query)){
echo '<tr>';
echo '<td>'.$y.'</td>';
echo '<td>'.$reg[0].'</td>';
echo '<td>
<form id="frm_data'.$y.'" method="post">
<input type="hidden" id="name" name="name" value="'.$reg[0].'" />
<input type="hidden" id="f" name="f" value="'.$f.'" />
<input type="hidden" id="a" name="a" value="'.$a.'" />
<input id="FormSubmit" type="submit" value="EDIT">
</form>
</td></tr>';
$y = $y +1;
}
echo '</table>';
}
?>
validate.js
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
e.preventDefault();
$("#FormSubmit").hide();
var myData = {
name: $("#name").val(),
a: $("#a").val(),
f: $("#f").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "update.php", //Where to make Ajax calls
dataType:"json", // Data type, HTML, json etc.
data:myData, //Form variables
success : function(data) {
if(data.status == 'success'){
alert("OK!");
} else if(data.status == 'error') {
alert("ERROR!");
}
},
error : function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
update.php
<?php
$f = $_POST["f"];
$name = $_POST["name"];
$q = "UPDATE list SET edited = '1' WHERE id = '$f' AND name = '$name' ";
$update_row = mysqli_query($db_con, $q);
if (!$update_row) {
$response_array['status'] = 'error';
} else {
$response_array['status'] = 'success';
}
?>

Categories

Resources