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...
Related
First of all, sorry if this is a duplicate. I've looked and seen some solutions but none worked. I've been trying to do this simple thing for like 3 hours with no result.
I'd have this html:
<form method="post" action="?c=Logo&action=save" id="form">
<!-- some inputs -->
<img src="" data-filename="new-logo.png">
<input type="submit" value="submit">
</form>
Here I'd like to modify the form so my php file will recognise $_POST['new-logo'].
// $_POST['new-logo'] = $('img').data('filename')
$logo = new Logo($_POST['new-logo']);
$logo->save();
I guess I should use the jQuery function $.post() but somehow I can't manage. Thank you all for your help :-)
SOLUTION
Finally since I found a very simple solution. Since I want my data to be processed in my php file, I simply added an <input type="hidden"> and modified its value with JS :-)
You could also make the data array from scratch like this:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: {key1:"value", key2:"value2"},
dataType: "json",
success: function(data) {
//do success stuff here
},
error: function() {
//do error stuff here.
}
});
});
You can add it as a hidden input.
$("#form").submit(function() {
$(this).append($("<input>", {
type: "hidden",
name: "new-logo",
value: $(this).find("img").data("filename")
});
});
you can add this to you're post request like this :
$('#form').on('submit', function(e){
e.preventDefault();
var $form = $(this);
var datastring = $form.serializeArray();
datastring.push({name:'new-logo', value:$form.find('img').data('filename')});
$.ajax({
type: "POST",
url: $form.attr('action'),
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
});
$logo = new Logo($_POST['new-logo']);
Is "new Logo" a function or something? Pretty sure that can't have a space.
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');
I am creating a chat system. I am sending a form data through ajax method in jquery. My first problem is ajax method is not sending data to proccess.php and page goes to redirect to its self.
<div id="chatOutput"></div>
<form id="myform">
<textarea id="chatInput" name="chatInput"></textarea>
<input type="submit" id="send" name="send" value="send" />
</form>
and script is :
$('#send').click(function () {
$('#myform').submit();
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data: $('#myform').serialize(),
success: function () {
alert("Submitted!"); // for testing
}
});
return false;
});
but script is not working and page goes to refresh and i see the variables and its values in the address bar like get method.
if this problem goes to solve, process.php will create a chat.txt and append data from #chatInput into it. and then will append chat.txt 's data to #chatOutput.
After appending data, div#chatOutput 's size goes to change. I want to fixed/specified width and height of this div. After the fixing size, how to scroll to bottom to see the last chatting?
The problem is here:
$('#myform').submit();
The simulates the "Submit" button click event
You can just do :
$('#myform').submit(function() {
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data: $('#myform').serialize(),
success: function() {
alert("Submitted!"); // for testing
}
});
return false;
});
You used $('#myform').submit(); which just submits the form in the normal way and thus ignoring the ajax etc after that.
Also, put this code either after the form itself or within $(function(){ ... });
EDIT
You had a syntax error. Make sure u have e.preventDefault(); as the first thing in your event click function. Then the default action will be prevented even when an error occurs later on.
$('#send').click( function(e) {
e.preventDefault(); //disable default action
$('#myform').submit();
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data: $('#myform').serialize(),
success: function() {
alert("Submitted!"); // for testing
}
});
});
return false; //return something
});
Remove the line:
$('#myform').submit();
It is submitting the form before your ajax call is made.
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.