I am trying to check if username already exists in the table using ajax input onchange trigger in CodeIgnitor view.
Ajax function on the view
<script>
$('#username').on('change',function(e){
var u_name=$(this).val();
$.ajax({
type: "POST",
url: "<?php echo site_url('home/checkUserExist');?>",
data: { u_name: u_name },
dataType: "html",
success: function(msg){
$('#error_msg').empty();
$('#error_msg').append(msg);
},
error:function(error){
$('#error_msg').append("There is some errors on server : " + error.error);
return false;
}
});
});
</script>
Controller function
function checkUserExist()
{
$u_name= strip_tags(mysql_real_escape_string(trim($this->input->post('u_name'))));
if($this->public->checkMemberExisit($u_name)==false)
{
echo "<p>Username Exists, Try another username</p>";
}
else
{
echo "<p>Username Available</p>";
}
}
but i keep getting this error :
There is some errors on server : function (){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this}
Can anyone tell me whats going on. it used to work before.
Related
so I have the following code that is calling a CheckEmail2.php. I know what I want to do in CheckEmail2.php but because my Ajax success is not working, I have minded the scope to just return a Json. below is my java script. When I launch my console, I see my string coming through that I am echoing in my CheckEmail2.php. so I know my php file is getting read but why won't my success function hit if my string is getting read? I can't get my success function to get called. It always goes to error.
<script type="text/javascript">
function validateForm(){
var email = document.forms["signupform"]["email"].value;
var result = false;
if (email != ""){
$.ajax({
type: "POST",
url: "/CheckEmail2.php",
data: { "User_Email": email },
dataType: "json",
success: function(resp){
console.log(resp);
if(resp == "Not Found"){
result = true;
}
else
{
result = false;
}
},
error: function(data, status){
console.log(data, status);
}
}); //end Ajax
}
return result;
}
</script>
here is my PHP
<?php
header("Content-type:application/json");
echo json_encode("Not Found");
?>
why is error always getting called?
I have been struggling for days. I am doing ajax callback by assigning an input field but I am unable to too. Below is the code:
Script
$('[name="acccode[]"]').each(function(idx,val){
var acccode = $('[name="acccode[]"]').eq(idx).val();
console.log(acccode);
$.ajax({
url : "<?php echo base_url(); ?>readacccode",
type: "POST",
data:"Acc_Code="+acccode,
dataType: "JSON",
success: function(data)
{
$.each(data.results,function(idx,val){
console.log(val);
$('[name="accname[]"]').val(val);
});
},
error: function (data)
{
swal("Oops", "We couldn't connect to the server!", "error");
}
});
});
I am successfully able to get each acc code. But not the name.
Here is the Controller code:
public function readacccode()
{
if (!$this->ion_auth->logged_in() || $this->ion_auth->is_store())
{
redirect('account/login');
}
$acccode = $this->input->post('acccode');
$data['results']=$this->Setting->get_acccode($acccode);
echo json_encode($data);
}
it is getting the acc name where the acc code matches.
Please advise.
Thanks, everyone the problem is resolved. For those wanting to know here is the thing I change.
public function readacccode()
{
if (!$this->ion_auth->logged_in() || $this->ion_auth->is_store())
{
redirect('account/login');
}
$acccode = $this->input->post('Acc_Code'); //All I did is replace acccode to Acc_Code
$data['results']=$this->Setting->get_acccode($acccode);
echo json_encode($data);
}
I'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});
I have a php file with a form that is sent using jQuery.ajax(). The problem that I have if the email is not sent and the error message is not shown.
$(document).ready(function () {
$('input[type="submit"]').click(function () {
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(responseText) {
$('#result').css('background', 'green');
},
error: function(responseText) {
$('#result').css('background', 'red');
}
});
return false;
});
});
As the email is not sent the error not shows anything but the success yes. So, I change my mail.php code for that other code.
<?php
if(2 > 4) {
true;
} else {
false;
}
?>
When I press the button, the success action stills working and I don't know why.
The error callback is only triggered if the ajax call fails, not if the PHP mail function fails, and not if you return false, that would be a success as you received something back from the server (the string "false").
To catch errors like that you can either trigger an error from PHP or just catch it in the success handler:
success: function(data) {
if (!data || $.trim(data) == 'false') {
$('#result').css('background', 'red');
}else{
$('#result').css('background', 'green');
}
},
and PHP
<?php
echo 2>4 ? 'true' : 'false';
?>
Remove the error function & make changes to your success function
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(responseText) {
if(responseText)$('#result').css('background', 'green');
else $('#result').css('background', 'red');
}
});
The error function will not trigger unless jQuery fails to connect to your php file, in this case you would wan't to handle your own errors, first off what does this do?
if(2 > 4) {
true;
} else {
false;
}
this would not send anything back to jQuery i recommend the following
if(2 > 4) {
echo 'true';
} else {
echo 'false';
}
then in your jQuery
$(document).ready(function () {
$('input[type="submit"]').click(function () {
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(result) {
if(result === 'true') {
$('#result').css('background', 'green');
} else {
$('#result').css('background', 'red');
}
},
error: function(error) {
alert(error)
}
});
return false;
});
});
In your both cases, the success callback is fired:
success: function(responseText) {
if(!!responseText) //!! convert string to boolean
$('#result').css('background', 'green');
else
$('#result').css('background', 'red');
},
First in mail.php file echo that you want to return:
<?php
if(2 > 4) {
echo "true";
} else {
echo "false";
}
?>
And then in success function do that:
success: function(responseText) {
if(responseText) {
$('#result').css('background', 'green');
} else {
$('#result').css('background', 'red');
}
}
It also depends on the version of the jquery you are using. If its 1.9 then you can handle it using the done, fail and always function
For 1.9
var request = $.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
}
});
request.done(function(e){
//GET THE STATUS FOR THE EMAIL FROM THE PHP SCRIPT
//ASSUMPTION THAT FETCHING e=1/0 - 1 - Success, 0 - Failure
if(parseInt(e))
{
$("#result").css("background","green");
}
else
{
$("#result").css("background","red");
}
});
1) Your php script doesn't return anything. For instance, if you eliminate all javascript from your html page, and your form's action attribute specifies myphp.php, and myphp.php looks like this:
<?php
$html = "<html><head></head><body><div>Hello world.</div></body></html>";
?>
What will be displayed after you click on the form's submit button?
2) The error function is called if the request fails. Getting a response of nothing or false from your php script is not a failure of the request. A successful request means that the browser sent out a request, the server received the request, the server caused your php script to execute, and the server sent back the results of your php script as a response. A request fails if the server is too busy to respond to the request, the server crashes while handling your request, you request a file that doesn't exist, etc.
I'm using in the same page a validation engine with date picker.
Datepicker: http://jqueryui.com/demos/datepicker/
Validationengine: http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
I've added a jQuery.noConflict(); to make it work (at the beginning of the code).
Now, I need to make my insert through a PHP file, but without refreshing the page, and by displaying an error message in the same bubble of validationEngine (for example when the email is already registered in the BDD).
should I import jQuery to make my insert in the same page
without causing conflicts, or can I use one on the query already used
for the same purpose?
How do I display a server response through the validationEngine?
My code is the following one.
$(".btn_newsletter").live('click', function() {
$.ajax(
{
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
if (data.check==0) {alert('Error : Sorry '); return false;}
if (data.check==1) {alert('yep!!!');
}
},
cache: false,
type: "POST",
dataType: 'json'
});
}
This is my PHP code.
$ip= $_SERVER["REMOTE_ADDR"];
$select = "select * from av_newsletter where email='".$_POST['email']."'";
$exist = $_BASE->query_array($select);
if ($exist) {
$check = "0";
}
else {
$ajout="INSERT INTO av_newsletter(id,sub_date,email,ip) VALUES (NULL,now(),'$email','$ip')";
$add=$_BASE->query($ajout);
if ($add) {
$check="1";
}
}
$return_arr["check"] = $check;
echo json_encode($return_arr);
It doesn't work; I've no alert, but also no errors.
If you are not tied in too deeply to your 'Validationengine' I would recommend using this one, is has served me well for years, it has support for making remote checks so you could do something like this:
$(document).ready(function(){
var save_options = {
success: userSaved, //callback function
url: '/users/save',
response: 'json',
method: 'post'
};
var validationObj = {
rules: {
name: "required",
email: {
email: true,
required: true,
remote: "/user/check_email/"
}
},
messages: {
name: "Please name yourself",
email: {
required: "Please enter your email address",
email: "Invalid email address",
remote: "Email already in use."
}
},
errorPlacement:function(error, element) {
error.appendTo( element.next() );
},
submitHandler: function(form) {
$(form).ajaxSubmit(save_options);
},
success:function(label) {
label.html(" ").addClass("checked");
}
};
});
And then on the PHP side at the '/users/check_email' endpoint the PHP does the following:
echo $emailExists ? json_encode(false) : json_encode(true);
Ok, before we spam the comments and get to far off topic, please execute this code which should get you started in getting it to work eventually.
$(".btn_newsletter").live('click',function() {
alert('clicked'); // click is executed
$.ajax({
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
alert(data); // should alert the data
if(data.check==0){ alert('Error : Sorry '); return false; }
if(data.check==1){ alert('yep!!!'); }
},
error: function(request, status, error) {
alert('failed '+status);
},
cache: false,
type: "POST",
dataType: 'json'
});
});
it works :)
$(".btn_newsletter").live('click',function() {
var data ="email="+$('#email').val();
$.ajax({
url: "php/functions/signin.php"+"?"+data,
success: function(data) {
if(data.check=='1'){ alert('yep!!!'); }
if(data.check=='0'){ alert('Error : Sorry '); return false; }
},
cache: false,
type: "POST",
dataType: 'json'
});
});
and in my signin.php I catch the value of the input like this $email=$_REQUEST['email']
Thanks a lot! time for me to see about validation engine how to link this with :)