Jquery ajax : dynamic success function - javascript

Hi i'm making a reusable javascript/ajax function used for validating input textboxes, checkboxes..etc. But I'm trying to create some sort of a generic validator using ajax. and so far i've managed to make my url and data dynamic by having this:
<?php
//contains php variables passed during after rendering the view
$url = //...some url;
$data = // array()... some array containing parameters;
$success = // should contain a string defining a function;
?>
So i get the needed php variables and pass them onto javascript, to use it into ajax like this :
<script>
$(document).ready(function(){
var submitUrl = '<?php echo Yii::app()->createAbsoluteUrl($url); ?>';
var params = <?php echo json_encode($data); ?>;
$.ajax({
url : submitUrl,
type : 'POST',
async : false,
data : params,
success : ??? // i don't know how to define this function dynamically based on php values
});
});
</script>
I don't know how to define success function dynamically. I tried defining :
var successFunction = <?php echo json_encode("function(response){ return 'sample response' ; }");?>;
but no luck. How do i put a success function dynamically from a string defining custom success function? Many thanks!
---------------------------------added-------------------------------------------
Practically i'm using X-edtiable extension.
$('.editable').editable({
type : editableType,
savenochange : true,
pk : 1,
emptytext: 'Click to edit',
params : function(){
return jsParameters;
},
url : submitUrl,
validate : validateFunction,
});
we use validate as :
validate : function(value){
//do some validation rules like if value < someValue or is a negative, or character
}
The problem is I've made the submitUrl dynamic, and editableType dynamic so far. but failed on the validate part. since I have a dynamic editable type. values could either be date, text, numbers, etc. And these have different validation rules, some may require another ajax call if i need to counter check something in the database. I was trying to make a validate function dynamic by basing it to some php variable passed onto the view after render, to see what validation rule is appropriate. Is this possible or am i making sci fi? Many Thanks!

There's no JSON encoding for functions. Use it for the data within the function body:
var successFunction = function(response) {
<?php switch($editableType) {
case 'date':
echo 'return response.test(dateRegexp);';
break;
case 'number':
echo 'return response.test(numberRegexp);'
break;
...
} ?>
};

you can use dataType: 'script;
<script>
$(document).ready(function(){
var submitUrl = '<?php echo Yii::app()->createAbsoluteUrl($url); ?>';
var params = <?php echo json_encode($data); ?>;
$.ajax({
url : submitUrl,
type : 'POST',
async : false,
data : params,
dataType: 'script'
});
});
</script>
https://api.jquery.com/jQuery.ajax/

Related

How to get one or two of data value in Controller Codeigniter when using AJAX Post

can someone help me with my code, i have AJAX json type POST and i wanto to get one or two of data send to controller in codeigniter, i wanto to add conditional function where the data from json.
My JSON
$('#add_people').submit(function(e){
e.preventDefault();
var id_people = $('#id_people').val();
var name_people = $('#name_people').val();
var phone_people = $('#phone_people').val();
$.ajax({
type : "POST",
url : "<?php echo base_url('add_people_data')?>",
dataType : "JSON",
data : {id_people:id_people , name_people:name_people, phone_people:phone_people},
success: function(data){
$("#show_people").html('<img src="assets/img/user/spinner.gif"> <h4>Loading data...</h4>');
$('#modal-add_people').modal('hide');
$('.modal-backdrop').remove();
$('[name="id_people"]').val("");
$('[name="name_people"]').val("");
$('[name="phone_people"]').val("");
var loadUrl = "<?php echo base_url('show-people-data')?>";
$("#show_people").load(loadUrl);
}
});
return false;
});
My Controler
public function add_people_data()
{
$id_people = $this->input->post('id_people');
$name_people = $this->input->post('name_people');
$phone_people = $this->input->post('phone_people');
$cekassignreviewer=$this->Model_reviewer->checkassignreviewer('data_people', $id_people, $name_people, $phone_people);
if ($cekassignreviewer > 0) {
$this->session->set_flashdata('failed',
"<script>swal({
title:'Failed!',
text: 'Number of people has been added',
icon: 'error',
confirmButtonText: 'Ok',
confirmButtonClass: 'btn btn-success'
});
</script>");
redirect(base_url('setting-reviewer'));
}else{
$data=$this->Model_reviewer->add_people();
echo json_encode($data);
}
My Model
function add_people()
{
$data = array(
'id_people' => $this->input->post('uniid_reviewer'),
'name_people' => $this->input->post('name_people'),
'phone_people' => $this->input->post('phone_people'),
);
$result=$this->db->insert('data_people',$data);
return $result;
}
Thank you in advance
IncomingRequest Class For CodeIgniter 4
If you are not within a controller, but still need access to the application’s Request object, you can get a copy of it through the Services class:
$request = \Config\Services::request();
With CodeIgniter’s built in methods you can simply do this:
$something = $request->getVar('foo');
The getVar() method will pull from $_REQUEST, so will return any data from $_GET, $_POST, or $_COOKIE. While this is convenient, you will often need to use a more specific method, like:
$request->getGet()
$request->getPost()
$request->getServer()
$request->getCookie()
In addition, there are a few utility methods for retrieving information from either $_GET or $_POST, while maintaining the ability to control the order you look for it:
$request->getPostGet() - checks $_POST first, then $_GET
$request->getGetPost() - checks $_GET first, then $_POST

Passing data with POST with AJAX

I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.

Pass JS var to PHP var

I need to have a "global" variable because I need to use it in different page and I want to modify it too: I think that I need to use $_SESSION
I need to change this variable, when the user click on dropdown or list.
I have this:
SOLUTION 1
PageA:
$('#list.test li').on('click',function(){
choice=$(this).attr('id');
$.ajax({
url: "PageB.php",
data: {word : choice},
dataType: "html",
success: function (data) {
$('#content_table').html(data);
}
});
});
PageB
session_start();
$_SESSION['b']=$_GET['word'];
echo $_SESSION['b']; // It works
PageC for verify the result
session_start();
echo $_SESSION['b']; // Error !!
In my PageC, I have an error ( Notice: Undefined index: b )
Is it possible to update session variable with ajax ?
SOLUTION 2
PageA: I want to passe the id JS var to PHP var
$('#list.test li').on('click',function(){
choice=$(this).attr('id');
<?php $_SESSION['b'] ?> = choice; //<--- it is possible ?
$.ajax({
url: "PageB.php",
data: {word : choice},
dataType: "html",
success: function (data) {
$('#content_table').html(data);
}
});
});
This solution doesn't work because AJAX and PHP are note in the same side (client/server).
Thank you
You can push data to cookies via JavaScript, smth like document.cookie = "key=value";
And receive it on back-end like $_COOKIE["key"];.
$_SESSION['b']=$_GET['projet']; should be $_SESSION['b']=$_GET['word'];

Getting PHP variable to jquery script file by AJAX call

So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
$('#results').html(data);
}
});
and it works fine by printing my results.
My php file is echoing data that should be printed in my results div.
Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??
Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.
<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>
And you could use those values accessing PHPVariables.VariableName1 on the javascript.
You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.
the explode function is used like this
explode('§', $somestringofinfoyouwanttoturnintoanarray);
you can then echo the relevent data like so
echo data[0];
which in this case wiill echo the text peiceofdata.
write this type of code in ajax file
var data =array('name'=>'steve', date=>'18-3-2014');
echo jsonencode(data);
//ajax call in this manner
$.ajax({
type: 'POST',
data: pass data array,
url: ajaxfile url,
success: function(data) {
var data = $.parseJSON(data);
$('#name').html(data.name);
$('#date').html(data.date);
}
});
Use json format, and in this json add your data variables :
PHP :
$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);
echo json_encode($arr);
Javascript :
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
data = JSON && JSON.parse(data) || $.parseJSON(data);
$('#results1').html(data.var1);
$('#results2').html(data.var2);
}
});

Ajax request in Codeigniter

I have been trying to create an ajax request in codeigniter. I've seen this question: Simple Ajax/Codeigniter request but I wasn't able to absorb that as there were the answers in which people were using PHP inside Javascript. I didn't know it was possible, however I gave that a try but it seems like the PHP wasn't being executed.
So here are my questions:
Is it really possible to use PHP inside Javascript, or am I mistaken?
What's the right way to perform an Ajax request in Codeigniter? What I've tried is the following:
var param = {name : event_name, date : event_date, time : event_time};
$.ajax({
// As seen from the question here at stackoverflow.
url : "<?php echo base_url('event/new_event'); ?>",
type : 'POST',
data : param,
beforeSend : function(){ },
success : function(){
alert("Event created! Feel free to add as much details as you want.");
namebox.val("");
$("#new-event-modal").find(".close").trigger('click');
window.location.href = "<php echo base_url('user/dashboard'); ?>";
},
complete : function(){ },
error : function(){ }
});
I know the possibility that I could hardcode the URL in the request but that wouldn't be a good practice!!
the easiest way for you to accomplish this is by using some jquery:
function getBaseUrl() {
var l = window.location;
var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
return base_url;
}
var postdata = {name : event_name, date : event_date, time : event_time};
var url = getBaseUrl()+"/event/new_event";
$.post(url, postdata, function(result){
...alert(result);
});
or call it straight from JS by caching it:
<script>
var test = "<?php echo base_url(); ?>"+"event/new_event";
alert(test);
</script>
Here is a dirty hack that I was going to use:
Create a hidden field somewhere on the page and when this page loads echo out the base_url() as the value of that hidden field.
Now when you want to make an ajax request, access that hidden field
and grab the base url and use it however you want.
The right way is always the simplest way, there is no need to import Jquery in your client if you are not already using it.
This is your controller
<?php if (!defined('BASEPATH')) die();
class Example_ctrl extends CI_Controller {
public function ajax_echo()
{
// get the ajax input
$input = json_decode(file_get_contents('php://input'));
// $input can be accessed like an object
$password = $input->password;
$name = $input->name;
// you can encode data back to JSON
$output = json_encode($input);
// and the response goes back!
echo($output);
}
}
?>
This goes into your client
<script>
// here's the data you will send
var my_data = {name: "Smith", password: "abc123"};
// create the request object
var xhr = new XMLHttpRequest();
// open the object to the required url
xhr.open("POST", "example_ctrl/ajax_echo", true);
// on success, alert the response
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200)
return;
alert("Success: " + xhr.responseText);
};
// encode in JSON and send the string
xhr.send(JSON.stringify(my_data));
</script>
There is no better way to do this .
Php codes can't be executed from external javascript files.
Try any of these :-
1) base_url() is something's that's will not change , better store it in cookie and then access it in both server side code and client side code
2) you can store the same base_url() in local storage , it will be available in your external JavaScript files
Hope it helps you :)

Categories

Resources