I need to check language already Exist condition{ without page reload/load }, so that i called ajax at End of my function.
I have a doubt, that can i call function inside ajax call to get a responce before return true statement execute????
my code :
function languageValid(){
if( field1 === '' ){
return false;
}
if( field2 === '' ){
return false;
}
if( field3 === '' ){
return false;
}
// e.g : ajax call
$.post(sitePath+"candidate/index/langues-update",{},function(responce){
// responce as '0' or '1'
exist = $.trim(responce);
if(exist){
return false;
}else{
return true;
}
});
return true;
}
calling function
languageValid();
function does not wait for ajax call respond,
it will execute return true before ajax call
pls share your suggestion!!!!
Your bloc below returns a value from the $.post() function.
if(exist){
return false;
}else{
return true;
}
If you want to get the response, you can try:
function languageValid(){ .....
var result = $.post('url',{},function(responce){}).responseText;
exist = $.trim(result);
if(exist){
return false;
}else{
return true;
}
}
Related
When I do an ajax request i get back the responseText and debugbar info (Laravel)
I get something like that:
ok<link rel='stylesheet' type='text/css' property='stylesheet' href='//127.0.0.1:8000/_debugbar/assets/stylesheets?v=1674820783&theme=auto' data-turbolinks-eval='false' data-turbo-eval='false'><script src='//127.0.0.1:8000/_debugbar/assets/javascript?v=1674820783' data-turbolinks-eval='false' data-turbo-eval='false'></script><script data-turbo-eval="false">jQuery.noConflict(true);</script>
<script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl', addEventListener = function (e, n, cb) { e.addEventListener(n, cb, false); }; refStyle.innerHTML = '.phpdebugbar pre.sf-dump .sf-dump-compact, .sf-dump-str-collapse .sf-dump-str-collapse, .sf-dump-str-expand .sf-dump-str-expand { display: none; }'; (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle); refStyle = doc.createElement('style'); (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle); if (!doc.addEventListener) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, function (e) { e.preventDefault
How can i prevent sendig debug bar info?
This are the few controller functions that I call by ajax request.
The function getusers that show me all users on a crud its the one thath first braks my program
public function usersCrudView(){
if (session('rol')=='admin'){
return view("crudUsers");
}
}
public function getusers(){
if (session('rol')=='admin'){
$users=DB::table('users')
->orderByRaw('email_verified_at IS NULL DESC')
->orderBy('email_verified_at', 'asc')
->get();
return $users->toJson();
}
}
public function verificado(){
try {
if ($_GET['status']=="verify"){
User::verificarEmail($_GET['id']);
return "ok";
}else if ($_GET['status']=="no-verify") {
User::denegarEmail($_GET['id']);
return "ok";
}else if ($_GET['status']=="ban"){
User::banearEmail($_GET['id']);
return "ok";
return "ok";
}else if ($_GET['status']=='quitar_ban') {
User::quitarBan($_GET['id']);
return "ok";
}else if($_GET['status']=='quitar_denegado'){
User::quitarDenegado($_GET['id']);
return "ok";
}
return "no";
}catch (\Exception $e){
return "no";
}
}
I want to have a comments box in my website using codeigniter with Ajax. I want if the comment success show new comment. Else show validation error. How to do it?
This is my controller form validation
if ($this->form_validation->run() == TRUE) {
$this->load->model('comment_model');
$this->load->model('user_model');
if($this->comment_model->insert_comment())
{
$data['user_comment']= $this->user_model->get_user_session($this->session->userdata('user_id'));
$data['new_comment']= $this->comment_model->get_one_comment();
$this->load->view('user/insert_comment',$data);
}
} else {
echo validation_errors();
}
This is my ajax success function.
success: function (data) {
if (data)// this is what is need. How to make a if condition
{
$('ol#update').prepend(data);
$('ol#update li:first').slideDown('slow');
}
else
{
$('#myerror1').html(data);
}
}
Return answer from controller as Json and parse it in success function.
if ($this->form_validation->run() == TRUE) {
$this->load->model('comment_model');
$this->load->model('user_model');
if($this->comment_model->insert_comment()) {
$data['user_comment']=$this->user_model->get_user_session($this->session->userdata('user_id'));
$data['new_comment']= $this->comment_model->get_one_comment();
// third argument means, return template as string instead of echo.
$data = $this->load->view('user/insert_comment',$data, TRUE);
$array = array();
$array['success'] = true;
$array['data'] = $data;
} else {
$array = array();
$array['success'] = false;
$array['data'] = validation_errors();
}
echo json_encode($array);
}
And in success function:
success: function (data) {
var jsonData = JSON.parse(data);
if (jsonData.success == true) {
$('ol#update').prepend(jsonData.data);
$('ol#update li:first').slideDown('slow');
} else {
$('#myerror1').html(jsonData.data);
}
}
For some reason I can't get the post variables from the controller
The AJAX/Javascript
function uploadImage(userActionPath,type)
{
if( (userActionPath == 'undefined') || (type == 'undefined')) {
console.error("no parameters for function uploadImage defined");
}
if((base64code == 'undefined') || (base64code == null))
{
console.error("please select an image");
}
var xml = ( window.XMLHttpRequest ) ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
alert(base64code); //<- shows the base64 code, so its there
var params = userActionPath+"?imagebase64="+base64code+"&type="+type;
xml.open("POST",userActionPath,true);
xml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xml.onreadystatechange = function()
{
if( xml.readyState === 4 && xml.status === 200 )
{
var serverResponse = JSON.parse(xml.responseText);
switch(serverResponse.f)
{
case 0:
console.log('love sosa'); //<- I get the response
break;
}
}
};
xml.send(params);
}
The controller
class LiveuploadController extends Controller
{
/**
* #Route("/LiveUpload",name="fileLiveUpload")
* #Template()
*/
public function indexAction(Request $request)
{
//I have tried these but 'imagebase64' returns null
//returns null
$value = $request->request->get('imagebase64');
//returns null
$value = $request->query->get('imagebase64');
//returns null
$value = $this->get('request')->request->get('imagebase64');
$response = array('f'=>0,'base64'=>$value);
return new Response(json_encode($response));
}
}
The request headers also show that the variables are being sent.But both the type AND the imagebase64 variables return null on the controller
The problem is with the way that you have setup the XmlHttpRequest. You have set it up like it should be using GET, but when you want to POST, it is a bit different. Take a look at this question for more info on how to send a POST request. The quick and dirty of it is:
var xml = ( window.XMLHttpRequest ) ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
var params = "imagebase64="+base64code+"&type="+type;
xml.open("POST", userActionPath, true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.setRequestHeader("Content-length", params.length);
xml.setRequestHeader("Connection", "close");
xml.onreadystatechange = function()
{
if( xml.readyState === 4 && xml.status === 200 )
{
var serverResponse = JSON.parse(xml.responseText);
switch(serverResponse.f)
{
case 0:
console.log('love sosa'); //<- I get the response
break;
}
}
};
xml.send(params);
In your example code, you are setting the header to expect JSON, but your params are urlencoded. Setting the proper header should do the trick.
And in your controller, if you are using POST, then you should get the request variables like this:
// Use this for getting variables of POST requests
$value = $request->request->get('imagebase64');
// This is used for getting variables of GET requests
$value = $request->query->get('imagebase64');
This line of code in your JS:
xml.open("POST",userActionPath,true);
You are actually supplying userActionPath instead of params variable. It should be:
xml.open("POST",params,true);
As for the controller's code you should use:
$value = $request->query->get('imagebase64');
Hope this helps...
I am checking a country name already exist in my database i used callback but it doest not shoot any error
$this->form_validation->set_rules('country_name', 'Country Name',
'trim|required|xss_clean|callback_check_exist');
This is my controller function
function check_exist($country_name)
{
$this->countrymodel->country_exists($country_name);
}
and this is my model
function country_exists($key)
{
$this->db->where('country_name',$key);
$this->db->from($this->dbname);
$query = $this->db->get();
if ($query->num_rows()> 0){
return true;
}
else{
return false;
}
}
The callback function should return a value and set a message:
function check_exist($country_name)
{
if (!$this->countrymodel->country_exists($country_name)) {
$this->form_validation->set_message('check_exist', 'an error message');
return FALSE;
}
else {
return TRUE;
}
}
How to check if any of 4 fields I have is filled in? If any of them is filled in, then it's fine, if not, it's not.
$("#sendMsg").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
if(name == ""){
$("#errorMsg").show();
return false;
}
if(email == ""){
$("#errorMsg").show();
return false;
}
if(subject == ""){
$("#errorMsg2").show();
return false;
}
if(message == ""){
$("#errorMsg3").show();
return false;
}
});
if (document.getElementById("idfield1") === undefined)
{
// do noting
}
else
{
// do something
}