Code igniter show div else show a different div in a view - php

I want to set a divs in conditions IN my View but I don't know how to I do it.If the request from controller comes true to him then success div appear otherwise failure div. At the time I am just printing true and false in alert boxes.
Here is my View:
<div class = "success">operation done successfully </div>
<div class = "failiour">operation done successfully </div>
//these are the two divs on which i want to apply a condition
<form>
</form>
<script type="text/javascript">
$('#btn').click(function() { // $("#form").serialize()
var item_name = $('#item_name').val();
var cat_id = $('#selsear').val();
if (!item_name || item_name == 'Name') {
alert('Please enter Category Name');
return false;
}
var form_data = {
item_name: $('#item_name').val(),
cat_id: $('#selsear').val(),
};
$.ajax({
url: "<?php echo site_url('itemsController/additems'); ?>",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1)
{
alert(true);
}
else{
alert(false);
}
}
});
return false;
});
</script>
my controller
function additems(){
//getting parameters from view
$data = array(
'item_name' => $this->input->post('item_name'),
'cat_id' => $this->input->post('cat_id')
);
//$is_ajax = $this->input->post('ajax'); //or use this line
//$this->input->is_ajax_request();
$result = array();
$this->load->model('itemsModel');
$query = $this->itemsModel->addItemstoDB($data);
if ($query){ //&& any other condition
$result['res'] = 1;//process successful - replace 1 with any message
}
else
{
$result['res'] = 0;//process failed - replace 0 with any message
}
echo json_encode($result);//at the end of the function.
}
}

Set display none through css in your both success and failure div and then do this :
$.ajax({
url: "",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1)
{
$(".success").fadeIn(500).delay(2000).fadeOut(500);
}
else
{
$(".failiour").fadeIn(500).delay(2000).fadeOut(500);
}
}
});

first hide your divs
<div class = "success" style="display:none;">operation done successfully </div>
<div class = "failiour" style="display:none;">operation done successfully </div>
then if you are get reuests multiple times
$.ajax({
url: "",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1)
{
$(".success").show();
$(".failiour").hide();
}
else
{
$(".failiour").show();
$(".success").hide();
}
}
});

In your script,
//supposing you are getting the result in response varible
if(response == true) // simply write: if(response)
{
document.getElementById('success').style.display='block';
document.getElementById('failure').style.display='none';
}
else
{
document.getElementById('success').style.display='none';
document.getElementById('failure').style.display='block';
}
//Add IDs to divs and add style block/none according to your requirement
<div id="success" style="display:block;"></div>
<div id="failure" style="display:none;"></div>

Related

jquery passing variable to php

when i try get and echo the variable on php, sending by ajax, i receive always var_dump null
the alert is ok, he shows the current slide id number when <a>(role=button) prev or next is clicked: 1 on slide 1, 2 on 2, 3 on 3;
<script>
$("#myCarousel").on('slide.bs.carousel', function(e) {
var value1 = $(this).find('.carousel-item.active').attr('id');
alert(value1);
var value = {
idCarrosselAtivo: $(this).find('.carousel-item.active').attr('id')
}
$.ajax({
type: "POST",
url: "teste.php",
data: value,
success: function(data) {
console.log(data);
}
});
})
</script>
<?php
if(isset($_POST['idCarrosselAtivo'])&& $_POST['idCarrosselAtivo'] === 'c1') {
echo $idCarrossel;
} else {
var_dump($idCarrossel);
}
?>
Consider this example.
jQuery
$("#myCarousel").on('slide.bs.carousel', function(e) {
console.log("Sending ", $(this).find('.carousel-item.active').attr('id'));
$.ajax({
type: "POST",
url: "teste.php",
data: {
idCarrosselAtivo: $(this).find('.carousel-item.active').attr('id')
},
success: function(data) {
console.log(data);
}
});
});
PHP
<?php
if(isset($_POST['idCarrosselAtivo'])){
$idCarrossel = $_POST['idCarrosselAtivo'];
if($idCarrossel === 'c1') {
echo $idCarrossel;
} else {
var_dump($_POST['idCarrosselAtivo']);
}
}
?>
It's not clear why you are sending back the ID when you just sent it to the script. This will send the ID and get some PHP back.

using ajax from a php function

I am new with ajax. I have this php function already from functions.php
function checkUserEmailExistent($email){
...
return $boolean;
}
and this is for my views views.html
<input type='text' name='email' id='email'>
this is for the script.js
jQuery( "#email" ).blur(function() {
jQuery.ajax({
type: 'POST',
url: 'url',
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(result){
}
});
});
my issue is how can I call my php function in ajax to connect it to my html. when it blur it check the email value if it is exist or not.
work in WordPress
JS SCRIPT
jQuery( "#email" ).blur(function() {
jQuery.ajax(
{
url: ajax_url,
type: "POST",
dataType: "json",
data: {
action: 'checkUserEmailExistent',
email: $(this).val(),
},
async: false,
success: function (data)
{
if (data.validation == 'true')
jQuery('.email-massage').html('<div class="alert alert-success">×<strong>Success!</strong> successfully</div>');
else
jQuery('.email-massage').html('<div class="alert alert-danger">×<strong>Oops!</strong> Something went wrong.</div>');
},
error: function (jqXHR, textStatus, errorThrown)
{
jQuery('.email-massage').html('<div class="alert alert-danger">×<strong>Oops!</strong> Something went wrong.</div>');
}
});
});
WP SCRIPT in functions.php
add_action('wp_ajax_checkUserEmailExistent', 'checkUserEmailExistent');
add_action('wp_ajax_nopriv_checkUserEmailExistent', 'checkUserEmailExistent');
function checkUserEmailExistent() {
$email = $_POST['email']; // get email val
/*if() your condition
$email = 1;
else
$email = 0;
*/
if ($email == 1):
$email_val= 'true';
else:
$email_val = 'false';
endif;
echo json_encode(array("validation" => $email_val));
die;
}
in function.php Enqueue file after add this code like this
wp_enqueue_script('themeslug-default', get_template_directory_uri() . '/js/default.js', array('jquery'));
wp_localize_script('themeslug-default', 'ajax_url', admin_url('admin-ajax.php'));
Set url to the php file where you have checkUserEmailExistent function. Then:
function checkUserEmailExistent($email){
...
return $boolean;
}
return checkUserEmailExistent($_REQUEST['value']);
I give the example for validation.This will help you to check
Email id<input type="text" name="email" id="email" size=18 maxlength=50 onblur="javascript:myFunction(this.value)">
You need to add the script
<script>
function myFunction(em) {
if(em!='')
{
var x = document.getElementById("email").value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
document.getElementById("email").value = "";
return false;
exit();
}
var email=$("#email").val();
$.ajax({
type:'post',
url:'email_client.php',
data:{email: email},
success:function(msg){
if (msg.length> 0) {
alert(msg);
document.getElementById("email").value = "";
}
}
});
} }
</script>
Create a page 'email_client.php' and add the code
<?php
$s=$_POST['email'];
include "config.php";
$echeck="select email from client where active=0 and email='".$_POST['email']."'"; //change your query as you needed
$echk=mysql_query($echeck);
$ecount=mysql_num_rows($echk);
if($ecount>='1' && $s!='0')
{
echo "Email already exists";
}
?>
You would call it in your url parameter. However, you'll need to manage your AJAX handler in the PHP script.
AJAX
jQuery( "#email" ).blur(function() {
jQuery.ajax({
type: 'POST',
url: 'functions.php',
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(result){
if (result.success) {
//handle success//
} else if (result.failure) {
//handle failure//
}
}
});
});
PHP
function checkUserEmailExistent($email){
...
return $boolean;
}
if ($_POST['value']) {
$status = checkUserEmailExistent($email);
if ($status === true) {
echo json_encode (array('status' => 'success'));
} elseif ($status === false) {
echo json_encode (array('status' => 'failure'));
}
}
you don't call your server function inside Ajax you only send your data in JSON format to the server on getting this data,server will route(if MVC) it to specific function and return a response to client in JSON format so now inside Ajax you perform operation on success (what to do next ) and in case of failure show the error
How server will route it to specific function that depend on framework you use, but i think they simply use regexp to match with URL

How to use JSON in Yii

I want to send/get a variable to/from controller action. My codes:
view file
....
<button id="radiyo">radio</button>
<script>
$("#radiyo").on("click", function(){
var $radio = $('input[type=radio][name=siniflerin-siyahisi]:checked').attr('id');
$.ajax({
type: 'POST',
url: '<?=Yii::app()->baseUrl;?>/ideyalar/sech/radio',
async: false,
cache: false,
data: {radio: $radio},
// datatype: "html",
success:function(){
alert($radio);
}
});
$.ajax({
type: 'GET',
url: '<?=Yii::app()->baseUrl;?>/ideyalar/sech/radio',
async: false,
cache: false,
datatype: "json",
data: {change: $sql},
success: function(data) {
alert(data.change);
}
});
});
</script>
....
controller action
public function actionSech ($radio)
{
$sql = Yii::app()->db->createCommand()
->select ('m.maraq')
->from ('maraq m')
->where ('m.idsinif=:ids', [':ids'=>$radio])
->queryAll();
$gonderilen = CJSON::encode(['change'=>$sql]);
}
I read articles from Yii offical site and other forums. But I couldn't understand how can I do it.
Please tell me, how can I send $sql variable to my view file?
Thanks.
I'm not pretty sure what you want. But, I want to pointing out some snippet.
In view file
<?php
Yii::app()->clientScript->registerScript("header-info","
var baseUrl = '".Yii::app()->baseUrl;."';
",CClientScript::POS_HEAD);
?>
<button id="radiyo">radio</button>
<script>
$("#radiyo").on("click", function(){
var radioValue = $('input[type=radio][name=siniflerin-siyahisi]:checked').attr('id');
$.ajax({
url: baseUrl +'/ideyalar/sech',
dataType:'json',
type:'POST',
data:{radioValue:radioValue},
async:false
}).done(function(data){
if(data['status'] == 'OK'){
alert(data['returnValue']);
}else if(data['status'] == 'ERROR'){
alert("HERE WE GO ERROR");
}
});
});
</script>
Your controller action;
public function actionSech()
{
//In my point, I never call db layer in controller. Controller should be routing purpose
If(Yii::app()->request->isAjaxRequest){
$radioValue = isset($_REQUEST['radioValue']) ? $_REQUEST['radioValue'] : "";
$returnObj = array();
if($radioValue !=""){
$query = "SELECT `maraq` FROM maraq WHERE idsinif='$radionValue'";
$result = Yii::app()->db->createCommand($query)->queryScalar();
if($result != "" || $result != null){ //ensure result is correct or not
$returnObj['returnValue'] = $result;
$returnObj['status'] = 'OK';
}else{
$returnObj['status'] = 'ERROR';
}
}else{ //if radiovalue is blank string
$returnObj['status'] = 'ERROR';
}
echo json_encode($returnObj);
}
}
Hope this help! Btw, JavaScript variable can't not initialize with $. Just only var yourVar="";

Returning json_encode as array not working

Here is my button
$( "#editVehicle" ).button().click(function( event ) {
event.preventDefault();
var vp = $("input[name=vehicle_plate]").val(),
dataString = 'vehicle_plate='+ vp;
$.ajax({
type: "POST",
url: "editvehicle.php",
data: dataString,
dataType: "json",
success: function(data){
if(!data.error && data.success) {
$("input[name=vehicle_model]").val(data.vehicleName);
$("input[name=assigned_driver]").val(data.assignedDriver);
} else {
alert(data.errorMsg);
}
}
});
});
And here is my PHP
<?PHP
include("db.classes.php");
$g = new DB();
$g->connection();
if($_POST) {
$vehiclePlate = $g->clean($_POST["vehicle_plate"],1);
$g->edit($vehiclePlate);
}
$g->close();
?>
and here is my db.classes
public function edit($vehiclePlate)
{
$sql = "select vehicle_name, driver_id from vehicles where vehicle_plate='$vehiclePlate'";
$result = mysql_query($sql) or die(json_encode(array("error" => 0, "errorMsg" => "MySQL query failed.")));
$row = mysql_fetch_array($result);
if(mysql_num_rows($row)) {
echo json_encode(array(
"success" => 1,
"vehicleName" => $row['vehicle_name'],
"assignedDriver" => $row['driver_id']
));
}
else {
echo json_encode(array(
"error" => 1,
"errorMsg" => "No rows returned"
));
}
}
button tag
<button type="submit" id="editVehicle" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
<span class="ui-button-text">Edit</span>
</button>
There is an input field in my html where i input the vehicle plate then when the user clicks the button the program searches the database for the vehicle name and driver_id with the plate the user entered and returns the value to another inputfield named "vehicle_name" and "assigned_driver" but nothing is happening when the button is clicked not even the error alert message. Any idea on where am i going wrong here?
The error is here -
if(!data.error && data.success) {
You are returning only either succcess or error but not both simultaneously, so the condition is always false.
Either return both or check of undefined property error and success before the condition like -
if ((typeof data.error != 'undefined' && !data.error) || (typeof data.success != 'undefined' && data.success))
And since you are returning error separately then you don't need to check with if, you can also try this and probably the better solution-
$.ajax({
type: "POST",
url: "editvehicle.php",
data: dataString,
dataType: "json",
success: function(data){
$("input[name=vehicle_model]").val(data.vehicleName);
$("input[name=assigned_driver]").val(data.assignedDriver);
},
error: function(data){
alert(data.errorMsg);
}
});
});

Pass a value from controller JSON to view Ajax in CodeIgniter

The problem is I am getting the dialog box of false but the query is running fine and values are successfully added into the database. It should print true, but it is giving me a false. I checked through Firebug also the value res = 1 is going, but I don't know what is wrong in it.
My View:
$.ajax({
url: "<?php echo site_url('itemsController/additems'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
if(msg.res == 1)
{
alert(true);
}
else
{
alert(false);
}
}
});
Controller:
$result = array();
$this->load->model('itemsModel');
$query = $this->itemsModel->addItemstoDB($data);
if ($query){ //&& any other condition
$result['res'] = 1;
}
else
{
$result['res'] = 0;
}
echo json_encode($result); //At the end of the function.
}
}
Try setting your dataType to json so the data sent back from the server gets parsed as JSON.
$.ajax({
url: "<?php echo site_url('itemsController/additems'); ?>",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1) {
alert(true);
}
else
{
alert(false);
}
}
});
Notice return.
if ($query){
$result['res'] = 1;
}
else
{
$result['res'] = 0;
}
return json_encode($result);//at the end of the function.
}

Categories