I want to prevent an echo from an AJAX response. I have 2 buttons and I need to enable and disable them using JS by AJAX responses. The JS code to enable/disable the HTML elements has been already written inside the PHP if condition of the AJAX URL Page. From AJAX I can display the results on <span id="dupmsg"></span>.
The result will be "Already Exists" and "Not Exist". I only want to display the message and enable/disable the buttons based on the condition. Here it's not working:
Index Page in php:
<h2>Enabling and Disabling text field using JavaScript</h2>
<form id="registration-form">
Enter your name: <input type="text" id="name">
</form>
<button onclick="disable()">Disable the text field</button>
<button onclick="enable()">Enable the text field</button>
<p>Ajax Response is: <span id="dupmsg"></span></p>
<script>
function check_dup()
{
var barcode=$("#memb_barcode").val();
$.ajax({
type: 'POST',
url: "ajax_attendance.php",
data: {
barcode: barcode
},
success: function(msg)
{
//alert(msg); // your message will come here.
$('#dupmsg')
.css('color', 'red')
.html(msg)
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
</script>
Ajax URL Page:
<?php
$reg_no = mysqli_real_escape_string($con, $_POST['reg_no']);
$barcode = mysqli_real_escape_string($con, $_POST['barcode']);
$sql = "SELECT id from tblstudent where reg_no = '$reg_no' && barcode like '$barcode' ";
$query = mysqli_query($con, $sql);
$ecount = mysqli_num_rows($query);
if($ecount!=0)
{
printf("Already Exists");
echo'
<script>
function disable() {
document.getElementById("name").disabled = true;
}
</script> ';
}
else
{
printf("Not Exists");
echo'
<script>
function enable() {
document.getElementById("name").disabled = false;
}
</script> ';
}
?>
The problem is that the JS written inside the PHP echo is reflecting back to span id="dupmsg" with AJAX response. I don't want to bring it in AJAX response. Please help.
<h2>Enabling and Disabling text field using JavaScript</h2>
<form id="registration-form">
Enter your name: <input type="text" id="name">
</form>
<button id="disable" onclick="disable()">Disable the text field</button>
<button id="enable" onclick="enable()">Enable the text field</button>
<p>Ajax Response is: <span id="dupmsg"></span></p>
<script>
function check_dup()
{
var barcode=$("#memb_barcode").val();
$.ajax({
type: 'POST',
url: "ajax_attendance.php",
data: {
barcode: barcode
},
success: function(msg)
{
if(msg=='true'){
document.getElementById("name").disabled = true;
$("#disable").attr("disabled", true); // write the id of the button u want to hide
$('#dupmsg')
.css('color', 'red')
.html("Already Exists")
}
else if(msg=='false')
{
document.getElementById("name").disabled = false;
$("#enable").attr("disabled", false); // write the id of the button u want to hide
$('#dupmsg')
.css('color', 'red')
.html("Not Exists")
}
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
function enable() {
document.getElementById("name").disabled = false;
}
function disable() {
document.getElementById("name").disabled = true;
}
</script>
ajax_attendance.php
<?php
$reg_no = mysqli_real_escape_string($con, $_POST['reg_no']);
$barcode = mysqli_real_escape_string($con, $_POST['barcode']);
$sql = "SELECT id from tblstudent where reg_no = '$reg_no' && barcode like '$barcode' ";
$query = mysqli_query($con, $sql);
$ecount = mysqli_num_rows($query);
if($ecount!=0)
{
return true;
}
else
{
return false;
}
?>
Related
I am trying to create a page that will delete a user from my database when it is searched, ask for confirmation, and then delete it, i am extremely close but i need to pass the function through ajax to java script but im not understanding how to do that. Here is my code:
<html>
<head>
<?php
require_once('conn.php');
function deleteEmployee($conn, $employee, $table){
$query = "DELETE from $table where EmployeeName = '$employee'";
$confirmed = mysqli_query($conn, $query);
if ($confirmed){
echo "User Deleted";
}
else{
return True;
echo 'User has been deleted';
}
return;
}
//$query1 = 'select *
?>
<script>
function myFunction() {
var txt;
return confirm('Are you sure?');
if (confirm == true) {
deleteEmployee($conn, $name, "employee");//This is where i am having trouble
} else {
txt = "Okay";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</head>
<body>
<p id="demo"></p>
<form action="" method="post">
Search Name to be Deleted: <input type="text" name="term" /><br />
<button onclick="myFunction()" type="submit" value="Submit" />submit</button>
</form>
<?php
if (!empty($_POST['term'])) {
$term = mysqli_real_escape_string($conn,$_POST['term']);
$sql = "SELECT EmployeeName FROM employee ";
$r_query = mysqli_query($conn,$sql);
if($r_query->num_rows == 0){
echo "Name not in database";
} else{
while ($row = mysqli_fetch_array($r_query)){
$name = $row['EmployeeName'];
}
}
}
?>
</form>
As of right now, the window pops up but when i press ok, nothing happens since i do not understand how to pass a function through ajax to javascript. Can someone help? If you need more info, let me know
How about using jQuery AJAX, storing your php functions in different files and just past post/get data so your PHP methods can process what you want to process?
Example Usage:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
i have a little problem here with jQuery.
i have made a submit form with this following code :
<form class="form-inline" id="newslatter" role="form" >
<select name="city" id='city' class="form-control">
<option value="<?=$id?>">Singapore</option>
</select>
<input type="email" class="form-control" name="email" id="email" placeholder="<?=$this->lang->line('footer_enter_email')?>" value="<?=(isset($json)?$json["email"]:"")?>">
<label id="emptyemail" style="color:indianred"><?php echo form_error('email'); ?></label>
<button type="submit" class="btn btn-success input"><?=$this->lang->line('footer_signup_now')?></button>
</form>
<div id="register_complete" style="display: none;color:whitesmoke;">
<p align="center">Congratulations, You have been added to our Newsletter
Thank you for your registration. From now on you will receive updates about exclusive offers in your city.</p>
</div>
and this is my jQuery :
<script type="text/javascript">
function validateEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$("#newslatter").submit(function(e){
e.preventDefault();
var email= $("#email").val();
var city=$("#city").val();
var something_wrong="";
var agreement = $('#agreement input[type="checkbox"]').is(":checked");
if(email.length == 0){
$("#emptyemail").html("Please fill in Email field");
$("#email").focus();
something_wrong=true;
}else if(!validateEmail(email)){
$("#emptyemail").html("insert valid email address!");
something_wrong=true;
}else{ $("#emptyemail").html(""); something_wrong=false; }
if(agreement == false ){
$("#notagree").html("You should read and accept Terms and conditions and Privacy Policy");
something_wrong=true;
}else{ $("#notagree").html(""); something_wrong=false;}
if( something_wrong == true) return false;
jQuery.ajax({
type: "POST",
url: "ajax/newslatter",
dataType: 'json',
data: {pcity:city,pemail:email},
success: function(res) {
if (res)
{
if(res.message != "success"){
$("#emptyemail").html(res.message);
return false;
}else{
$("#newslatter").hide();
$("#register_complete").show();
}
}
}
});
return false;
});
and this is my ajax controller:
Function newslatter(){
$city_id=$this->input->post('pcity',true);
$email = $this->input->post("pemail",true);
$query= $this->ajax_m->m_check_email($email);
if(strlen($email)==0){
$data["message"]= "Please fill in Email field";
}else{
if($query != null){
$data["message"]= "E-mail already registered";
}else{
$this->ajax_m->m_insert_newslatter($city_id,$email);
$data["message"]= "success";
}
}
}
and here is the following model for ajax :
Function m_check_email($email){
$sql="SELECT `email` FROM `uhd_newslatter` WHERE `email` = '$email'";
$query=$this->db->query($sql)->row_array();
return $query;
}
Function m_insert_newslatter($city,$email){
$sql="INSERT INTO `uhd_newslatter` (`singapore_address_id` , `email`) VALUES ($city,'$email')";
$this->db->query($sql);
}
those are all my code. my problems are :
if i submit data, data send into my database, but after that there is nothing happening in my view, actually if submit process is success there will be show my success message, and all my submit form will be hide
and, if i use the same email, if i submit it, it should be show a message that i put it ajax controller. but data isn't input to database.
guys can you help me whats wrong on my code?
sorry if i have so many part of code (:
In your ajax writen dataType:'json', but in your controller there is json_encode($yourdata); that will be read in success ajax. Because of that, your success is not executed.
jQuery.ajax({
type: "POST",
url: "ajax/newslatter",
dataType: 'json',
data: {pcity:city,pemail:email},
success: function(res) { //controller has to make json_encode($data); for product res value.
if (res)
{
if(res.message != "success"){
$("#emptyemail").html(res.message);
return false;
}else{
$("#newslatter").hide();
$("#register_complete").show();
}
}
}
});
Your controller need to be added echo json_encode($data);
Function newslatter(){
$city_id=$this->input->post('pcity',true);
$email = $this->input->post("pemail",true);
$query= $this->ajax_m->m_check_email($email);
if(strlen($email)==0){
$data["message"]= "Please fill in Email field";
}else{
if($query != null){
$data["message"]= "E-mail already registered";
}else{
$this->ajax_m->m_insert_newslatter($city_id,$email);
$data["message"]= "success";
}
}
echo json_encode($data);//add this line
}
Please update your newsletter function with this code:
function newslatter(){
$data =array();
$city_id=$this->input->post('pcity',true);
$email = $this->input->post("pemail",true);
$query= $this->ajax_m->m_check_email($email);
if(strlen($email)==0){
$data["message"]= "Please fill in Email field";
}else{
if($query != null){
$data["message"]= "E-mail already registered";
}else{
$this->ajax_m->m_insert_newslatter($city_id,$email);
$data["message"]= "success";
}
}
return json_encode($data);
}
I am trying to get the results from the database whether username is available or not . But it is not giving any results i am not getting ajax response this is the html code
<form id="user_form">
<input placeholder="username here" type="text" name="ajax-data" id="ajax-data">
<input type="submit" name="btnSubmit" id="btnSubmit" Value="Submit">
</form>
<span class="php_responce_here"></span>
This is the ajax code which i have used
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: {ajax-data: textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result);
}
});
});
});
</script>
final code of php where i have used the validation and the query to find whether the username is available in the database or not the problem is that it is not giving any of the result
<?php
error_reporting(0);
require "config.php";// configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if($user_name)
{
$usernamecheck= mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check= mysql_fetch_row($usernamecheck);
if($check[0]==0)
{
if($user_name!=""){
if(strlen($user_name)>25){
echo "You have reached the maximum limit";
}
else{
echo "User name is valid";
}
}
else
{
echo "username is empty";
}
}
else{
echo "Username Already Taken";
}
}
?>
should be submit event not click:
$("form#user_form").submit(function(e) {
e.preventDefault();
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: { "ajax-data": textboxvalue },
success: function(result) {
$(".php_responce_here").html(result);
}
});
});
and as #Cyril BOGNOU pointed out;
data: { "ajax-data": textboxvalue }
You should too add data type to be returned with the parameter if you want to return JSON for example
dataType: 'JSON',
and Yes I think you should better write
data: { "ajax-data": textboxvalue }
So the update should be
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
dataType: 'JSON',
data: {"ajax-data": textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result.message);
}
});
});
});
and return json string from PHP script
<?php
error_reporting(0);
require "config.php"; // configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if ($user_name) {
$usernamecheck = mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check = mysql_fetch_row($usernamecheck);
if ($check[0] == 0) {
if ($user_name != "") {
if (strlen($user_name) > 25) {
$message = "You have reached the maximum limit";
} else {
$message = "User name is valid";
}
} else {
$message = "username is empty";
}
} else {
$message = "Username Already Taken";
}
echo json_encode(["message" => $message]);
}
?>
NOTE : mysql is deprecated. you should use mysqli or PDO
There are some mistakes in your code. check the below code. it should work.
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var textboxvalue = $("#ajax-data").val();
$.ajax({
data: {ajaxdata: textboxvalue},
type: "POST",
url: 'second.php',
success: function (result)
{
$(".php_responce_here").html(result);
}
});
return false;
});
});
</script>
You can not create variable ajax-data with -.
PHP
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$user_name'");
$check = mysql_num_rows($usernamecheck);
you should use mysql_num_rows instead of mysql_fetch_row. it will auto calculate the rows.
Check working example
Empty page? Nothing prints out?
<?php
error_reporting(-1);
ini_set('display_errors', 1);
require "config.php";// configuration file holds the database info
if(isset($username = $_POST['ajax-data'])){
if($l = strlen($username) <= 25 && $l > 2){
$sql = "SELECT * FROM users WHERE username='$username'"; // wide open for SQL injections. use mysqli or PDO instead.
if($rsl = mysql_query($sql) != false){ // ALWAYS verify if your query's ran successfully.
if(mysql_num_rows($rsl) != 0){
echo 'Username already exists';
} else {
echo 'Username is available';
}
} else {
echo 'Query failed: ' . mysql_error();
}
} else {
echo $l > 25 ? 'Reached limit' : 'Needs to be longer';
}
} else {
echo "post['ajax-data'] not set<\br>";
print_r($_POST);
}
?>
Then there is your Javascript code that I have questions on. Yet you have a submit button but you want to check if its valid upon change?
$(document).ready(function(){
$("#user_form").submit(function(event){
event.preventDefault();
$.ajax({
url: "second.php",
type: "post",
data: $(this).serialize(),
success: function(result){
$(".php_responce_here").html(result);
}
});
});
});
On blur of an e-mail textbox, I want it to do an ajax call back and verify if the e-mail is already in use.
The call is finding the webmethod, however, it's returning a null value. I trimmed the code and I'm getting a null value with the following:
function chkEmail(email) {
var prom = $.Deferred();
console.log(email);
$('#emailCheckGIF').show();
$('input[type="submit"]').prop('disabled', true);
$.ajax({
url: 'emailAvailable',
data: { 'email': email },
success: function (data) {
console.log(data + ' good');
prom.resolve(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown + ' error');
prom.reject(errorThrown);
}
});
return prom;
}
My simplified web method
public function emailAvailable($email = null) {
echo json_encode($email);
}
In the firefox dev tools, it says the email param is being passed correctly and the response from the service is NULL
If I remove the json_encode it comes over as a blank string.
Please Try This --
My Controller --
public function checkEmail()
{
$email = $_POST['email'];
$result = $this->federation_model->checkEmail($email);
echo json_encode($result);
}
My Model --
public function checkEmail($email)
{
$this->db->where('user_email', $email);
$result=$this->db->get('users')->row_array();
if(is_array($result))
{
return $result;
}
else
{
return false;
}
}
My View --
<div class="col-md-4">
<input name="assoc_email" id="assoc_email" type="email" class="form-control"/>
<span id="line2" class="text-left"></span>
</div>
My Script --
<script type="text/javascript">
$(document).ready(function(){
$('#assoc_email').keyup(function(){
var email = $('#assoc_email').val();
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// my ajax function will call after enter the valid email
if(email == "" || !filter.test(email))
{
$('#line2').html("");
$('#submit_assoc').attr('disabled', false);
}
if(filter.test(email) && email != "")
{
$.ajax({
url:"<?php echo base_url(); ?>federation/checkEmail",
type:"post",
data:"email="+email,
success: function(data){
var result = JSON.parse(data);
if(result == "")
{
$('#line2').html("<?php echo $this->lang->line('email'); ?> <?php echo $this->lang->line('available'); ?> ");
$('#line2').css('color', 'green');
}
else
{
$('#line2').html("<?php echo $this->lang->line('email'); ?> <?php echo $this->lang->line('already'); ?> <?php echo $this->lang->line('exists'); ?>");
$('#line2').css('color', '#f3565d');
}
}
});
}
});
});
</script>
as title, I am a beginner about website design.
Please never mind if I ask a stupid question.
while i send the form, it didnt work.
here is html:
<form id="form1" name="form1" action="toSQL.php" method="POST" accept-charset="utf-8">
<input type="text" name="Cliname" id="textfield" maxlength = "10" />
<textarea name="message" id="message" rows="3" maxlength = "20" ></textarea>
<input type="submit" value="submit" id="submit" />
</form>
<div class="alert"></div>
and here is js:
<script type="text/javascript">
$(document).ready(function() {
var form = $(this) ;
var submited = $('#submit') ;
var alerted = $('.alert') ;
form.on( 'submit', this, (function(event) {
event.preventDefault();
if ( $.trim($form.find('input[name="Cliname"]').val()) == "" || $.trim($form.find('input[name="message"]').val()) == "" ) {
alert( "please enter!!" ) ;
return ;
}
else {
$.ajax({
url: 'toSQL.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alerted.fadeOut();
},
success: function(data) {
alerted.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
},
error: function(e) {
console.log(e)
}
});
}
}));
});
</script>
server side php:
<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['Cliname']) AND isset($_POST['message'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (send($name, $message)) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
function send( $name, $message ) {
$time = date("Y-m-d H:i:s");
$mysqlConnection=mysql_connect("localhost", 'root', '') or die("connect error!");
mysql_select_db('test') or die ("db error!");
$queryStr="INSERT INTO fortest (time, message, name)
VALUES ( '$time', '$message', '$name')";
mysql_query($queryStr,$mysqlConnection) or die(mysql_error());
return true ;
}
?>
here is the website i reference : http://www.w3bees.com/2013/08/submit-form-without-page-refresh-with.html
Did i miss something?
As a couple people have mentioned already, you are trying to serialize your entire dom object, which isn't going to work. Change it to var form = $("#form1") and it should work.
I recommend you open the webpage in chrome dev tools and click the network tab, click preserve log and then submit the form. When it is submitted you'll see the full headers that were sent to the server and can verify it works correctly to help narrow down the problem