I am trying to use checkbox with Ajax. Without Ajax I have handle it.
Here is my Jquery code
$("#skillcat").click(function(e) {
var submit_val = new Array();
e.preventDefault();
var ids = $('check_subjects input:checked')
.map(function(){
return this.value;
}).get();
$.ajax( {
type : "POST",
dataType : "json",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'each_category',
check_subjects : ids
},
success : function(data) {
alert(data);
$('#accordion').html(data);
}
});
});
Here is my php code where button and checkbox is generated in serverside
foreach($subjects as $key=> $data){
echo '<input type="checkbox" id="'. $data->id .'" value="'. $data->id .'" name="check_subjects[]"> '. $data->subject .'<br>';
}
Serverside I used to catch data from Post array
if(isset($_POST['check_subjects'])){
//var_dump(check_subjects);
$check_subjects = implode(',', $_POST['check_subjects']);
//echo '$check_subjects '. $check_subjects;
}
however when I run above codes, I notice that some data is sent to the server(via chrom developer tool). But I get null in alert box. I guess response is null becase data is not sent to server properly. I am not sure about the javasript code I use to passe the request to Ajax.
Can anybody explain where I have done the mistake?
It is expecting JSON and you are returning html. So make the dataType HTML or json encode your return...
Try this:
$("#skillcat").on('click', function (e) {
e.preventDefault();
var ids = [];
var $el = $('[name*=check_subjects]:checked'); //Get all checked Checkboxes
$el.each(function () {
ids.push($(this).attr('id')); //get the Id from each checkbox
});
$.ajax({
type: "POST",
dataType: "html",
url : "./wp-admin/admin-ajax.php",
data: {
action: 'each_category',
check_subjects: ids
},
success: function (data) {
alert(data);
$('#accordion').html(data);
}
});
});
Related
I want to display the values in datatable. How to retrieve the object value in ajax success function..
AJAX
$(function(){
$(document).on("click", "#submits", function(e) {
e.preventDefault();
var password = $("#password").val();
alert(password);
$.ajax({
type: "POST",
url: "db/add.php",
data: "password="+password,
success: function(results){
alert( "Data Saved: " + results );
var obj = JSON.parse(results);
}
});
e.preventDefault();
});
});
</script>
Perhaps you can try this -
$("#submits").bind("click", function(e) {
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "db/add.php",
data : "password="+password,
success : function(results) {
alert("Data Saved: "+results);
var userInfo = JSON.parse(results);
//Output the data to an HTML element - example...
$(".user-name").html(userInfo.patient_name);
}else{
console.log('No user info found');
}
},
error : function(a,b,c) {
console.log('There was an error getting user info.');
}
});
});
//HTML element for data
<p class="user-name"></p>
I've added an HTML element you can simply output the data to. Not sure how you'd like the data to be output but this is simply an example.
Just some quick notes on your code from your original post -
You must set the dataType to json when working with/parsing json. See Documentation.
Once you assign your data to a variable, you need to access that data by declaring the variable and then the data name, such as obj.patient_name.
I've done the best I can to help.
Good luck.
Try this code :
$(results.patient_password).each(function(i,v){
console.log(v.id);
});
use data-type:json,
in your jquery
I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});
I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.
I am learning Cakephp and I've been trying to delete multiple (checked) record using checkbox, but still not success. here's my jQuery :
var ids = [];
$(':checkbox:checked').each(function(index){
ids[index] = $(this).val();;
alert(ids[index]);
});
//alert(ids);
var formData = $(this).parents('form').serialize();
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data:"id="+ids,
success: function() {
alert('Record has been delete');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
and here is code in controller :
function multi_delete() {
$delrec=$_GET['id'];
//debuger::dump($del_rec);
foreach ($delrec as $id) {
$sql="DELETE FROM tickets where id=".$id;
$this->Ticket->query($sql);
};
}
anybody will help me please. thank
you could try a .join(',') on the array of IDs and then an explode() on the server side to get the array of IDs passed to the script.
e.g.
var idStr = ids.join(',');
pass it (idStr) to the ajax call
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: {id:idStr},
//more code cont.
on the server side:
$ids = explode(',',$_POST['ids']);
OR
check the jquery.param() function in the jquery docs. Apply and to the IDS array and then pass it to $.ajax({});
Note: You are using POST and not GET HTTP METHOD in the code you provided
use json encode and decode for serialized data transfer
Since JSON encoding is not supported in jQuery by default, download the JSON Plugin for jQuery.
Your javascript then becomes:
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: { records: $.toJSON(ids) },
success: function() {
alert('Records have been deleted.');
},
});
In the controller:
var $components = array('RequestHandler');
function multi_delete() {
if (!$this->RequestHandler->isAjax()) {
die();
}
$records = $_POST['records'];
if (version_compare(PHP_VERSION,"5.2","<")) {
require_once("./JSON.php"); //if php<5.2 need JSON class
$json = new Services_JSON();//instantiate new json object
$selectedRows = $json->decode(stripslashes($records));//decode the data from json format
} else {
$selectedRows = json_decode(stripslashes($records));//decode the data from json format
}
$this->Ticket->deleteAll(array('Ticket.id' => $selectedRows));
$total = $this->Ticket->getAffectedRows();
$success = ($total > 0) ? 'true' : 'false';
$this->set(compact('success', 'total'));
}
The RequestHandler component ensures that this is an AJAX request. This is optional.
The corresponding view:
<?php echo '({ "success": ' . $success . ', "total": ' . $total . '})'; ?>
Wish you luck!
currently I have following code:
home.php
<form name='myformname' id='myformid'>
<input type='text' name='mytext1' value='abc'>
<input type='text' name='mytext2' value='123'>
<input type='submit' value='Submit'>
</form>
<div id='textone'></div><div id='texttwo'></div>
_home.php
$arr = array( 'textone' => $_POST['mytext1'], 'texttwo' => $_POST['mytext2'] );
echo json_encode( $arr );
ajax.js
jQuery('#myformid').live('submit',function(event) {
$.ajax({
url: '_home.php',
type: 'POST',
data: $('#myformid').serialize(),
success: function( data ) {
// TODO: write code here to get json data and load DIVs instead of alert
alert(data);
}
});
return false;
});
Output on submit:
{"textone":"abc","texttwo":"123"}
Question
I want to load mytext1 value in textone DIV and mytext2 value in texttwo DIV using json data in _home.php
Hint: I am using this answer to do the same task on link click event. But how to do this on form submission ?
Thanks
You just wanna parse that JSON and set the divs to the values it contains right?
var divs = JSON.parse(data);
for (var div in divs) {
document.getElementById(div).innerHTML = divs[div];
}
(Previous poster's syntax is probably more like what you're after, and maybe is more cross-browser compatible, but doesn't include the JSON parsing.)
Since JSON is just a subset of JavaScript, you can just eval() it. JSON.parse() basically does that, but gives you assurances that if 'data' contains some nasty code instead of a simple object, it won't be evaluated.
In the success function
for (prop in data){
$('#' + prop).html(data[prop]);
}
Here is my complete JS solution:
jQuery('#myformid').live('submit',function(event) {
$.ajax({
url: '_home.php',
type: 'POST',
dataType: 'json',
data: $('#myformid').serialize(),
success: function( data ) {
for(var id in data) {
//jQuery('#' + id).html(data[id]); // This will also work
document.getElementById(id).innerHTML = data[id];
}
}
});
return false;
});