$.ajax({
type: "post",
url: "<?php echo site_url(); ?>/controller_d/login/admin_search_user",
cache: false,
data: $('#docContainer1').serialize(),
dataType:"JSON", //<----here
success: function(json){
var str= "<table><tr>";
$.each(json.query,function(i,v){
alert(v.uID); //gives U0016
alert(v.name); //gives saman
str+="<td>"+v.uID+"</td>";
str+="<td>"+v.name+"</td>";
})
str+="</tr></table">;
$("body").append(str);
}
I want to create a dynamic table using json object values it must create a table but this is not working it will says v.ID not define
row += "$('<td>').append("+dataString[i]+")";
or
var row = $('<tr>');
for(var i = 0; i < n; i++) {
row.append($('<td>').html(dataString[i]));
}
$('#results').append(row);
create a table on the layout (on html code) then inside this create a <tbody> tag. assign an ID, then on the success function of your jquery, use $("#*tbody ID*").html to assign the value on the tbody.
i've got this code on one of my projects. maybe you can use this as a reference (tblApproved is the id of the tbody):
function updateApprovedTable(){
// retrieve Unit Record
$.ajax({
type:'post',
url:'php/requests.php',
data:{mode:"getApproved"},
success:function(data){
$('#tblApproved').html(data);
}//success
});//ajax
}
can you please used this :
$.ajax({
type: "post",
url: "<?php echo site_url(); ?>/controller_d/login/admin_search_user",
cache: false,
data: $('#docContainer1').serialize(),
success: function(data){
$("body").append(data);
});
Also write your code for table create into this url "/controller_d/login/admin_search_user"
PHP Code
echo "<table>";
echo "<tr><td>content</td></tr>";
echo "<tr><td>content</td></tr>";
echo "<tr><td>content</td></tr>";
echo "</table>";
Related
I want to capture value keyed in textbox for quantity in the shopping cart while they type. I used jquery's key up for this.Then I want to save the new value in the session for quantity. I'm getting the value but unable to save it. It returns null after refreshing the page.
Html
<input type="text" size="4" class="qty" value="<?php echo $v['quantity'];?>" id="<?php echo $k;?>"/>
Ajax
$("input[class=qty]").keyup(function()
{
var data;
var newVal = $(this).val();
var id = this.id;
console.log(id+" "+newVal);
$.ajax({
type: "GET",
dataType: "text",
url: "updateCart.php?id="+id+"&&value"+newVal, //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
newVal=data;
}
});
});
updateCart.php
<?php
session_start();
$id = $_GET['id'];//say 2
$new_value =$_GET['value'];//say 16
foreach($_SESSION['cart'] as $k=>$v)
{
$k;
$v["id"];
$v["quantity"];
if($id == $k)
{
//assign new value to the quantity
$_SESSION['cart'][$id]['quantity']=$new_value;
//print_r($_SESSION['cart'][1]['quantity']);
}
}
//echo json_encode($new_value);
//var_dump($_SESSION['cart']);
this can display session['cart'] with updated value if I test in
this page ..but when passed to originated page via ajax, returns null.
echo $_SESSION['cart'][$id]['quantity'];
?>
You left out the = between &value and + newVal. But I recommend you let jQuery do this automatically by using the data: option.
data = { id: id, value: newVal };
$.ajax({
type: "GET",
dataType: "text",
url: "updateCart.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
newVal=data;
}
});
Below is the Jquery code
$("#state").change(function(){
$.ajax
({
url: "www.myweb.com/ajax.abc.php",
type: "POST",
data: {state: function(){return $("#state").val()}}; /* i have given stateId as value*/
cache: false,
success: function(html)
{
$('#city').find('option').remove().end().append(html);
}
});
below code is represented in the ajax file (i.e. ajax.abc.php)
if(isset($_POST['state']))
{
$getCity = mysql_query('SELECT * FROM tblCity WHERE stateId = '.$_POST['state']);
while($fetchCity = mysql_fetch_array($getCity))
{
echo '<option value="'.$fetchCity["cityName"].'">'.$fetchCity["cityName"].'</option>';
}
}
Break this line:
$('#city').find('option').remove().end().append(html);
Into two parts:
$('#city').find('option').remove();
$('#city').append(html);
Right now, you are removing an option, but then calling append on it, which obviously won't work.
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 have 2 selects on my HTML, the options are loaded via my database and the user can switch the options between the boxes, like so:
<select id="column1" multiple size="10" name="FromLB" style="width:150px">
<?php foreach ($result->result() as $row) { ?>
<option value="<?php echo $row->id ?>"><?php echo $row->title ?></option>
<?php } ?>
</select>
So far so good, the final plan is for the the user to click Submit and to have access to the data on these two selects in PHP (via an array).
After digging around for a bit, it seems like JSON is the way to go.
I import json.js to my project and get to work:
function sort_cols(){
var i=0;
var p=0;
var column1 = new Array();
var column2 = new Array();
$("#column1 option").each(function()
{
column1[i]=$(this).val();
i=i+1;
});
$("#column2 option").each(function()
{
column2[p]=$(this).val();
p=p+1;
});
JSON = JSON.stringify(column1);
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: JSON,
success: function(){
alert("Success!")
}
});
}
So far I'm only passing one array (for the first select column), but I'm getting an error:
Uncaught TypeError: Object ["15","14","1"] has no method 'stringify'
I've been following this answer:
How exactly do you use json_decode to pass a javascript array to php?
I'm wondering what am I doing wrong here, and how can I pass my second array (column2) as well?
In this line
JSON = JSON.stringify(column1);
you redefine the native JSON object. Use another name for your variable and you should be fine.
And as for submitting both arrays, just use an encapsulating object:
data2send = JSON.stringify( { 'column1': column1, 'column2': column2 } );
Besides instead of using an incrementing index to insert your data into the arrays, just use the native push() method.
There's some strange behaviour happening here, most likely caused by the fact your JSON variable is overwriting the browser's native JSON object (or the one provided by json.js in older browsers).
You can actually pass an object directly to $.ajax, so the following will work:
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: column1,
success: function(){
alert("Success!")
}
});
If you want to pass both columns as separate parameters, change it to:
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: {
first_column: column1,
second_column: column2
},
success: function(){
alert("Success!")
}
});
They will now be available in your PHP script as $_POST['first_column'] and $_POST['second_column'].
This way, you leave the heavy lifting of converting your objects to JSON to jQuery, so you don't need to include the json.js library at all.
Your full code, rewritten:
function sort_cols(){
var column1 = [],
column2 = [];
$("#column1 option").each(function() {
column1.push($(this).val());
});
$("#column2 option").each(function() {
column2.push($(this).val());
});
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: {
first_column: column1,
second_column: column2
},
success: function(){
alert("Success!")
}
});
}
Make jQuery do the heavy lifting:
function sort_cols(){
var col1 = [], col2 = [];
$("#column1 option").each(function() {
col1.push($(this).val());
});
$("#column2 option").each(function() {
col2.push($(this).val());
});
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
contentType: "application/json",
data: JSON.stringify({
column1: col1,
column2: col2
}),
success: function(){
alert("Success!")
}
});
}
My page consists of a list of records retrieved from a database and when you click on certain span elements it updates the database but at present this only works for the first record to be displayed.
(Basically changes a 0 to 1 and vice versa)
These are my two html elements on the page that are echoed out inside a loop:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
Here is what I have:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
It was working fine with one using id attributes but now I'm using class the fadeIn part of the success query isn't working but I'm hoping the .each will fix this.
UPDATE
The full loop is as follows:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
Cymen is right about the id selector causing you trouble. Also, I decided to refactor that for you. Might need some tweaks, but doesn't everything?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
The click function is getting the same id and value on each click because you've bound it to the class. Instead, you can take advantage of event.target assuming these values are on the item being clicked. If not, you need to use event.target and navigate to the items within the row.
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
So something like that but it likely won't work as it needs to be customized to your HTML.