How to access AJAX file from different folder in CodeIgniter - php

I have one form with Jquery validation which is working perfectly, Even AJAX is also working perfectly if I use my validation code with AJAX on the same page.
Now What I did, I create a file called as validation.js and I added my validation code with AJAX in it and I added a script like below in my view page.
<script type="text/javascript" src="<?php echo base_url() ?>js/validation.js"></script>
Then I clicked on submit button It's checked my validation even it also goes to AJAX URL which I entered but this time I haven't got output.
I am getting in Network tab in the browser my URL like this
<?php echo base_url("index.php/user_control/admin_submit_from"); ?>
I am using sublime text editor If I used above URL on the same page then the base_url color is showing in blue and If I used in validaion.js the color is showing in yellow.
Above URL Is not working from the validation.js file. Would you help me in this?
My Jquery validation with AJAX
$(document).ready(function() {
$("form[name='admin_form_submit']").validate({
rules: {
firstname: {
required: true,
minlength:3,
maxlength:50
},
lastname: {
required: true,
minlength:3,
maxlength:50
},
role:{
required: true
},
inst_name:{
required: true
}
},
submitHandler: function(form) {
//// form.submit();
$.ajax({
type: 'post',
url: '<?php echo base_url("index.php/user_control/admin_submit_from"); ?>',
data: $('form[name="admin_form_submit"]').serialize(),
success: function (data) {
alert(data);
}
});
}
})
});

The reason why the code worked in the first method was because it was included within a PHP file. Within a php file, you can embed HTML, CSS, JS, and that's why when you write something like this:
<script src='<?php echo $something; ?>'></script>
the value of that $something is echoed.
On the other hand, you cannot embed a php code inside a javascript file. The entire code will be treated as a string, and the reason why it is parsed that way.
So to solve you issue (if you still want to put your js in a separate file), one of the ways to do that is to add a hidden input with your desired value, in your form, and use js to get it.
In your form:
<input type="hidden" name="my_url" id="my_url" value="<?php echo base_url("index.php/user_control/admin_submit_from"); ?>">
Then you target it from your js file like so:
var myUrl = $('#my_url').val();
then update your ajax to:
$.ajax({
// other objects and properties
url: myUrl,
});

you can't execute php in a js file
create a global js variable in your php file with the url and reference that in your js file
index.php
<script>
var url = '<?php echo base_url("index.php/user_control/admin_submit_from"); ?>';
</script>
validation.js
$.ajax({
type: 'post',
url: url,
data: $('form[name="admin_form_submit"]').serialize(),
success: function (data) {
alert(data);
}
});
}

Related

PHP - Old session variable on previous page (IE works fine!)

I have a session variable $_SESSION['name']. I set in a php file which is called with ajax inside a keyup event. It works well. Until a user uses the previous page button.
When a user uses this button (or mouse button), the last set session variable value is basically not set. It will return to an older set value (the one before the last one). I wonder how/why and what I can do about it.
I've read quite a lot stackoverflow (and other) solutions, but nothing so far seems to work.
HTML:
if(isset($_SESSION['name'])) {
echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
}
<script type="text/javascript" defer>
$(function() {
var name = $('input[name="name"]').val();
$('input').on('keyup', function() {
$.ajax({
url: 'example.php?name=' + name,
type: 'GET',
dataType: 'json',
success: function(data) {
// blablabal more code
}
});
});
</script>
example.php:
$_SESSION['name'] = 'test';
Please note I'm starting the session on all of my pages with session_start(); and please note that I also tried to regenerate my session id with any hope that would do the trick.
You cannot achieve this you have to reload your page to see the changes.
although here is a suggestion to do this what you want to achieve.
if(isset($_SESSION['name'])) {
echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
}
<script type="text/javascript" defer>
$(function() {
var name = $('input[name="name"]').val();
$('input').on('keyup', function() {
$.ajax({
url: 'example.php?name=' + name,
type: 'GET',
dataType: 'json',
success: function(data) {
$("[name='name']").val('Your response');
}
});
});
By doing this you can achieve what you are looking for. also if you load the page it will get the value from session

Using $.post with CodeIgniter URL issue

I have one page in CodeIgniter with URL http://127.0.0.1/FOLDER/data/getList.
On that page, there is list of enteries. On that list, in every item there is a link on which by clicking I need to fetch some data using $.post jQuery.
I have used this code:
$(".class_name").click(function() {
$val = $(this).attr('val')
$.post("class/func", {val:$val}, function(data) {
alert(data);
});
});
The issue is with the URL to be used with $.post.
If I use, "/class/func", it sends the requsts to http://127.0.0.1/class/func (FOLDER is not getting in).
If I use, "class/func", it sends the request to
http://127.0.0.1/FOLDER/data/class/func (here data gets inserted which is class for the current page).
How should I resolve this error? Should I be using <?php echo base_url() ?>class/func; is it the correct way of doing it?
If your JavaScript code is between <script></script> in your view:
$.post("<?php echo site_url("class/func") ?>", {val:$val}, function(data) {
alert(data);
});
If your JavaScript is on a separate .js file:
In the footer of your page:
<script>var baseUrl = "<?php echo base_url() ?>";</script>
And then:
$.post(baseUrl + "index.php/class/func", {val:$val}, function(data) {
alert(data);
});
Alternative :
Set a data-attribute to your item
Go!
And then:
$.post($(this).data("ajaxurl"), {val:$val}, function(data) {
alert(data);
});
I had a separate js file from where I had to call the function in a controller "Verifypass.php". I had something like this in the $_post():
$.post( "verifypass", { pass: $("#password").val() }, function(data){
});
This did not work for me, So all I did was to add index.php at the beginning of the controller name as:
$.post( "index.php/verifypass", { pass: $("#password").val() }, function(data){
});
And it worked then.

load partial page using AJAX in PHP page

I'm trying to figure out how I can load a partial page (div) into another div using AJAX in my php page.
basically I have a div with some php output stuff, and I need to put that div's content into another one using ajax but my code doesn't do anything (it doesn't put the div's content into the other one).
this is my current code:
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({
type: "GET",
url: "<?php echo $actual_link; ?>",
dataType: "html",
success: function(response) {
// $("#ajaxContent").html(response);
$("#issomeone").html($(response).find("#notis"));
setTimeout(load, 4000);
}
});
}
load();
});
</script>
so the #notis div holds the php output and the #issomeone div is the div that i need to put the stuff in using ajax.
is there something missing in my code or I'm just doing it all wrong?
any help would be appreciated.
Thanks
EDIT:
THIS DOESN'T DO ANYTHING:
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({
type: "GET",
url: "<?php echo $actual_link; ?>",
dataType: "html",
success: function(response) {
// $("#ajaxContent").html(response);
//$("#issomeone").html($(response).find("#notis"));
$('#issomeone').load("<?php echo $actual_link; ?> #notis");
setTimeout(load, 4000);
}
});
}
load();
});
</script>
You are finding the DOM element and then trying to set that as target element's innerHTML with html(). You in essence have a type mismatch.
You would need to get the innnerHTML of #notis to pass as the parameter to this function so:
$("#issomeone").html($(response).find("#notis").html());
Alternately, you could append the node if you want to keep the whole #notis element
$("#issomeone").append($(response).find("#notis"));
But really, since you are using a straight GET, you might be better off simply doing:
$('#issomeone').load('<?php echo $actual_link; ?> #notis');
This provides a more simple abstraction to what you are trying to do more manually with .ajax()
I would however encourage you to not get in the habit of loading full HTML pages and then scraping them for some particular element. It is better design architecture to have the AJAX target script serve up only content that is needed when possible.

send data to a new window and use there [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Jquery post, response in new window
i have a table html in a page called results.php that looks like
GenID
ENSMUSG00000098791
ENSMUSG00000023441
ENSMUSG00000047431
results.php have this function
<script>
function contenidoCelda()
{
var table= $('#tabla_results');
cells = $('td');
for (var i=0,len=cells.length; i<len; i++)
{
cells[i].onclick = function()
{
var formData2 = new FormData(document.getElementById("formulario"));
formData2.append("gen_id",(this.innerHTML));
$.ajax({
type: "POST",
url: "test.php",
data: formData2,
cache: false,
processData: false,
contentType: false,
success: function(data)
{
alert(data);
window.open('test.php', '_blank');
}
});
}
}
}
</script>
i whant to use the data i send in the file test.php, not to return this to results.php, use in test.php, to generate the content dinamycally.
this is test.php
<?php
$data = $_POST['gen_id'];
system("mkdir $data");
echo "Hola";
echo $data;
echo '<xmp>';var_dump($data);echo '</xmp>';
?>
<html>
<link href="css/ui-lightness/jquery-ui-1.9.1.custom.css" rel="stylesheet">
<script src="js/jquery-1.8.2.js"></script>
<script src="js/jquery-ui-1.9.1.custom.js"></script>
<body>
<form>
<p id = "testing"> Test page </p>
<?php if($data == "ENSMUSG00000047751") {echo "Good";} else {echo "Bad";} ?>
</form>
</body>
so here in test.php, it must show Good, if i click that genid in the table
but it show Bad, and returns Good to results.php
the test where i create a dir, whit the genid i click works fine
what i must do?
In your $.ajax call, try setting:
$.ajax({
type: "POST",
url: "test.php",
data: "testing123",
cache: false,
processData: false,
contentType: false,
});
And see if dir test123 is created, and echoed back.
If not, then the problem is in these two lines, specifically with your definition of var formData2:
var formData2 = new FormData($('#formulario')[0]);
formData2.append("gen_id",(this.innerHTML));
Check for typing errors, such as the comma in place of the semi-colon:
var table = document.getElementById('tabla_results'), <-- THIS IS A COMMA. TYPO?
cells = table.getElementsByTagName('td');
Also, you have a mix of jQuery and javascript. Why not standardize on jQuery? For example, the two lines above would be written like this in jQuery:
var table = $('#tabla_results');
cells = $('td');
Much less typing, yes?
Also, I'm sure you have, but are you sure you've included a link to the jQuery library? Such as:
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
I think the problem is with the way you define formData2:
var formData2 = new FormData($('#formulario')[0]);
Resulting in formData2 not actually being FormData.
Try switching it to:
var formData2 = new FormData(document.getElementById("formulario"));
This should solve the data problem.
Edit: About the edit to your question, if you want to post the results to another page, there really is no need to use ajax. Just use javascript on form submit to add the additional field with the ID (if you cannot add it like a hidden field...) and use a normal form submit.

How load a PHP page in the same window in jQuery

I have a PHP file, Test.php, and it has two functions:
<?php
echo displayInfo();
echo displayDetails();
?>
JavaScript:
<html>
...
<script type="text/javascript">
$.ajax({
type:'POST',
url: 'display.php',
data:'id='+id ,
success: function(data){
$("#response").html(data);
}
});
</script>
...
<div id="response">
</div>
</html>
It returns the response from jQuery. The response shows as <a href=Another.php?>Link</a>. When I click the Another.php link in test.php, it loads in another window. But I need it to load the same <div> </div> area without changing the content of test.php, since it has displayInfo(), displayDetails(). Or is it possible to load a PHP page inside <div> </div> elements?
How can I tackle this problem?
If I understand correctly, you'd like for the a link to cancel navigation, but fire the AJAX function?
In that case:
$("#mylink").click(function() {
$.ajax({ type: "POST", url: "another.php", data: {id: "somedata"}, function(data) {
$("#response").html(data);
});
return false;
});
Krof is correct,
One possible unwanted behavior of this however is that it will query the data every time the link is clicked. You can set the event to only call the ajax query once by using one.
$("#mylink").one('click', function() {
// ajax call
return false;
});
Don't forget to set href="javascript:{}" in your link so after the event is fired once the link wont do anything;
You could just use MooTools and class Request.HTML.

Categories