I use this code to trigger the row delete:
<a href="javascript:void(0);" onclick='$.get("web_page.php",{ cmd: "delete_stmt", id_f: "<?php echo $rrows['id_f']; ?>", id: "<?php echo $row['id']; ?>" } ,self.location="web_page.php");'>delete</a>
and this is the code:
if($get['cmd'] == 'delete_stmt') {
$stmt = $conn_bd->prepare("DELETE FROM table WHERE id_f=:id_f and id=:id");
$stmt->execute(array('id_f' => $get[id_f], 'id' => $get[id]));
$stmt->execute();
}
the record is always deleted from the database table, but sometimes the record is displayed on the web page.
this happens in IE, Firefox, Chrome ...
do you have an idea what could be causing this?
thk
Change your link to this:
<a href="javascript:void(0);" onclick='deleteItem("<?php echo $row['id_f']; ?>", "<?php echo $row['id']; ?>");'>delete</a>
... and add this function:
function deleteItem(row_id_f, row_id)
{
$.get(
"web_page.php",
{ cmd: "delete_stmt", id_f: row_id_f, id: row_id },
function(data){
self.location="web_page.php";
}
);
}
The link will call the deleteItem function which does the ajax call, it then waits for the success event before doing the page redirect.
self.location executing before the $.get() call. Try to create a function and wait for the $.get().
You can use the jquery ajax Here is a official page function. It is easy to use. Also If you redirecting this own page, you can try hiding the "delete" and throw a alert box.
Related
how to bring ajax post data to the controller when redirecting the page, I have got id_user data from <a class="edit" href="<?php echo BASE_URL. "app.php/usermanagement/edit_user "?>" id_user="<?php echo $row ['idx'] ?>">Edit</a> but when redirecting the data page is null / 0, how do I bring post ajax data to the redirect page through the controller, please help me, if something is unclear please apologize and can ask me ...
Note: I use PHP native MVC
This is my code
$(document).ready(function(){
$('.edit').on('click', function(){
var id_user =$(this).attr("id_user");
alert(id_user);
var url =$(this).attr("href");
$.ajax({
type:'post',
url: url,
data:{id_user:id_user},
success: function(data){
alert(data)
},
error:function(err){
alert(err)
}
});
});
});
This is my controller
public function edit(){
Template::setTitle('Edit User Management');
$id_user = (int)Request::post('id_user');
$result = $this->getUserbyId($id_user);
$dataresult = json_decode($result, true);
if($dataresult === NULL) {
echo "<script language = \"javascript\">window.alert(\No Have Data\");";
echo "javascript:history.back();</script>";
return false;
}
$data = $dataresult;
return $data;
this is my code
<a class="edit" href="<?php echo BASE_URL. "app.php/usermanagement/edit "?>" id_user="<?php echo $row ['idx'] ?>">Edit</a>
this is my problem
I have get data id_user, I cacth data use alert
but when I redirect page, this is result
I want to get data like this, when I redirect Page
This is my new error when I add Prevent Default
Since you have a list of rows and you render them somehow, you can assign an id of the record to each of the entity.
<a class="edit" href="<?php echo BASE_URL. "app.php/usermanagement/edit_user?id_user=" . $row['idx']; ?>">Edit</a>
Now, when you click, you make a GET request to your edit controller action with id_user parameter. You can handle this request like this:
public function edit_user(){
if(isset($_GET['id_user'])){
//TODO: make something with it
var_dump($id_user);
die();
} else {
//throw an error
}
}
And your JQuery code should looks like this:
$('.edit').on('click', function(){
var id_user =$(this).attr("id_user");
alert(id_user);
var url =$(this).attr("href");
$.ajax({
type:'post',
url: url,
data:{id_user:id_user},
success: function(data){
//alert(data);
window.location = '/app.php/usermanagement/edit_user?id_user=' + id_user;
},
error:function(err){
alert(err);
}
});
});
I am trying to implement "ADD TO SHORTLIST" via php/ajax
Here's my relevant codes
Calling ajax from this page :
<a id="shortlist" class="pull-right add-to-shortlist">Add to shortlist</a>
<p id="cookieShortList"><?=$_COOKIE['shortlist_count']?></p>
<script>
$("#shortlist").click(function(){
$.ajax({
type: "post",
url: "ajaxcall.php",
data:{spId : "111",prId : "222"},
success: function(result)
{
$('#cookieShortList').html(result);
}
});
});
</script>
POST DATA page:
$s_id = $_REQUEST['spId'];
$product_id = $_REQUEST['prId'];
setcookie("cookie_product[$s_id]", $product_id, time()+ (30),'/');
echo $shortlist_count_c = count($_COOKIE['cookie_product']);
if (isset($_COOKIE['cookie_product'][$s_id])) {
echo "blah blah";
}
setcookie("shortlist_count", $shortlist_count_c, time()+ (30),'/');
The problem is I can see that cookie is being set on my browser under resources tab as "cookie_product[111]" => "222" on first click on "add to shortlist" but the count gets updated only after second click on "add to shortlist".
Read documentation
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array.
Try this:
$shortlist_count_c = count($_COOKIE['cookie_product']) + 1;
I am very new to PHP and Javascript.
Now I am running a PHP Script by using but it redirect to another page.
the code is
<a name='update_status' target='_top'
href='updateRCstatus.php?rxdtime=".$time."&txid=".$txid."&balance=".$balance."&ref=".$ref."'>Update</a>
How do I execute this code without redirecting to another page and get a popup of success and fail alert message.
My script code is -
<?PHP
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
-------- SQL Query --------
?>
Thanks in advance.
You will need to use AJAX to do this. Here is a simple example:
HTML
Just a simple link, like you have in the question. However I'm going to modify the structure a bit to keep it a bit cleaner:
<a id='update_status' href='updateRCstatus.php' data-rxdtime='$time' data-txid='$txid' data-balance='$balance' data-ref='$ref'>Update</a>
I'm assuming here that this code is a double-quoted string with interpolated variables.
JavaScript
Since you tagged jQuery... I'll use jQuery :)
The browser will listen for a click event on the link and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.
As you can see, I'm using .data() to get the GET parameters.
$(document).ready(function() {
$('#update_status').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
rxdtime: $(this).data('rxdtime'),
txid: $(this).data('txid'),
balance: $(this).data('balance'),
ref: $(this).data('ref')
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});
PHP
Looks like you know what you're doing here. The important thing is to output the appropriate data type.
<?php
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
header('Content-Type: text/plain; charset=utf-8');
// -------- SQL Query -------
// your logic here will vary
try {
// ...
echo 'success';
} catch(PDOException $e) {
echo $e->getMessage();
}
Instead of <a href>, use ajax to pass the values to your php and get the result back-
$.post('updateRCstatus/test.html', { 'rxdtime': <?php ecdho $time ?>, OTHER_PARAMS },
function(data) {
alert(data);
});
Here is my function:
function loadNext(choice) {
$("#thequestion").load("question.php", { ans: choice, id: "<?php echo $row['id']; ?>", nextId: "<?php echo $nextQuestionId; ?>" } );
$("#graph").load("graph.php", { id:"<?php echo $row['id']; ?>", nextId: "<?php echo $nextQuestionId; ?>" } );
}
I execute the function and Firebug says the data is being posted, eg:
Parameters:
ans y
id 3
nextId 1
Source:
ans=y&id=3&nextId=1
But when I try to retrieve them in 'question.php' or 'graph.php' like so:
$id=$_GET["id"];
$nextId=$_GET["nextId"];
They echo back as null.
Any ideas?
EDIT: I've just noticed that the webiste URL does not change when the function is executed. Shouldn't ans=y&id=3&nextId=1 be appended onto it for the data to be sent? Or is this not the case for jQuery/ajax stuff?
EDIT 2: Sorry, this may be becoming really specific, but if I append the
/question.php?ans=y&id=3&nextId=1
manually, it all works fine! So now I'm really confused - this has narrowed the problem down to the function loadNext(choice), has it not?
Edit - (not op) suggested edit to include javascript and jquery tags.
From the jQuery load() API
The POST method is used if data is provided as an object; otherwise, GET is assumed.
Either change your PHP script to look in $_POST (or $_REQUEST if you're feeling lazy) or change the JavaScript to
$.get("question.php", {
ans: choice,
id: "<?php echo $row['id'] ?>",
nextId: "<?php echo $nextQuestionId ?>"
}, function(data) {
$("#thequestion").html(data);
});
Try this as well,
function loadNext(choice) {
$("#thequestion").load("question.php?ans=choice&id=<?php echo $row['id']; ?>&nextId=<?php echo $nextQuestionId; ?>" } );
$("#graph").load("graph.php?id=<?php echo $row['id']; ?>&nextId=<?php echo $nextQuestionId; ?>" } );
}
I have a little personal webapp that I'm working on. I have a link that, when clicked, is supposed to make an ajax call to a php that is supposed to delete that info from a database. For some unknown reason, it won't actually delete the row from the database. I've tried everything I know, but still nothing. I'm sure it's something incredibly easy... Here are the scripts involved.
Database output:
$sql = "SELECT * FROM bookmark_app";
foreach ($dbh->query($sql) as $row)
{
echo '<div class="box" id="',$row['id'],'"><img src="images/avatar.jpg" width="75" height="75" border="0" class="avatar"/>
<div class="text">',$row['title'],'<br/>
</div>
/*** Click to delete ***/
x</div>
<div class="clear"></div>';
}
$dbh = null;
Ajax script:
$(document).ready(function() {
$("a.delete").click(function(){
var element = $(this);
var noteid = element.attr("id");
var info = 'id=' + noteid;
$.ajax({
type: "GET",
url: "includes/delete.php",
data: info,
success: function(){
element.parent().eq(0).fadeOut("slow");
}
});
return false;
});
});
Delete code:
include('connect.php');
//delete.php?id=IdOfPost
if($_GET['id']){
$id = $_GET['id'];
//Delete the record of the post
$delete = mysql_query("DELETE FROM `db` WHERE `id` = '$id'");
//Redirect the user
header("Location:xxxx.php");
}
Ah just spotted your error, in the href you're generating you're not setting the id attribute. It should be something like:
x
Of course that's just an immediate example, you must escape these kinds of things but this should let you access the item in jQuery.
You may want to modify your delete script to not just redirect after the DB query. Since it's being called via AJAX, have it at least return a success/error code to the javascript:
// can't return $delete unconditionally, since *_query() returns an object
if ($delete) {
return(json_encode(array('code' => 1, 'msg' => 'Delete succeeded')));
} else {
return(json_encode(array('code' => 0, 'msg' => 'Delete failed: ' . mysql_error()));
}
It's bad practice to assume a database call succeeded.