Multiple deletion in flexigrid - php

I'm unable to do multiple deletion when I try something on my own and single delete is working but multiple delete is not working need help!
// Flexigrid
if (com=='Delete')
{
if($('.trSelected').length>0){
if(confirm('Delete ' + $('.trSelected').length + ' rows?')){
var items = parseInt($('.trSelected').text(),10);
var itemlist =items;
for(i=0;i<items.length;i++){
itemlist+= items[i].id.substr(3)+" "; //its contains no value for multiple delete
}
$.ajax({
type: "POST",
dataType: "json",
url: "delete.php",
data: "items="+itemlist,
success: function(data){
alert("Query: "+data.query+" - Total affected rows: "+data.total);
$("#flex1").flexReload();
}
});
}
} else {
return false;
}
}

This is the problem:
var items = parseInt($('.trSelected').text(),10);
var itemlist =items;
for(i=0;i<items.length;i++){
itemlist+= items[i].id.substr(3)+" "; //its contains no value for multiple delete
}
Whenever there are multiple items, you cannot call parseInt() on the jQuery collection, as it doesn't know what to do with it. Instead, you can map the selection into a list of parsed .text() values, e.g.
$('.trSelected').map(function(index, item) {
return parseInt($(item).text(), 10);
}
This will turn a group of elements into an array of numbers. But then you cannot use it in the item list in the next for loop. So instead you need to simplify the logic, instead of returning the parsed int list, just return the id as you require it processed. e.g.
$('.trSelected').map(function(index, item) {
return item.id.substr(3);
}
Just be careful with the map, if you want to treat the item as a regular DOM element, use item, but if you need jQuery stuff like .css() you need to wrap item in $. i.e. $(item). Alternatively you can use $(this) to refer to the current item, which will likely be faster.
Good luck!

Related

Multidimensional PHP array to jQuery - Only seeing one result

I'm trying to use PHP and jQuery to create a dynamic search results page.
On the PHP side, a SELECT statement is called, where I check if all variables are set, add my HTML that I want to be used clientside, then put the variables in an array named $result.
Of the results of the database call, I also add the longitude and latitude in their own array, named $pins.
I then create a multidimensional array called $results, and put the array together like so:
$result = array('listing'=>$listing);
$pins = array('lat'=>$lat1,'lng'=>$lon2);
$results = array('listing'=>$result,'pins'=>$pins);
echo json_encode($results);
Now, clientside I use jquery. The issue I'm facing, is there should be 2 results in total. However I see the same result repeated twice (I can confirm they should be unique). Here is my jQuery:
$.ajax({
url: '/updatedsearch.php',
type: 'POST',
data: {
q: search,
lng: coordinates[0],
lat: coordinates[1],
},
dataType: "json",
success: function(data) {
if(data == "undefined" || data == null) {
console.log("There was no search results or something similar");
} else {
var pins = [data.pins.lat, data.pins.lng];
$.each(data, function(key, val) {
$('#listings').append(data.listing.listing);
console.log(pins);
console.log(data);
});
}
},
Everything here works as it should, apart from when $.each() runs, it appears to be appending the same data twice.
I assume it's because of .append(data.listing.listing);, if I understand correctly I'm not looping through the array here, I'm effectively referencing data.listing.listing[0] - have I understood this correctly?
Edit: I now have an issue with my results appearing twice. There should be only two results, however there are four in total, it appears as though these have been duplicated.
{"listing":["<div>This contains my HTML</div>"], "pins":"lat":"50.000000","lng":"-1.000000"}}
I have run this though jsonlint and it appears invalid. Using PHP I have created this data as follows:
while($listrow = mysqli_fetch_assoc($list)) {
$listing[] = '<div>This contains my HTML</div>';
}
$pins = array("lat"=>$lat1, "lng"=>$lon2);
$results = array('listing'=>$listing, 'pins'=>$pins);
echo json_encode($results);
Have I misunderstood using multidimensional arrays, which is causing the error?
You are correct that you are not looping through the array. You are also not referencing the individual array items when you append.
Try:
$.each(data.listing.listing, function(i, item) {
$('#listings').append(item);
});
When you do the following:
$.each(data, function(key, val) {
You are looping through the properties of the data object. It has two properties: listings and pins, so the loop executes twice.
And for each iteration of the loop, you are appending the same value (data.listing.listing), which I assume is an array.
Instead, I think you want to iterate over the array, and append each item in the array.
EDIT: The PHP you show at the top of your question looks like it would generate JSON like this:
{
"listing": { "listing": ["<div>This contains my HTML</div>"] },
"pins": { "lat":"50.000000","lng":"-1.000000" }
}
But with your edit, you show JSON that looks like this:
{
"listing": ["<div>This contains my HTML</div>"],
"pins": { "lat":"50.000000","lng":"-1.000000" }
}
If that is what your JSON looks like, you should use:
$.each(data.listing, function(i, item) {
jsfiddle
It appears that you intend your $.each to loop through the listings placed in $results['listing'] in your PHP, but it's actually looping over the whole $results.
To better see what's going on, use a different name for the current item in your $.each. Because you use data, the same name you use as the argument of your success callback, you're making the code harder to debug. If you want to cycle through your listings, do the following inside the success callback:
$.each(data.listing, function(i, result)){
$('#listings').append(result);
}
The JSON you posted:
{
"listing":["<div>This contains my HTML</div>"],
"pins": "lat":"50.000000","lng":"-1.000000"}
}
Is invalid because you're missing an opening bracket between "pins": and "lat". It should be
{
"listing":["<div>This contains my HTML</div>"],
"pins": {"lat":"50.000000","lng":"-1.000000"}
}

Update DOM with jQuery ajax array results

I have search results generated by a 3rd party script that I would like to add data to. I have parsed the results to get an array of id's, and queried the database for additional fields. The ajax success method receives the formatted array back, but now I'm stuck on how to get those results into the right place in the DOM.
The HTML:
<div class="ihf-results-property-info">
<div class="ihf-results-price">LIST: $2,150,000</div>
<div class="ihf-results-links"> 24 Photos
</div>
<div class="ihf-results-extra-info">
<div class="ihf-results-listingnum hidden-xs">Listing # 727938</div>
</div>
Repeat...
The last div I included in the example has the unique ID I'm using for the query. I'd like to use that to associate the ajax return with proper placement in the DOM. Here is my javascript:
jQuery(document).ready(function($) {
// grab the listings numbers so we can query the db for extra data
var listings = $('.ihf-results-listingnum').map(function() {
// grab just the digits
var listingNum = $(this).text().replace(/[^0-9]/g, '');
// add the listing number to the parent so we can target it later
$( this ).parents('.ihf-results-extra-info').parent().addClass('marketing-details-' + listingNum);
return listingNum;
// use .get to create an array of the listing numbers
}).get();
$.ajax({
type: "GET",
url: "custom/07-idx-queries.php",
data: 'mlsNums=' + listings, // looks like ?mlsNums=735383,727468,699876...
success: function(result) {
// this logic came from here: http://stackoverflow.com/questions/15311320/how-to-work-with-jquery-ajax-and-php-array-return
resultJson = $.parseJSON(result);
if (typeof resultJson == 'object') {
jsObject = eval(resultJson);
jsArray = [];
for(elem in jsObject){
jsArray.push(jsObject[elem]);
}
console.log(jsArray);
// this works as expected, except keys are 0 based
// This is where it all falls apart. I want to extract each object and stick it in the DOM in the correct place
jQuery.each(jsArray, function(key, value) {
$( this ).appendTo('.marketing-details-' + key);
});
}
else {
console.log("error occurred");
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
})
});
And the php I'm using produces the desired results from the db, with the exception that it is a numerical array. I think an associative array would work better when trying to put the results into the DOM, tha way I could use the ID's as the key and match them to the classes I added. Here is the relevant code from custom/07-idx-queries.php:
$mls_nums = explode(",",$_GET['mlsNums']);
// removed all of the conditionals to keep the question clean
$html = array();
foreach ($mls_nums as $mls_num) {
// just retreiving a single object from each row for now
$remarks = $mysqli->query("SELECT mr FROM listings WHERE ln = '$mls_num'")->fetch_object()->mr;
// format the data
$my_html = "<p class='marketing-remarks mlsnum-".$mls_num."'>$remarks</p>";
// build an array of the results - necessary?
array_push($html,$my_html);
}
// send the data back in a JSON string
echo json_encode($html);
So my goal is to query the db for up to 10 rows, and insert the results into an equal number of new divs that are children to a div with the same id number in its class. I greatly appreciate any help.
In your PHP do this:
$html[$mls_num] = $my_html;
// this isn't needed
// array_push($html,$my_html);
Now your returned data has a way to tie into the target div.
Not clear if you have control over the HTML in the first part of your example, but this would be one approach.
<div class="ihf-results-listingnum hidden-xs">Listing # 727938</div>
<div class="remarks" id="remarks_<?= $listingid; ?>"></div>
Then in the JavaScript $("#remarks_" + key).html(value);
Otherwise, you need to use jQuery to locate the div with the listing id using the :contains selector:
$("div:contains('# " + key + "')").appendTo(value);
'# " + key + "' would equate to # 1234 or whatever it is. This won't work if the same listing is on the page twice though!
Okay, here is the working success method. Thanks to LG_PDX for the cleaned up php. I eliminated the unnecessary processing as .each() appears to iterate just fine over the JSON response:
success: function(result) {
resultJson = $.parseJSON(result);
if (typeof resultJson == 'object') {
$.each(resultJson, function(key, value) {
$('.marketing-details-' + key).append( value );
});
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}

Multiple Arrays returned by json from PHP

To begin with I am building a complete CRM running Ajax and there is a lot to this, so please be patient and read the whole thing.
I have an ajax script returning several json arrays. When I display the return value from my php script I get this:
[{"packages":{"id":"1","name":"Land Line"}},{"packages":{"id":"2","name":"Cellular w\/Alarm.com"}},{"packages":{"id":"3","name":"Home Automation"}}]
What I am trying to do is separate the arrays so I can make a select drop down from it. Before anyone says anything, yes I know how to do that my itself, but I am needing the form this script is populating to be a select dropdown or a complete filled in form based off of the id going into another script. It is a bit confusing, so don't ding me for it please.
Here is the PHP script alliance_form.php:
$equip = "SELECT * FROM packages WHERE brand='$brand'";
if($db->query($equip) === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $db->error, E_USER_ERROR);
} else {
$result = $db->query($equip);
$array = array();
foreach($result as $r) {
$array[] = array(
"packages" => array(
"id" => $r['id'],
"name" => $r['name']
)
);
}
echo json_encode($array);
}
Here is the jquery going to the PHP form and coming back to input the information:
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
success: function(msg)
{
$("#package-form").html(msg);
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
alert(value);
});
});
},
error: function(error)
{
$(".error").html(error);
}
});
This is part of an ordering system of a CRM, so this script is checking the database for existing orders under the id. If the id is there then it is supposed to come back with the order information and I populate the form. If not it will give a select dropdown to select a package which then populates an empty form. That is the gist of what I am on right now.
Here is the question: Why can't I get a response from JQuery on the each() loop on this. One return comes back with a regular array, and this one is a nested array.
I'm not quite clear on what you're asking, but here are my thoughts on this:
You've got .packages in the wrong place. Instead of this:
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
...
You should have written this:
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
...
Better yet, you could just get rid of packages altogether. It's an unnecessary level in the JSON structure.
Also, I don't think jQuery knows that the response is JSON. For this to work, you need either dataType: 'json' in the list of arguments to $.ajax, or something on the server to set the MIME type appropriately.
I'm also concerned about $("#package-form").html(msg);, because msg is not an HTML string.
You should try something like this (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
console.log(value);
});
});
Instead of $.each(msg.packages, function(i, object){...}) because msg is an array of objects and in your given example there are three objects right now and each object has a packages item (nested object) which contains id and name.
Update : You can also use, just one loop (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
console.log(object.packages.id);
console.log(object.packages.name);
});
Sorry guys, I threw out my back and couldn't get to my code from home.
Anyways I tried both solutions you provided, and I have been looking at this for a while but neither worked. I have this updated to:
$("#brand").click(function () {
var brand = $(this).attr('rel');
$("#order-form").empty();
var contact_id = $("#contact_id").val();
var dataString = "contact_id=" + contact_id +"&brand=" + brand + "";
//alert("test");
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
//dataType: "json",
success: function(msg)
{
//$("#package-form").html(msg);
$.each(msg, function(i, object) {
if(msg.packages) {
$("#package-form").append("<select>");
$.each(object.packages, function(index, value) {
$("#package-form").append('<option value="'+value+'">'+index+'</option>');
});
$("#package-form").append('</select>');
}
});
},
error: function(error)
{
$(".error").html(error);
}
});
});
This just returns nothing not even a blank select box. The $("#package-form").html(msg); is just so I can see the output how the php script is sending it back. The if statement is just to run a verification to see if the array has a nested array with packages in it. I need the return function to do a certain action if it does. Very Important!
As for the dataType: 'json', line in the ajax, it doesn't give me a return value if I have that placed in it. But when I remove it, it will display the array.
Nothing has been changed in the PHP file besides moving the query like suggested.
Ok guys. I got the answer! I have it like this:
$("#brand").click(function () {
$("#order-form").empty();
$("#package-form").empty();
var msg = '[{"packages":{"1":"Land Line"}},{"packages":{"2":"Cellular w\/Alarm.com"}},{"packages":{"3":"Home Automation"}}]';
var newData = JSON.parse(msg);
var newSelect = "<select>";
$.each(newData, function(i, ob) {
$.each(ob.packages, function(index, value) {
newSelect += '<option value="'+index+'">'+value+'</option>';
});
});
newSelect += "</select>";
$("#package-form").append(""+newSelect+"");
});
Here is the fiddle: http://jsfiddle.net/M78vE/

Adding to an array in sqlite3 and passing with json to jquery ajax

I attempt to fill a drop down from a database. I query and add my result to an array. I then use json_encode to send my data to a php file.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => $proj_option);
echo json_encode($output);
In my php file, I use jquery ajax to fill the drop down.
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
This is great, BUT the only item in my drop down is the last item in the db. For example, my database has the following under Project:
Project: up, down, low, right
But my drop down only fills with the last entry, "right." Why is this? How can I fix it?
PHP json_encode() in while loop was similar, and I made the changes, but there is something missing here.
may be try this
success:function(response) {
$.each(response.proj,function(key,value){
$("#exp").append(value);
$("#project").append(value);
});
}
each time thru your loop in javascript you are overwriting your html. The .html() method sets the innerHTML property of the tag, so each time you call it you are resetting the html and only the last one will show. try not using a loop, instead join you response together and then call .html()
$("#exp").html(response.proj.join(''));
$("#project").html(response.proj.join(''));

Looping though JSON data and displaying it in a DIV

I have a page with some checkboxes and a submit button. I use AJAX to post the checkbox values to a PHP script, calc.php, run some calculations with the data and assign the result to a PHP session variable. I have another PHP script, json.php, that takes that session data and encodes it as JSON for the jquery to display in the div. My problem is I allow the user to set the amount of data sets they are going to submit, subnumber, and my display loop gets out of sync when the user changes the number of sets.
For example, if they start with 3 data sets, they submit them one by one by pressing #button. After the last set, if (count == max) runs and. Now they can do another calculation and change the number of data sets if they wish. If they change it to say 2, output goes to four instead of reseting to 1 and emptying #log.
$("#button").click(function() {
$.ajax({
type: "POST",
url: "calc.php",
data: $("form#checkboxes").serialize(),
success: function(data) {
if(document.getElementById('calc').checked) {
var max = checkboxes.subnumber.value;
var stop = Number(max) + 1;
count++;
output++;
$.getJSON('json.php', function(data) {
$.each(data, function(key, val) {
$('#log').append(output);
$('#log').append(val.result);
$('#log').append("</br>");
})
})
if (count == max){
count = 0;
$("#results").load('results.php')
}
if(output == stop) {
$("#log").empty();
output = 1;
}
}
}
})
}
I know it's something simple, but I have been trying to fix it for two hours now and can't figure out the problem. Everything else works perfectly, it's just the output counter that isn't done correctly.
You're running asynchronous calls into your JSON. If users are doing things so quickly that the calls are coming back out of order, the issue lies in there.
You've got two options:
Run all of your JSON synchronously (use async:false in your JSON calls)
Utilize a counter and only process events that are coming back on the current index.
Psuedo Code for #2:
var pCounter = 0;
function doSomeAjax()
{
pCounter++;
$.ajax('url',{
data:{count:pCounter}
success:function(data)
{
// your json should return the current counter index
if (data.counter != pCounter) return;
// execute normally.
}
});
}

Categories