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; ?>" } );
}
Related
I've created a custom template for wordpress and I'm trying to execute some php code (deleteUser.php) to delete a record from a db but I'm not sure how to run the code without using alert. At the moment I'm just getting an empty dialog box rather than my php code deleting a row from the db.
ajax part
<?php
echo '<script>';
echo 'function dltUser(siteID){';
echo "jQuery.ajax({";
echo "data: 'siteID=' + siteID,";
echo "url:"."'".get_stylesheet_directory_uri()."/deleteUser.php"."',";
echo "method: 'POST', ";
echo "success: function(msg) {";
echo "alert(msg);";
echo "}";
echo "});";
echo '}';
echo '</script>';
?>
deleteUser.php - the code to delete a row
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-config.php' );
global $wpdb;
$siteID = $_POST['siteID'];
echo '$wpdb->query("DELETE FROM my_site WHERE SiteID = %d",$siteID)';
?>
Don't wrap the $wpdb->query(...) inside an echo, that won't execute the query, it will just output the command as a string, and you want to return a value to the AJAX function after the code is executed, not echo it.
If you don't want to use alert() to prevent the message from displaying to the user, use console.log() instead, see Console.log()
Also, as Rory said, don't use an echo for every single line you write. Either use . to concatenate or write plain HTML and inject the PHP variables where needed.
Resuming, your code should look something like this:
Ajax:
<script>
function dltUser(siteID) {
$.ajax({
data : siteID,
url : <?php get_stylesheet_directory_uri(); ?> + '/deleteUser.php',
method : 'POST',
success : function(msg) {
console.log(msg);
}
})
}
</script>
deleteUser.php
<?php
include_once ($_SERVER['DOCUMENT_ROOT'] . '/wp-config.php');
global $wpdb;
$siteID = $_POST['siteID'];
if ($wpdb->query("DELETE FROM my_site WHERE SiteID = %d", $siteID)) {
return 'Success';
}
return 'Error';
?>
Remove the alert. An empty dialog box means alert is being called, but you have no message. However the PHP script ran returning an HTTP response with a 200 OK code. If you don't want the popup, remove the alert. If you want a message, echo something at the end of your script.
Oh, and ditch the closing ?> if there isn't any output after it.
This is my html code
<td class="saltr" style=" border-color:#000; cursor:pointer;" id="<?php echo $grade["DEALID"];?>" onclick="dealid(this.id)" ><?php echo $grade["DEALINGS"];?></td>
on onclick() javascrip is written.
function dealid(psid)
{
var serow = psid;
//alert (serow)
$.ajax({url:"../views/printdeal.php?proc=dealing",data:"dealdatres="+serow,success:
function(z)
{
//alert("hiiiii")
alert(z);
//window.location="printdeal.php";
}
});
}
and in printdeal.php page the code is written as
if($_REQUEST["proc"]=='dealing')
{
$dealdatres1=$_REQUEST["dealdatres"];
include_once("../classes/dbqrs.php");
$obj=new qrys();
$qremp="select deals.PROSPECS ,deals.DEALINGS,deals.BUYER,deals.BENEFICIARY,deals.GUIDE,deals.REMARKS ,deals.DATES,salescal.DEALID from salescal left join deals on deals.ID=salescal.DEALID where salescal.DEALID='$dealdatres1'";
$empr=$obj->exeqry($qremp);
$empres=mysqli_fetch_array($empr);
?>
but when I run this code and when i click on it ,it shows a notice as undifined "proc" .
Please help me to solve this.
It looks like you have placed you function somewhere out of usual global scope. I don't know what should be changed as far as I cannot know your structure.
At first, move all function's content into onclick:
onclick='$.ajax({url:"../views/printdeal.php?proc=dealing",data:"dealdatres="+this.id,success:
function(z)
{
//alert("hiiiii")
alert(z);
//window.location="printdeal.php";
}
});'
and get a proof that there is something wrong with the name/placement only.
P.S. BTW read about addEventListener/attachEvent as strong and more convenient alternative to "onclick" usage.
We have kinds of ways to get the function,one of them like this:
You may write the code in view page :
$.ajax({
url: "<?php echo url('/soc/cnews/savetop') ?>",
type: 'post',
data: "sets=" + $("#top10").val(),
sync: false,
dataType: 'json',
success: function(data) {
if (data.status == 'success') {
window.location.reload();
} else {
alert(data.msg);
}
}
});
and the write the code in page which get data:
if($success){
echo "{status:'success',msg:'victory'}";
}else{
echo "{status:'failur',msg:'I am sorry to failure :('}";
}
And again: if you want get data via ajax,make sure print or echo the message on data page.
Try This
$.ajax({type: "POST",url: "../views/printdeal.php",data: { proc:"dealing",dealdatres=serow }});
if your problem in php, i think you can check values in global variables with
<pre>
<?php
var_dump($_REQUEST);
?>
</pre>
the result can be like this
array(2) {
["asd"]=>
string(3) "qwe"
["zxcv"]=>
string(5) "lkjsf"
}
that's result is from my localhost with url localhost/a.php?asd=qwe&zxcv=lkjsf
I need to pass array data through ajax, and also should post back it in another page.
but my code is not working, this is my code:
var data = [page_num: page, lstGend: <?php echo $gender;?>, lstFrom: <?php echo $fromyear;?>, lstTo: <?php echo $toyear;?>];
$.ajax({
type: "POST",
url: "data.php",
data:{ activitiesArray : data },
success: function(res) {
$("#result").append(res);
console.log(res);
}
});
POST the array:
$myArray = $_REQUEST['activitiesArray'];
foreach($myArray as $a){
echo $a['page_num'];
echo $a['lstGend'];
echo $a['lstFrom'];
echo $a['lstTo'];
}
Please help me guys, thnx
Send JSON data from Javascript to PHP?
Above issue is not same as mine, i need to pass multiple data(array data), please consider about this.
Replace
data:{ activitiesArray : data },
with
data:{ page_num: page,
lstGend: <?php echo $gender;?>,
lstFrom: <?php echo $fromyear;?>,
lstTo: <?php echo $toyear;?> },
and in PHP code make below changes.
Replace
$myArray = $_REQUEST['activitiesArray'];
foreach($myArray as $a){
echo $a['page_num'];
echo $a['lstGend'];
echo $a['lstFrom'];
echo $a['lstTo'];
}
with
echo $_POST['page_num'];
echo $_POST['lstGend'];
echo $_POST['lstFrom'];
echo $_POST['lstTo'];
I have this function which uses ajax, but this function doesn't work. I tried a lot, but I'm not able to figure out where the problem is. I am trying to create an alert, when the user inserts a duplicate entry into the database using a check-box selection.
<script>
function func(e,eid,emprid) {
if(document.getElementById(e).checked){
var dataString = 'eid=' + eid + '&emprid='+emprid;
$.ajax({
type:"POST",
url: "mylistcheck.php",
data: dataString,
success: function(result){
if(result!='0') {
modal.open({content: "<span style=\"color:red\" ><h2>You have already selected candidate </h2></span>"});
document.getElementById(e).checked=false;
}
}
});
}
}
</script>
mylistcheck.php looks like this:
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
$eid=$_POST['eid'];
$emprid=$_POST['emprid'];
$sqlchecklist="SELECT * FROM selected_candidate WHERE eid='{$eid}' AND rid='{$emprid}' ";
$checklistres=mysql_query($sqlchecklist);
$list_check=mysql_num_rows($checklistres);
echo "numrows listcheck".$list_check;
if($list_check>0) {
echo "1";
} else {
echo "0";
}
?>
The check-box code is like this:
echo "<td><input id=\"select_candi{$i}\" onclick=\"javascript:func(this.id,{$data_set['eid']},{$emprid})\" type=\"checkbox\" name=\"check_candi[]\" value=\"{$data_set['eid']},{$emprid}\"/></td>";
In your code you have
echo "eid".$eid;
$emprid=$_POST['emprid'];
echo "rid".$emprid;
Since you are already echoing the result your ajax functie will never be just '0'. Its always something like eid{value}rid{value}0 or eid{value}rid{value}1
Also switch to mysqli or pdo for security reasons. Also check the values of $eid and $rid to match what you expect. Your code is vulnerable for SQL injection.
In your script code you have onclick="javascript:func(...)". onclick is already a javascript function, so you dont need the javascript:
You are sending a POST request but the data is sent in GET form - i.e a string. You need to send it as an object instead:
$.ajax({
type:"POST",
url: "mylistcheck.php",
data: {"eid":eid,
"emprid":emprid}, // send an object
success: function(result){
if(result!='0')
{
modal.open({content: "<span style=\"color:red\" ><h2>You have already selected candidate </h2></span>"});
document.getElementById(e).checked=false;
}
}
});
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.