I have create multiple forms, this form hide and show after change a drop down value
I wank to check duplicate entry on click on submit button
than add this code
but this code do not work properly
jQuery('#form_1').on('submit', function(event) {
jQuery.ajax({
url: SITE_URL+'/admin/ajax/function.php',
type: "POST",
data: jQuery('#form_1').serialize(),
dataType : 'json',
a sync : false,
success: function(response){
if(response.status === true){
var error = '<div class="alert alert-danger">this record already exist</div>';
jQuery('.form1ErrorMsg').html(error);
return false;
}else{
alert('test');
//return true;
}
},
error: function(){
return false;
}
});
//return false;
});
function.php
if(isset($_POST['ActionToCall'])){
$Action = $_POST['ActionToCall'];
switch($Action){
default:{
break;
}
case 'chkDuplicatChiefInvigilator':{
require_once('../../class/staff.class.php');
require_once('../../class/user.class.php');
$staff = new staffmanager();
$users = new usermanager();
$result=$staff->getDuplicatChiefInvigilator($_POST);
if(!empty($result)){
$output['status']=1;
}else{
$output['status']=0;
}
print json_encode($output,true);
die;
}
}
Look at your syntax error:
dataType : 'json',
async : false,
Related
I have the code below requesting a php file result:
var fn_name = function(data){
var tmp = 'no change';
$.ajax({
type: 'POST'
, url: 'std/files/fn/cquery.php'
, cache: false
, data: { query:data }
, success: function(data){ tmp = data; }
, error: function() { tmp = 'error'; }
});
return tmp;
}
And here is the php file:
<?php
function cquery($data){
$conn = new mysqli('localhost','user','pswd','db');
if(($conn->query($data))->fetch_assoc()){
return 'true';
}else{
return 'false';
}
}
if(isset($_POST['query'])){ echo cquery($_POST['query']); }
?>
The problem is that the fn_name('correct query here') returns 'no change'. The Ajax's success is been executed, inserting an alert() there works...
Can't figure out what's happening...
I have the below Ajax function
ajax = function (params, action) {
$.ajax({
type: "POST",
url: "ajax.php",
data : params+"&action="+action,
dataType: "json",
success: function(response) {
switch(action)
{
case "save":
//some stuff
break;
case "del":
var seclastRow = $("."+table+" tr").length;
if(response.success == 1)
{
$("."+table+" tr[id='"+response.id+"']").effect("highlight",{color: '#f4667b'},500,function()
{
$("."+table+" tr[id='"+response.id+"']").remove();
});
}
break;
}
},
error: function() {
alert("Unexpected error, Please try again");
}
});
}
The following is the ajax.php that it calls. The file is a big if-else series, but I am pasting the wrong part only.
else if ($action == "del")
{
$id = $_POST['rid'];
$res = $obj->delete_record($id);
if ($res)
{
echo json_encode(array("success" => "1","id" => $id));
}
else
{
echo $obj->error("delete");
}
}
However, once the result is echoed back, the success function never enters in the Ajax part and I always get the Unexpected error alert.
Any ideas?
I as able to get the error using the callback error: function() and then displaying the response inside console.log. Check the image. response text
I've created a JQuery script that checks a database for usernames and shows an error if you type in an existing name on keyup, this is workng fine but the form still submits even if this error is true. What other code can I add to check that this error doesn't exist? Here is the code I have so far:
<script>
$(function()
{
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Thank you
please see the comments on the code
assuming that the data == 1 means that the name is already registered and you will show an error
<script>
$(function()
{
var name = false; // a variable that holds false as the initial value
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
name = true; // on success , if the name isnt there then assign it to true
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username) && name == true) // check for the value of name
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Instead of checking the username against the regex, you should check the status of $('.usernameStatus') because it is possible that it passes the regex test but still fails the duplicate test returned from your db.
So
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
should instead be:
$('#registerButton').click(function()
{
var username=$("#username").val();
if(!$('.usernameStatus').hasClass('error'))
{
Even better would be to introduce a variable that holds the validity of the name field so you don't need to get the DOM Element all the time and check it's class.
I think your error might be because of a bad data syntax
It should be like this:
data: 'username:'+ username,
Debug your PHP code to see if its receiving the username properly at the moment though
I'm trying to check if a website exists with an ajax call, but I'm not sure I am getting it right. On my page I grab a URL on click
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(){
$("#start").remove();
},
error: function(){
alert("Bad URL");
}
});
});
a=And then check on ajax.php
$url = $_POST['url'];
ini_set("default_socket_timeout","05");
set_time_limit(5);
$f=fopen($url,"r");
$r=fread($f,1000);
fclose($f);
if(strlen($r)>1) {
return true;
} else {
return false;
}
It seems I am getting SUCCESS no matter what... What am I missing?
It seems I am getting SUCCESS no matter what... What am I missing?
This is extremely pretty straightforward.
Because of this reasons:
// You have no idea what server respond is.
// that is you can't parse that respond
success: function(){
$("#start").remove();
}
Which should be
success: function(respond){
//you don't have to return TRUE in your php
//you have to echo this one instead
if ( respond == '1'){
$("#start").remove();
} else {
//handle non-true if you need so
}
}
In php replace this:
if(strlen($r)>1) {
return true;
} else {
return false;
}
to
if(strlen($r)>1) {
print true; //by the way, TRUE is a constant and it equals to == 1 (not ===)
}
Oh yeah, also don't forget to fix this as well:
data: "url="+url,
to data : {"url" : url}
As Nemoden said, you get a success message even if it returns false.
You need to check the data returned and then remove the element.
for example
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(response){
if (response == 'whatever you are returning') {
$("#start").remove();
}
},
error: function(){
alert("Bad URL");
}
});
});
Success callback is called whenever server-side script returned an answer (there were no connectivity errors or server-side errors). Is this answering your question?
See the difference:
$("#go").click(function() {
var url = $("#url").val(),
ajax_data = {url: url};
$.post({
"/ajax.php?cb=?",
ajax_data,
function(response){
if (response.status) {
// URL exists
}
else {
// URL not exists
}
$("#start").remove();
},
'json'
});
});
php back-end:
printf('%s(%s)', $_GET['cb'], json_encode(array('status' => (bool)$url_exists)));
How to create jQuery + ajax form without refresh?
This is my controller and views:
http://pastebin.com/GL5xVXFZ
In "clear" PHP I create something like this:
$(document).ready(function(){
$("form#submit").submit(function() {
var note = $('#note').attr('value');
$.ajax({
type: "POST",
url: "add.php",
data: "note="+ note,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
});
in add.php file is INSERT to Database.
There are more complicated ways of doing this for example detecting an ajax request in your action and then if detected print out a javascript response. The way you would do this is
JAVASCRIPT
function postForm(note){
$.ajax({
url : '/controller/action',
type : 'POST',
data : 'note='+note,
success : function(jsn){
var json = $.parseJSON(jsn);
if(json.status == 200)
alert('Completed Successfully');
else
alert('Not Completed Successfully');
},
error : function(xhr){
//Debugging
console.log(xhr);
}
});
}
PHP
<?php
Class Controller_ControllerName extends Controller_Template{
public $template = 'template';
public function action_index(){}
public function action_form(){
$this->auto_render = false; // <-EDITED
$array = array();
//PROCESSING FORM CODE HERE
if($success){
$array['status'] = 200;
}else{
$array['status'] = 500;
}
print json_encode($array);
}
}
?>
this is an example i have done without testing but this surely should be enough for you to work on