Using $.post with CodeIgniter URL issue - php

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.

Related

send data by Jquery ajax to same php

i need help because i'm stuck and don't know what's wrong ,i try to send user clicked button "id" to php to get related data from database in the same page
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
console.log(res, data);
},
error: function(err) {
alert(err);
}
});
});
the ajax print success in console log ,here is php code to get the value if clicked id
<?php
if(isset($_POST['ToEditId'])){
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
}
but nothing happen in php file !!
Which is the expected behaviour.
PHP is not dynamic. It doesn't "update".
PHP only runs once. This means that once your page is rendered, you cannot use PHP to change it again. You actually would have to use javascript to change the page, like so;
PHP side:
<?php
if(isset($_POST['ToEditId'])){
echo $_POST['ToEditId'];
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
die(); // prevent entire page from re-rendering again.
}
JS side:
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
//Add your PHP file's response to the body through javascript.
$('body').append(res);
},
error: function(err) {
alert(err);
}
});
});
As #IncredibleHat mentioned, you should make sure your page doesn't render any of its usual HTML, so it won't return the entire page back to your ajax call. So put the PHP all the way above your html!

How to access AJAX file from different folder in CodeIgniter

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);
}
});
}

Execute php using jquery post

I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard

Keep jQuery accordion state on postback with PHP

I am using jQuery UI's accordion as a subnav on a site I am building. The problem is that I haven't been able to find a good way to maintain state between pages. I'm wondering what the best way to do this is.
I've thought of storing the index of the accordion in the database, but that seems overly complicated for a problem like this. Is there a better way? Obviously cookies and session but that is equally complicated for just a subnav...any ideas?
EDIT: Here's my code
$.post(
accordion_ajax.ajaxurl,
{
type : 'GET',
action : 'accordion_ajax'
},
function(data){
$(".accordion-main").accordion('option', 'collapsible', true);
$(".accordion-main").accordion('option', 'active', 0);
// the accordion just does not work inside this ajax call, but if I put it outside the ajax call it works fine. Any thoughts?
}
);
$(".accordion-main").accordion({
change: function(event, ui){
$.post(
accordion_ajax.ajaxurl,
{
type : 'SET',
action : 'accordion_ajax',
data : $(".accordion-main").accordion('option', 'active')
}
);
}
});
Here's what I would do:
In the change() handler for the accordion, I would send the index of the current accordion section to the server via an AJAX call:
$( "#AccordionID" ).accordion({
change: function(event, ui) {
$.ajax({
type:'POST',
url: 'urlToPhpScript.php',
data:'function=setAccordion&selectedAccordionSection='+ $("#AccordionID").accordion('option', 'active')
});
}
});
On the server side I would store this value in the users session:
<?php
// urlToPhpScript.php
session_start();
if($_GET['function']=='getAccordion') {
if(isset($_SESSION['currentAccordion'])) {
return $_SESSION['currentAccordion'];
} else {
return 0;
}
}
if($_POST['function']=='setAccordion') {
$_SESSION['currentAccordion'] = $_POST['AccordionID'];
}
Then on each page load I would send an AJAX call to the server that would query the accordion section from the users session:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'urlToPhpScript.php',
data: 'function=getAccordion',
success: function(data) {
$('#AccordionID').accordion('activate', data);
}
});
});
This way it wouldn't matter how you're navigating from one page to the next, and you wouldn't need to worry about burying a 'currentAccordion' type hidden field on each page of your site.

Get only part of the message and reload only one div

this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');

Categories