passing an array data through ajax and POST in php - php

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'];

Related

Can't post to PHP with AJAX

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;
?>

Passing value from one page to other using ajax

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

Storing values in a database via AJAX not working

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;
}
}
});

Ajax php jquery

I have an AJAX call on txt_RollNo's blur event to bring std_name,Class,age from database and fill it in txt_name,txt_class,txt_age.
In a single call can I have name,class,age all as a whole in array or any, how to seperate it.
$("#txt_RollNo").blur(function(){
$.ajax({
url:'getSudent.php',
data:'stdID='+ $(this).val().trim(),
success:function(array_from_php)
{
//but here i m receiving php array, how deal in jquery
//$("#txt_name").val(array_from_php);
//$("#txt_Class").val(array_from_php);
//$("#txt_age").val(array_from_php);
}
})
});
getSudent.php echos array as below
<?php
$qry=mysql_query("select * from students where studentID='".$_GET['std_ID']."'");
$row=mysql_fetch_array($qry);
echo $row;
?>
PHP:
<?php
header('Content-type: application/json');
$qry=mysql_query("select * from v_shop where shop_no='".$_GET['shopno']."'");
$row=mysql_fetch_array($qry);
echo json_encode($row);
?>
JavaScript
...
$.ajax({
dataType: 'json',
...
success:function(array_from_php){
console.log(array_from_php); // WTF is this?
See json_encode : http://php.net/manual/en/function.json-encode.php
First in php send it as json:
echo json_encode($row);
then just treat it as any array:
$("#txt_RollNo").blur(function(){
$.ajax({
url:'getSudent.php',
data:'stdID='+ $(this).val().trim(),
dataType : 'json',
success:function(array_from_php)
{
// i suggest you output the array to console so you can see it
// more crearly
console.log(array_from_php);
$("#txt_name").val(array_from_php[0]);
$("#txt_Class").val(array_from_php[1]);
$("#txt_age").val(array_from_php[2]);
}
})
});

Xml reply from PHP to post of jquery Ajax

i have a javascript code that requests a php page to provide it with list of names that are currently online and update a Table, but i have a problem sending it back in form of an array, someone told me that this is usually done using XML, but i dont know how to start.
javascript Post method:-
$.post( "updateTable.php", POSTdata,
function( data ) {
$("#mytable").last().append('<tr><td>'+data+'</td></tr>');
}
);
the php file:-
include("connect.php");
$query1 = "SELECT * FROM formtable";
$result_id = mysql_query($query1, $global_dbh)
or die ("display_db_query:" . mysql_error());
while ($table_array = mysql_fetch_object ($result_id))
{
$rows[] = $table_array;
}
foreach ($rows as $temp ) {
if ($temp->isOnline==1)
$newRow[] = $temp->name;
}
echo "$newRow";
mysql_close($global_dbh);
Please excuse any syntax or semantics in my code, i am a beginner.
How can i populate my table using ajax callback function, and in what form the data will arrive there, and how can i use xml to help me.
Many thanks in advance.
A quick example of json:
var table = $("#mytable").last();
$.ajax({
type: 'post',
url: "updateTable.php",
dataType: 'json',
data: POSTdata,
success: function(data){
jQuery.each(data, function(i, row){
//console.log(row);
table.append('<tr><td>'+row.name+'</td></tr>');
});
}
});
and in php file, instead of :
echo "$newRow";
replace with:
echo json_encode($newRow);
That's it!

Categories