Can't post to PHP with AJAX - php

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

Related

AJAX how to grab returning value AND database connections

I am quite new to jQuery and AJAX.
I am sending the request via AJAX to check file 'test' every 5 seconds which works fine. 'test' stands for test.php file.
<script>
$(document).ready(function () {
function load() {
var test = "<?php echo $test; ?>/";
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: test,
dataType: "html", //expect html to be returned
contentType: "text/html",
success: function (response) {
$("#responsecontainer").html(response);
setTimeout(load, 5000)
}
});
}
load(); //if you don't want the click
// $("#display").click(load); //if you want to start the display on click
});
</script>
<div id="responsecontainer"></div>
test.php
$id = $this->session->userdata('UserID');
$get_friends_notification = $this->friends_model->get_friends_alert_by_ID($id);
if(isset($get_friends_notification) && !empty($get_friends_notification))
{
?>
<div id="test" style="width:200px; height:auto; border:1px solid red;">
<h3>Friend invitation from:</h3>
<?php
foreach($get_friends_notification as $key => $value)
{
$new_id = $get_friends_notification[$key] = $value["FrieInviter"];
$new_name = $get_friends_notification[$key] = $value["UserName"];
echo ''.$new_name.'<br />';
}
?>
</div>
<?php
}
Then it just displays it in the div # responsecontainer which works fine too.
$("#responsecontainer").html(response);
In the file 'test' I am checking database if there were any updates.
So I am pulling the information from DB and return to #responsecontainer. As it runs every 5 seconds, after it ran for the first time I would like to grab the last ID that I pulled and before it runs again and save it in variable and then I would like to pass that ID to the 'test' or process it differently. Basically I want to be able to use it. How can I do that??
EXAMPLE:
ajax checks test.php file and find 5 rows. returns these 5 rows with 5 IDs. The last ID is number 5. In the meantime there were some other rows inserted so next time it will find more rows.
Before it checkes again I want to tell it to not to check ID 1,2,3,4,5 but start from ID 6.
Also how does this method works with DB connections? Assuming that I have for example 500 users, and on all of theirs profiles that check would run every 5 seconds wouldnt it kill database connections?
Basically you need to add a pgination effect in here. Pass a parameter in the ajax request for example : if you are getting 5 records at a time,
then initialize a variable say
current_page = 0 , increment the same as you request via ajax
var current_page=0;
function load() {
var test = "<?php echo $test; ?>/";
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: test,
data : current_page
dataType: "html", //expect html to be returned
contentType: "text/html",
success: function (response) {
if(response.length!==0){
$("#responsecontainer").html(response);
current_page+=1;
}
setTimeout(load, 5000)
}
});
}
in the php page make the necessary changes (hope you know how pagination is done).

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

how to get the values from php to javascript variable is it possible

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

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

Using the JQuery .Ajax() method?

I am creating a site where the user fills out a form, has that data sent to a php script and display result in a div and have been struggling to complete it for a while now. Below is the code i have created:
the button activates this function:
function callFunc()
{
var testVar = "Example 01";
$.ajax(
{
url: "public/includes/userCreate.php",
type: "POST",
data: testVar,
success: function(html)
{
$('#web_Content').html(html);
}
});
};
The PHP file is this:
<?php
$test = $_POST['testVar'];
echo $test;
?>
For some reason though i doesnt work. I mean it doesnt inject the value of the echo command into the div, If however i take out the variable data from the PHP and just have it echo a simple element, it does work and injects the echo value into the div, Below is the code that will run:
<?php
$test = $_POST['testVar'];
echo "<h3>User ???? Created.</h3>";
?>
I think it is because i am not sending data correctly, Could anyone tell me the correct way to send the data to the PHP script and also, how to send more than one variable?
you need data: { testVar: "Example 01"} it is a key value pair. This will generate a query string parameter like testVar=Example%2001
The correct way to send data via the AJAX function is with either an object or string. Examples:
var pData = "testVar=Example.";
$.ajax({
/* Other ajax params */
data: pData,
/* Other ajax params */
});
or
var pData = { testVar: "Example." };
$.ajax({
/* Other ajax params */
data: pData,
/* Other ajax params */
});

Categories