Get Session value based on ajax success - php

I have a PHP page that uses a jQuery ajax call.
After I execute my AJAX and return a value on success, I need to use this value to pull an item from a PHP array, stored in session and update my SPAN with the new set.
Here's what I've got so far. I tested and I do return correct data value. I guess my syntax in jQuery is off, because my original span fades out, but nothing comes back.
JS:
$.ajax({
...
},
success: function(data){
var nextItem = <?php echo $_SESSION['items'][data]->desc; ?>
$('.x').fadeOut();
$('.x').attr(id, data);
$('.x').text(nextItem).fadeIn();
});
HTML:
<span id="'.$_SESSION['items'][0]->id.'" class="x">'.$_SESSION['items'][0]->desc.'</span>

You should return the session variable in the AJAX call. Execute the PHP code to get the session variable on the URL your AJAX call is hitting. The response of the AJAX call (in this case the 'data' variable in your success function) will be the result of:
<?php echo $_SESSION['items'][data]->desc; ?>
So no PHP code will be in your JS.
If you need to return multiple values, then you might consider using JSON. Your AJAX processing page might be like:
$result = array('id' => $id, 'session' => $_SESSION['items'][$id]->desc);
echo json_encode($result);
Your JS might look like this:
$("#getJSON").click(function() {
$.ajax({
...
success: function(data) {
$obj = $.parseJSON(data);
console.log($obj[0].id, $obj[0].session);
}
});
});​

Related

Getting only one record in the response using ajax

I have a small part of the code. I have to get the data using ajax but I am getting only one field.
There is no issue with the value and I am getting the correct one. I have to send the result to ajax but I am getting only one field.
I believe there is some issue with my array.
$result=[];
if ($haschange['fb']==1) {
$result[]="<input type='text' value='".$social_links['fb']."'>";
}
if ($haschange['twitter']==1) {
$result[]="<input type='text' value='".$social_links['twitter']."'>";
}
if ($haschange['linkedin']==1) {
$result[]="<input type='text' value='".$social_links['linkedin']."'>";
}
if ($haschange['instagram']==1) {
$result[]="<input type='text' value='".$social_links['instagram']."'>";
}
echo json_encode($result);
exit();
script
<script type="text/javascript">
$(document).on('click', '.pendingContent', function(){
var id=$(this).data("id");
//alert(id);
$.ajax({
url: 'process.php',
method:'post',
dataType: "json",
data:{action:"pendingContent",id:id},
success: function(data){
$('#shaedcontent').html(data);
$("#pendingContent").modal('show');
}
});
});
</script>
Your and other comments basically already described it. If we assume that $haschange has different values, your array should be okay. If you are not sure, just check the return of that function inside your browser within the developer tools.
As we should have an array posted to the ajax function, you should have an array. Your access on the array is not correct as you just add the array (json string) to the html element.
The best approach is to use a foreach loop to go through each object within the json response. If you are not sure what you have received in the ajax method, just use console.log(data). With this you should see a proper json object.

Posting data from ajax to php

Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});

Can't get data back from an Ajax get request

Been playing with this for too long now!
I'm using codeigniter.
I am trying to get some data back from an Ajax get request. Simply I want to check a MySQL DB to check if there is some data in there mathcing a given date. A simple true or false will be fine for the return.
Here is my request, followed by the PHP. The PHP does return the correct result into $data, but when it gets back to the Ajax request, the alert(data) is called and shows up as blank... nothing there.
Any ideas what I'm doing wrong?
Thanks
function get_appointment_data(request_date){
$.ajax({
url: 'http://localhost/doctor_today/booking/retrieve_cal_data',
type: 'GET',
data: request_date,
success: function(data){
alert(data);
}
});
}
function retrieve_cal_data() {
$this->load->model('Booking_model');
$date = $this->input->get('date');
$data = $this->Booking_model->get_calendar_data($date);
return $data==null;
}
I am not familiar with codeigniter but you must output the result of the function. Instade of 'return' you must use 'echo' to return result to ajax request.
You have to echo the result, otherwise your ajax won't receive a result and the success handler won't execute. Here is what I'm going to use for this case, I'm using the simpler .post function for that task with one key difference - I specify 'json' at end of it which means I'll get a json object as a result from my .post (you can search Google for this). The next key is to use encode the result I wanna get in json format using PHP's json_encode function and echo its result. We don't really need to return a result via the normal 'return' statement. So...
The script:
var url = 'http://example.com/ajax_function';
var data = null;
$.post(url, data, function(data) {
if(data.ok)
alert('Everything is fine!');
else
alert('Ops!');
}, 'json');
The server side:
function retrieve_cal_data() {
$this->load->model('Booking_model');
$date = $this->input->get('date');
$data = $this->Booking_model->get_calendar_data($date);
echo json_encode(array('OK' => $data==null));
}
If you call directly the PHP function it should output something like
{ "OK": "true" }
which later on will be translated to an javascript array
data[OK] = true;
which you can use as you wish.
Cheers,
Stan.
P.S. I haven't tested the code but it should pretty work.

How to do a GET on a PHP page to get a JSON object?

How do I accomplish the following:
User clicks on "Start" button on an HTML page makes a GET to a getnumber.php page, that returns the number 10 in the following form: {count: 10}
//you jquery code
$.getJSON('getnumber.php', function(data) {
alert(data); //returns your json_encoded number sent from getnumber.php page
});
//your php page
$arr = array("count" => 10);
echo json_encode($arr);
<input type="button" id="btnID"/>
$("#btnID").click(function(e){
e.preventDefault(); //prevent the default behavior of the button, or return false as #alecgorge pointed it out
$.get("process.php",function(data){
console.log(data);
},'json'); //<-- specifying the dataType as json will parse the json return by the server
});
in the process.php
var $count=10;
echo json_encode($count);
look at
json_encode
$.get()
Try Google.
Here is a good place to start.
Then go here and learn more.
Put them together and you should be well on your way.
You need PHP return data in JSON format, which would be:
{"count": 10}
and indicating the returning data is JSON format with a header in the response.
From JavaScript side the returned value, the previous string, can be evalutated and converted to a JS object.
use json_decode in getnumber.php
json decode manual page
Try something like this
$.get('getnumber.php', function(data) {
var result = eval(data);
});
If the page getnumber.php output {count: 10} then you get the result with result.count
You can also use $.getJSON method.

PHP + Jquery - pass value through ajax to php and check against variable

I can't get the following PHP + jQuery to work - all I want the script to do is pass the value through ajax, and get the php to grab it, check it matches and add 1 to score.
This is the code I've written:
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}else{
//Do nothing
}
echo $score;
?>
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
var value = "145";
alert(value);
$.ajax({
url: 'processing.php', //This is the current doc
type: "POST",
data: ({name: value}),
success: function(){
location.reload();
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
Thanks for the help, I've changed GET to POST in both instances, and no joy - there's something else wrong.
First of all: Do not go back to the dark ages... don't use the same script to generate HTML and to respond to an ajax request.
I can't make any sense of what you are trying to do... Let me change your code so it at least makes some sense and document what's going on. It seems like the problem is the fact that you are calling location.reload from your success handler.
// ajax.php - Outputs 2 if the name parameter is 145, 1 otherwise (????)
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}
echo $score;
?>
// test.html
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
// Why were you reloading the page? This is probably your bug
// location.reload();
// Replace the content of the clicked paragraph
// with the result from the ajax call
$("#raaagh").html(data);
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
You use POST in your jQuery, but you try and get a GET in you php.
BTW it is good practice to check if a GET/POST variable is set before reading it.
using the isset() function.
Replace $_GET with $_POST and there you are.
Basically POST and GET are two different way to pass variables to a script. The get method in php can also be attached at the end of a url : script.php?variable=value and it is really easy to hack. While the post method can be submitted with forms or ajax calls and it is pretty safe, at least more than the get.
Also i'd suggest you to check whatever a GET or POST variable is set before calling it, so that you can prevent stupid notice errors.
Just use the following code:
if (isset($_POST['var']) and !empty($_POST['var'])) { // do something }
You can also delete the
}else{
// do nothing
}
part of the script, since the else clause it is not necessary always.
You're submitting the data with an Ajax POST, but trying to read it out of a GET. Either use type: "GET" in your Ajax call or $_POST['name'] in your PHP.
The problem is you are using jQuery to POST your value, yet you are reading it with GET.
You should be able to fix your problem by changing your $_GET['name'] to $_POST['name']

Categories