Passing value from one page to other using ajax - php

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

Related

Why is my php variable made with ajax keeping empty?

First, precisions : I'm using MAMP and Brackets, and Chrome to test.
Here's what I have :
<ul>
<li class="brick" data-pseudo="one">Some text or elements</li>
<li class="brick" data-pseudo="two">Some text or elements</li>
<li class="brick" data-pseudo="three">Some text or elements</li>
</ul>
li.bricks are just rectangle articles "linking" to Work1, Work2 and Work3, and generated by a PHP function from an array.
I'm trying to get the "pseudo" data of the clicked .brick to put it in a PHP variable and use it to call another array in another php function, in order to generate the HTML elements of Work1, Work2,...
I found I had to use AJAX and managed to get that code :
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
$('.brick').click(function(){
//some code
pseudo = $(this).data('pseudo');
sendPseudo(pseudo); //calling sendPseudo() function
});
And here's my testing PHP function :
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
... I'm calling in my HTML document :
<section class="site">
<div class="left">
<?php loadWork() ?>
</div>
<div class="right">
//some other content
</div>
</section>
And so I have two problems. Firstly, when a .brick is clicked, the alert pops up but it's empty, absolutely nothing appears in it, but when I console.log the var pseudo, I see "one", "two"... And secondly, the echo in testing PHP function does not generate the paragraph with the pseudo.
Pleeeaaase, help me to find out what I'm doing wrong, it's making me go crazy !
Thank you !
I think there is some confusion in your order. loadWork(), as you say, is part of an html file gets called as soon as the browser reads the html file and it's only called once. If loadWork() hasn't been defined yet (or exists in another file as your AJAX request suggests based on it's call to my_php_function_page.php) then it won't output anything. In other words, loadWork() needs its post data to exist when the browser requests the html.
You can put the php in the same file as the html that is being called on, but it looks like you might be trying to get the results of loadWork() inserted into a div that already exists. Change your ajax function so that if(data!="") changes the inner html of your div to include the data:
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
$('.left').html(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
I think you have missed calling your function loadWork() in my_php_function_page.php, this code may be fix your empty alert issue.
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
data=data.trim(); // to remove the unwanted space around the string
success: function (data) { //testing the success
if(data!="")
{
alert(data);
$(".right").html(data); // This adds your AJAX success data to the class left inside your DIV
}
else
{
alert("You're wrong !");
}
},
});
}
my_php_function_page.php
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
loadWork();
I'm not sure why, but sometimes data function is not working, so I always use attr('data-pseudo') in your case.
so it would be like this:
pseudo = $(this).attr('data-pseudo');

AJAX URL issue…very odd

I have a page from which I am trying to make an AJAX call, but it isn't working, and I'm stumped as to why. My call is:
$.ajax({
type: "GET",
url: "<relative URL>/index.php?action=x",
dataType: "JSON"
}).success(function(person) {
alert(person.name) //alerts naem
});
return false;
});
and the PHP is:
<?
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
header("Content-Type: application/json");
echo json_encode($person);
}
?>
I don't THINK the issue is a faulty URL, since it is a c/p of working calls. It seems to me (but I'm not sure) that it chooses to reuse the old 'action-values' from when the source page was loaded originally. For some reason it completely ignores my action-value…?
Any ideas?
Try moving the PHP into its own file rather than the index.php, which I assume is your main PHP file.
$.ajax({
type: "GET",
url: "/ajax.php?action=x",
dataType: "JSON",
success: function (person) {
console.log(person.name);
}
});
This should be a separate file. Call it ajax.php for an example.
<?
// ajax.php
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
die(json_encode($person));
}
?>
Just make sure ajax.php is in the route of your project and this should work. Check the console.log if it doesn't.
Try moving the variable into 'data':
$.ajax({
type: "GET",
url: "<relative URL>/index.php",
data: "action=x",
success: function (person) {
console.log(person.name);
}
});
Since you are calling index.php with a get parameter, you might be echoing the json_encode and then continuing to output everything else after the if statement.
Try this?
<?
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
header("Content-Type: application/json");
echo json_encode($person);
exit;
}
?>
I'm assuming you have more content in the index.php below that if statement. If so, the exit; statement would be needed so that you only echo the json and not anything after the if statement.
The ajax response can be viewed in Google Chrome's Dev Tools, under the Network tab.
Let's say you had no exit; statement:
<?
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
header("Content-Type: application/json");
echo json_encode($person);
}
?>
<html>
<head></head>
<body>
...etc, etc
The ajax response under Dev tools would look something like this:
{"name":"Jon Doe","Reputation":"Good"}<html><head></head><body>... and so on
which would then try to be parsed by the $.ajax into a JSON object.
But this is not possible because <html><head></head><body>... is not valid JSON.
Hope this helps!

Using ajax to call a php function

I have a main page in my app called index.php where i want to show some photos. Code in that file is:
<div id="main" name="main">
<input type="button" value="Photos" onclick="showIm()">
</div>
File function.php contains a function to show photos on the screen:
function showPhotos()
{
global $link;
$result = pg_query_params($link, 'SELECT photo_name FROM photos');
while($photos_row = pg_fetch_row($result))
{
echo '<a href="photos/'.$photos_row[0].'">
<img src="photos/'.$photos_row[0].'"></a>';
}
}
My last file is function.js where i try to call showPhotos using ajax
function showIm()
{
$.ajax({
url: "functions.php"
})
}
So inside the last function I want to call showPhotos() to get the results. I think that my implementation is a little complicated but I would like to know if anyone could help.
Well, you have to do something with that result! Add a success method and declare a return dataType
function showIm()
{
$.ajax({
url: "functions.php",
dataType: "html",
success: function(html) {
//do something with the response here
//the "html" variable will contain your PHP response
}
})
}

Running a PHP Script without redirecting or refreshing the page

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

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

Categories