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;
}
}
});
Related
This question might have been asked a few times, but I couldn't find any solutions to my problem.
So I created a list consisting of names of sweets (here Marshmallow, Milk Chocolate), I want to pass this as a string to a php file using POST. Here is my current code:
<script>
function passJSON(){
var endValues = $("#sweets").val().toString();
$.ajax({
type: "POST",
url: "temporaryEchos.php",
data: { sweetsAJAX : endValues },
success: function(){
var endValues = $("#sweets").val().toString();
alert(endValues);
}
});
}
</script>
<button onclick="passJSON()">Click me to get data!</button>
$("#sweets").val() returns Marshmallow, Milk Chocolate, but I found I had to convert it to string for it to properly work.
Here's my temporaryEchos.php
<?php
$sweets = $_POST["sweetsAJAX”];
echo $sweets;
foreach ($sweets as $value){
echo "Value: $value <br>";
}
echo "sweets set successfully!";
?>
after clicking submit the $.ajax success function returns Marshmallow, Milk Chocolate, but the PHP only echos "sweets set successfully!". How could I go around this?
Change sweetsArray to sweetsAJAX
<?php
$sweets = $_POST["sweetsAJAX"];
echo $sweets;
?>
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
this is my php script from which am returning the value to the ajax calling it
<?php
$questionid=$_GET['qid'];
$answer=$_GET['clickedvalue'];
$dbconnect=mysqli_connect('localhost','root','','quiz')or die("Error Connecting to database");
$query="select answer from question_answer where id=$questionid";
$result=mysqli_query($dbconnect,$query);
while($rows=mysqli_fetch_array($result))
{
$dbanswer=$rows['answer'];
}
//array values which will be passed to json
$result=array('correct'=>'Correct Answer',
'incorrect'=>'Incorrect Answer'
);
if($dbanswer==$answer)
{
//json to be passed to next page with key value pair
echo json_encode(array('display_msg'=>$result['correct'],'points'=>'positive'));
}
else{
echo json_encode(array('display_msg'=>$result['incorrect'],'points'=>'negative'));
}
?>
and this is my ajax code
$.ajax({
url:'checkanswer.php',
dataType:'json',
data:{'clickedvalue':clickedvalue,'qid':qid},
success:function(data){
$this.find(".report").html(data.display_msg);
$this.delay(1000).slideUp();
}
});
So my question is how do i store the value of data.points object that is passed from the php as a json in the javascript variable or is it not possible to store in javascript variable directly if yes how and if no what will be the way to get the value and store somewhere
Just add a temp variable before calling ajax
Some thing like this
var myTempVariable; //Temp JS variable to use somewhere else
$.ajax(
{
url: 'checkanswer.php',
dataType: 'json',
data:
{
'clickedvalue': clickedvalue,
'qid': qid
},
success: function(data) {
$this.find(".report").html(data.display_msg);
$this.delay(1000).slideUp();
myTempVariable = data; //assugn value to temp varaible
}
});
in your ajax success function :
var myVariable = data.points;
This might help
I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.
I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.