Remove the desired number from data - php

I have a question about how can I delete the desired number from the img_ids. As you see in the table below the img_ids like 68,67,66,65,64, . I want to delete for example number 67, how can I do that with PHP. My mind is confused because of the commas :S.
<div class="delete" id="67">Delete Image</div>
Ajax
$("body").on("click", ".delete", function(){
var deleteimgid = $(this).attr("id");
var data = 'img='+deleteimgid;
$.ajax({
type: 'POST',
url: 'delete.php',
data: data,
cache: false,
beforeSend: function(){},
success: function(response){
}
});
});
delete.php
<?php
include_once 'inc.php';
if(isset($_POST['img'])){
$imgid = mysqli_real_escape_string($db, $imgid);
// Then what should be the query ?
// I am confused because of the commas.
}
?>

Even tho you should not store data like that, here a working approach:
$imgList = '12,23,45,56,67,78';
$imgid = 12;
$imgIds = explode(',', $imgList);
$imgIds = array_filter($imgIds, function ($item) use ($imgid) {
return $imgid != $item;
});
$imgList = implode(',', $imgIds);
print $ImgList; // prints 23,45,56,67,78
What it does:
Splitting the list of ids into an array by comma
Use array_filter to map over the array and remove the desired value
Implode the list again by comma
How you actually should/could store your data
As others have pointed out in the comments, you should normalize your database. Read more
You also could use a blob field instead of a text field, since PHP can handle blob data very easy using serialize/unserialize

Related

How to split data while loop data in php and pass to ajax html with different id's

I have db table of doctors nearly more than 100 doctors list in it, Here is my PHP code for doctors dc.php :
$conn= mysqli_connect('localhost', 'root', '', 'test');
$query = mysqli_query($conn, "select * from doctors");
while($result=mysqli_fetch_array($query)){
$dc_name = $result['name'];
$dc_img = $result['image'];
$dc_email = $result['email'];
echo $dc_name."||".$dc_img."||".$dc_email;
}
I want echo all doctors another main page index which already fixed large layout with bootstrap,html,css by using ajax calling on click
Here is my code for ajax
$(function(){
$(".divscrolla").on("click", function(){
$.ajax({
url:'db.php',
type:'POST',
data:{"data":$(this).val()},
success:function(data){
var splitted = data.split("||");
$("#result_name").html.splitted[0];
$("#result_img").html.splitted[1];
$("#result_email").html.splitted[2];
}
});
});
Here I want display all 100 records by AJAX
But here I am getting only first element only, but I have more 100 records in database.
How can I solve by simplifying this?
Did you try
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
$jsonstring = json_encode($resultArray);
echo $jsonstring;
And then in the AJAX code don't split, let the json format help you. By setting the data type to json dataType: "json",
$(function(){
$(".divscrolla").on("click", function(){
$.ajax({
dataType : "json",
url:'db.php',
type:'POST',
data:{"data":$(this).val()},
success:function(data){
//consume the data in a assoc array manner
//data[0]['name'] for first entry's name
}
});
});
}

Passing multi dimensional array to PHP with jQuery and AJAX

I've got the jQuery code:
$(document).ready(function() {
answers = new Array();
answers[0] = new Array();
answers[0]['question_id'] = 12;
answers[0]['answer_id'] = 32;
answers[1] = new Array();
answers[1]['question_id'] = 55;
answers[1]['answer_id'] = 132;
answers[2] = new Array();
answers[2]['question_id'] = 987;
answers[2]['answer_id'] = 1112;
$.ajax({
type: "POST",
url: "collect.php",
data: {answers: answers},
dataType: "json",
beforeSend:function(){
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
},
success: function(data){
alert('success!');
}
});
});
Now, should this work? According to what I've found when looking for code examples it should. Problem is, I have no idea how I could collect the data in my PHP file. I mean, it's a $_POST[], but then what? How do I collect the $result[0]['question_id'] and all the other data?
Thanks a lot in advance,
Carl C. Carlsson
You're never actually populating the arrays inside of the answers array with data, their length is still 0 because you're using string indexes rather than int indexes. What you really want are objects stored in your array.
answers[0] = {};
answers[0]['question_id'] = 12;
answers[0]['answer_id'] = 32;
You can collect the value in php page with $_POST['answers']. Then you can loop through that array do whatever you want with the data.
It was solved by changing the Javascript to:
answers = {};
I could then simply access the data in PHP with:
$_POST['answers'][1]['answer_id'];
for example, or just loop through it.
Thanks for your help, ladies and gentlemen.

jquery each loop into a multi array, check for duplicates

I think what I want to do is really simple but can't get it to work. I'm looping through a table and getting some values from the existing rows, that part works. Then I'm using AJAX to try and make a multidimensional array without duplicates but something isn't working. What I really want to do is delete the duplicate part, reorder the array and array_push new values. Here's what I have:
AJAX:
function getData(){
$("#table .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
$.ajax({
type: "POST",
async: false,
data: {key: key, s: sel, q: q}
});
});
}
PHP:
if(isset($_POST['key'])){
$title = $_POST['key'];
$s = $_POST['s'];
$q = $_POST['q'];
if(!empty($_SESSION['check'])){
foreach ($_SESSION['check'] as $key=>$value){
if(in_array($title, $value)){
unset ($_SESSION['check'][$title]);
$_SESSION['check'] = array_values($_SESSION['check']);
array_push($_SESSION['check'], array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
}else{
$_SESSION['check'] = array(array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
Is there something wrong with the logic? It seems like it should work. The same foreach loop works when trying to delete a table row. It finds the correct KEY and deletes it. Why doesn't it work here?
Here's the answer I got by hours and hours of searching. I avoided using serialize since...well I don't understand how to use it. In JS I'm looping to find values in the table and making an array like this:
function getData(){
var checkArray = new Array();
$("#shopCart .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
checkArray.push(key);
checkArray.push(sel);
checkArray.push(q);
});
$.ajax({
type: "POST",
data: {ch: checkArray}
});
}
In my PHP is where I found a cool trick. Since I'm controlling the data in the array, I know how many values will be in it. The trick I found is "array_chunk" so for the 3 values I'm doing this:
if(isset($_POST['ch']) && (!empty($_POST['ch']))){
unset($_SESSION['check']);
$_SESSION['check'] = array_chunk($_POST['ch'], 3);
}
So I'm just clearing the session variable and adding the new values. That eliminates all the checking and clearing and all that. I'm sure there are better ways to do this but this method is short and works and that's what I'm looking for. Hope this helps someone!

Jquery Ajax read post values with php

I'm sending the following info to a php file. data contains 'one' and 'two'. 'One' contains the serialized form and two contains similar custom info. How can i read those post values with php. I want to be able to differentiated between the value contained in one and value contains into two.
$('form').submit(function() {
x = $(this).serialize(),
test = 'testing=whatever&something=else';
$.ajax({
type: 'POST',
data: {'one':x, 'two':test}
...
})
})
How can i read the values in php in such a way where i can do
$one = $_POST['one'];
foreach($one as $key=>$value){ $message.= $key.": ".$value."\r\n"; }
I'm not sure what you want to do with the serialised version of the form (x) but you can get access to both of the variables in the receiving PHP script using $_POST as per usual and then probably use parse_str (http://au.php.net/manual/en/function.parse-str.php) to break 'test' out into the various parameters, but I question why you are taking this route instead of breaking the parameters up and passing them as individual arguments in the data argument:
data: {'testing' : whatever, 'something' : else}
you need to cancel the default behavior of submit
$('form').submit(function(e) {
e.preventDefault();
x = $(this).serialize();
test = 'testing=whatever&something=else';
$.ajax({
type: 'POST',
data: {one:x, two:test}
...
})
})
on the php side
$one = $_POST['one'];
$two = $_POST['two'];
update:
im not that well versed in php but i think the following should work
$one = $_POST['one'];
$two = $_POST['two'];
$cols = explode("&", $one);
foreach($cols as $col) {
$key_values = explode("=", $col);
$key = urldecode($key_values[0]);
$values = urldecode(key_values[1]);
}
echo $key, $values;
If your form contains checkboxes or radioboxes (inputs with same names) use $(this).serializeArray() instead of $(this).serialize() to distinguish between them
You need to first convert your form data into JSON! not the query string which serialize does, for that see This, JSON can give you ability to have nested keys.
Then you can put seperate data in different keys in JSON like:
var myData =
{
'one': $('form').serializeObject(),
'two': 'testing=whatever&something=else',
};
$('form').submit(function() {
$.ajax({
type: 'POST',
data: myData,
...
});
});
And the on PHP side you can easily get it using the way you want to:
$one = $_POST['one']
foreach($one as $key=>$value) { $message.= $key.": ".$value."\r\n"; }

retrieving data from db based on php's $_GET var with jquery/ajax?

Disclaimer
I have searched for duplicates, but I can't seem to find them. I am surprised because this seems to be a big issue. I most likely am missing something big though.
Problem/Question
I am having the userid passed into through the url via php, myOtherScript.php?userid=1. How can I get that variable to be passed via ajax so that I may query the database with that userid, echo it out and return it to the page?
This is in global.js file
jQuery
$.ajax({
url: "myScript.php",
data: "userid=" - This is what I need: $_GET['userid'] - ,
success: function( data ) {
$('#myDiv').html( data );
}
});
Solution
WIth the help of bstakes and this answer, I was able to figure it out with this function: (top answer)
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Thanks for the answers guys!
$.ajax({
url: "myScript.php",
data: "userid=<?php echo intval($_GET['userid']); ?>",
success: function( data ) {
$('#myDiv').html( data );
}
});
You could also try using the search attribute of the window.location object.
If the url is http://www.mysite.com/display.php?userid=7 window.location.search will return "?userid=7". You will obviously need to remove the leading "?", but be aware that if there are additional GET paramaters, separated with ampersand '&', those will be included as well.
So, with a bit of additional Javascript, you can split on the '&', which gets you an array of "key=val", then you can spilt on the equal sign and create an object with {key : val}. Then you could use that object to access the query string params.
var qs = window.location.search.substring(1),
pieces = qs.split('&'),
i,
qsObj {},
tmp;
for ( var i in pieces ) {
tmp = pieces[i].split('=');
qsObj[tmp[0]] = tmp[1];
}
See https://developer.mozilla.org/En/Window.location for additional information on the window.location.
If you want to keep the JS seperate, put it in a function that accepts the user id...
function do_something(user_id) {
$.ajax({
url: "myScript.php",
data: "userid=" + user_id,
success: function( data ) {
$('#myDiv').html( data );
}
});
}
Then just call do_something($_GET['user_id']);
You might have to move the script inline on the PHP file then you echo out the $_GET['userid'] in the data area of your ajax call.
just found this: how to get GET and POST variables with JQuery?

Categories