Am trying to load an external file to a div using this function
$(document).ready(function(){
$("#postdiv").load('posts.php');
});
This is working alright.
The problem is, I need to pass parameters/variables to posts.php from the caller page and use them to do some filtering.
How can i do this ?
You can pass parameters with jquery load
This method will pass parameter as POST
$("#postdiv").load('posts.php',{'name' : 'Test','age' : 25});
if you want pass it as GET you can do like this
$("#postdiv").load('posts.php?name=Test&age=25');
you can read more here
Use ajax
ajax is better option,best practice.
var value = "value of the data here";
$.ajax({
url: "posts.php",
data: "key="+value,
type: "post",
success: function(data){
$('#postdiv').html(data);
}
});
you can make an ajax call
$.ajax({
url: "posts.php",
data: data,
type: "post",
success: function(data){
$('#postdiv').html(data);
}
});
or you want to go for load then try below code
$( "#postdiv" ).load( "posts.php", { "test[]": [ "test1", "test2" ] } );
Related
I'll make it easy, I want to submit data without using a form, etc, etc, etc...
I have this code:
HTML
<span class="categ-edit">Edit</span>
<span class="categ-add">Add</span>
<span class="categ-delete">Delete</span>
JQUERY
$('.categ-edit').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'edit'},
});
window.location.href = "categoryactions.php";
});
$('.categ-add').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'add'},
});
window.location.href = "categoryactions.php";
});
$('.categ-delete').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'delete'},
});
window.location.href = "categoryactions.php";
});
And in categoryactions.php I have this:
PHP
<?php
$action = $_POST['action'];
echo $action;
?>
But when it redirects me to categoryactions.php I get nothing. I'm not sure if that's the way to submit data with AJAX but at least I tried. If someone knows how to fix this, I'll be grateful!
You click handler is making two separate requests. First, you are sending a request with AJAX, then you are going to the page. When you look at the page, you won't see the result because the result was given to the AJAX request.
The point of AJAX is to avoid changing the page.
Try this:
$('.categ-edit').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'edit'},
success: function(data) {
alert(data);
}
});
});
You are actually calling "categoryactions.php" twice. First as an asynchronous call (ajax) and the second time as a redirect: window.location.href = "categoryactions.php";
In the 2nd call, nothing is being posted so your output is empty. This line does not serve any purpose - you should remove it.
The ajax call happens in the background so you won't see the output from the echo in the browser. if you really want to verify it is working, replace the echo with a file call to write it to a file. Then check the file contents.
Using redirection with Ajax doesn't make sense. You need to use the success method.
$('.categ-delete').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'delete'},
success: function(data){
alert(data);
//or, put response in a div
$('#someDivId').html(data);
}
});
});
The point of Ajax is to retrieve the response from a request to another page without changing the URL in the address bar. It retrieves the response for you in the variable that is the input to your success method, and then you do something with that.
Example AJAX with PHP
I can't exactly answer your question, but I will help you understand ajax requests to http server and how to handle responses accordingly.
Sample jQuery
$('.categ-edit').click(function() {
$.get('/path/to/file.php', function(data) {
console.log(data);
});
});
Sample file.php
<?php
echo json_encode('HELLO');
Any idea why this doesn't work? I have tried to see if the button clicked actually works with alerts, had alerts as well as before and after the ajax code and they both worked.
var selectedCheckboxes = "12421";
jQuery(document).ready(function($){
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: { selectedCheckboxes: "selectedCheckboxes" },
success: function(response){
//do action
},
error: function(){
// do action
}
});
});
});
the link:
Edit
test.php
<?php
echo $_POST["selectedCheckboxes"];
?>
Try this instead:
Edit
If you want the output of the php in your page you have to do something like this in your javascsript
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: { selectedCheckboxes: selectedCheckboxes },
success: function(response){
$("body").html(response);
},
error: function(){
// do action
}
});
});
You may need to change the "body" tag.. or not
depends on what the teste.php returns
Well, if you don't want the output to be placed inside your current page html, maybe a different aproach would be better.
Maybe there are better answers but you could try something like:
<form method="post" action="test.php" onsubmit="javascript:$('#selectedCheckboxes').val(selectedCheckboxes);">
<input type="hidden" value="" name="selectedCheckboxes" id="selectedCheckboxes">
<input type="submit" value="Edit">
</form>
You would have to style the submit input
Does the idea help? No ajax though.
The reason you're not seeing the AJAX reqeust go through is because when the you click on the anchor tag, the browser is performing the default action of navigating to 'test.php', which cancels the AJAX call. Since you are simply GET'ing that page, and not POST'ing to it, there is nothing in $_POST. In order to prevent this default action, either use a span instead of an a tag (recommended), or prevent the default action, doing something like this:
Edit
If I get you right, you want to pass selectedCheckboxes as JSON to the Server. In this case you need to actually pass your selectedCheckboxes variable to the Server.
Like this:
$.ajax({
url: "test.php",
type: "POST",
data: selectedCheckboxes,
success: function(response){
//do action
},
error: function(){
// do action
}
});
The problem with your code is that you passed a new JSONObject containing a String that contains "selectedCheckboxes". You did not pass the actual variable.
Put a return false; after ajax call
You try to pass a variable selectedCheckboxes but unfortunately with double ("") quotes you passing a string as selectedCheckboxes
Use below code
var selectedCheckboxes = "12421";
var dataObject = {};
data[selectedCheckboxes] = 1;
jQuery(document).ready(function($){
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: dataObject ,
success: function(response){
//do action
},
error: function(){
// do action
}
});
});
});
Hope this helps...
i am trying to submit a php form through ajax, my jquery code is
$("#editContraForm").submit(function editContra (e) {
e.preventDefault();
dataString = $("#editContraForm").serialize();
$.ajax({
type: "POST",
url: "./validations/contraAjax.php",
data: dataString,
action : "edit",
dataType: "text",
success: function(data) {
console.debug("success : "+data);
},
error : function(error){
console.debug("erro");
}
});
});
and php code is (contraAjax.php)
if(!isset($_SESSION))
session_start();
include_once '../connect/connectOpen.php';
$action=isset($_REQUEST['action'])?$_REQUEST['action']:'';
if($action=="edit"){
echo 'good';
}
and the call is successfule (as shown in firbug) but console prints 'success: ', means data is null. What is wrong with this code, Kindly help me
You should not serialize data, but pass an object.
See jQuery documentation: http://api.jquery.com/jQuery.ajax/
use action as a parameter and then access it using $_POST['action'].
also try to var_dump($_POST['action']);
To add an action parameter just concatenate it into the data string.
data: dataString + '&action=edit',
I am new to codeigniter and cannot get my ajax to work.
I am trying to make links load content into the main document on click.
I looked for instructions but could not figure it out. All works except the ajax returns alert('ERROR') message. nothing is loadded into <div id='load_here'></div>
Maybe I am missing something in config.php? Do i have to load some library for this to work?
Any ideas would be helpfull
//main document link
<span id='reg_link_rules'>Link</span>
<div id='load_here'></div>
// controller
class Register extends CI_Controller {
public function hello()
{
echo 'hello';
}
}
// jQuery
$(document).ready(function() {
$('#reg_link_rules').click(function(eve){
$.ajax({
type: "GET",
url: "register/hello",
complete: function(data){
$('#load_here').html(data);
},
error: function(){alert('error');}
});
});
});
I think the problem is that the ajax url does not access the controller.
Z:/home/codeigniter/www/register/test this is where i think it takes me
problem solved, the url needed to be http://codeigniter/index.php/register/hello
Try with url: "/register/hello".
Might do the trick.
Usually I do a
<script type="text/javascript">
base_url = '<?=base_url()?>';
</script>
At the beginning of my page and simply
base_url+"register/hello"
instead
That makes my ajax more reliable, even when / is incorrect.
complete: function(data){
$('#load_here').html(data);
},
should be
Just referencing another SO question ... Use success() or complete() in AJAX call
success: function(data){
$('#load_here').html(data);
},
AND
$.ajax({
type: "GET",
Should be
unless you want your form vars to be submitted along in the URL.
$.ajax({
type: "POST",
Hello You should add the base url to the URL Ajax.
$.ajax({
type: "GET",
url: <?php echo base_url();?>"register/hello",
complete: function(data){
$('#load_here').html(data);
},
Remember enable the helper URL in the Controller!
Cheers
you need to pass the bas_url to ajax file
<script type="text/javascript">
$(document).ready(function(e) {
var baseurl = <?php echo base_url();?>
$('#reg_link_rules').click(function(){
$.ajax({
url : baseurl+'index.php/register/hello',
data : '',
type: "POST",
success : function(){
}
})
return false;
})
});
</script>
Sometimes you have do add index.php to the string. Like so:
$.ajax({
type: "GET",
url: <?php echo base_url();?>"index.php/register/hello",
complete: function(data){
$('#load_here').html(data);
},
But it's all about your config file however. It was the mistake in my case.
Hope it helps.
You need to ensure two matter
please put your ajax part as url: ?php echo base_url();?>"register/hello", and type: "GET", and also need to check wheter it is routed the url on config/routes.php.
When i submit a jquery ajax request without the data value, it works, when i submit it with the data value, nothing happens. I check if it works using firebug. I think its a simple mistake but i cant seem to figure it out. Please Help.
Here is the Jquery Code
var inputString = $("something").val();
var suggestions = $.ajax({
url: "temp.php",
type: "POST",
data: {valueInput : inputString},
dataType: "html"
});
temp.php just has some simple code since I'm testing:
echo "We got sumn here";
another thing is the suggestions variable is empty, any ideas?
You can try:
data: 'valueInput=' + encodeURIComponent(inputString),
Update
suggestions is being set to the jqXHR object returned from the $.ajax() function. If you want to do work on the server-response then you need to set a success callback somehow. Here are two ways:
var inputString = $("something").val();
$.ajax({
url : "temp.php",
type : "POST",
data : 'valueInput=' + encodeURIComponent(inputString),
dataType : "html",
success : function (serverResponse) {
//you can now do work on the server-response, it's stored in the serverResponse variable
alert(serverResponse);
}
});
OR
var inputString = $("something").val(),
suggestions = $.ajax({
url : "temp.php",
type : "POST",
data : 'valueInput=' + encodeURIComponent(inputString),
dataType : "html"
});
$.when(suggestions).then(function () {
//this is your callback function
});
I suggest the first method, the second is more advanced and is really only helpful if you want to wait for a set of AJAX requests to complete before doing something.
valueInput should be in quotes as it's a name. 'valueInput'
var inputString = $("something").val();
var suggestions = $.ajax({
url: "temp.php",
type: "POST",
data: {'valueInput': inputString},
dataType: "html"
});
You need to pass data in a form of query string. It should be something like a=1&b=2&c=3&d=4&e=5
You can use .serialize() method over jQuery object that has selected form elements or form tag. So, maybe this code shall be helpful.
var suggestions = $.ajax({
url: "temp.php",
type: "POST",
data: $("something").serialize(),
dataType: "html"
});
You can try
data: JSON.stringify({'valueInput': inputString}),
in you data parameter.