Can't access data in php file sent via jquery ajax [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to access some data in php file sent via jquery ajax method
but I get an error of Undefined Index.
sender.php
$('#slot1').click(function(){
var selectedDate = $('#selectedDate').html();
var timeSlot = $('#timeSlot1').html();
var hm = timeSlot.slice(0, 5);
var seconds = ':00';
var time = hm + seconds;
$.ajax({
url: 'insertBookings.php',
type: 'post',
data: {date: selectedDate, timeslot: time},
async: false,
success: function(data) {
alert(data);
}
})
})
reciver.php
<?php
$date = $_POST['date'];
echo date;
?>

Consider testing with the following.
$('#slot1').click(function() {
var selectedDate = $('#selectedDate').text().trim();
var timeSlot = $('#timeSlot1').text().trim();
var selectedTime = timeSlot.slice(0, 5) + ":00";
$.ajax({
url: 'insertBookings.php',
type: "POST",
data: {
"date": selectedDate,
"timeslot": selectedTime
},
async: false,
beforeSend: function() {
console.log("Sending Date: " + selectedDate + ", Time: " + time);
},
success: function(data) {
console.log("Received: ", data);
},
error: function(xhr, status, error) {
console.log("Error:", status, error);
}
});
});
No major changes, yet I switched from .html() to .text(). The former will gather more than just the text if there is anything. Since you did not provide a Minimal, Reproducible Example, this is a precaution to ensure you're not capturing incorrect items before sending them.
I also added some extra Ajax code to help see each part as it happens.
In your PHP, you have a syntax error too. You are missing a $ before date.
<?php
$date = $_POST['date'];
echo $date;
?>

Related

How to Parse php json_decode data to Jquery Ajax request [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
The current problem now is this, the below files are working perfectly well, but when using console.log(data), it prints out the result I wanted very well.
But what I want is to print out the result in a html tag (div) profoundly instead of console.log().
The Php File section
<?php
$transaction_id = $_POST['transaction_id'];//get the Transaction ID from Ajax request..
//get the full transaction details as an json from VoguePay
$json = file_get_contents('https://example.com/?v_transaction_id=' . $transaction_id . '&type=json');
$transaction=json_decode($json, true);
//header('Content-Type: application/json');
echo json_encode($transaction);
The Ajax Section...
//clear the display section
$("#id-input2").html('');
var data="";
//call the Ajax Request..
$.ajax({
url: "php/fetch_transaction_id.php",
type: "POST",
data: {transaction_id:transaction_id},
dataType: "json",
success: function (vp_response) {
$.each(vp_response, function(index, value) {
data=(index + ': ' + value);
console.log(data);
});
$('#searchID').val('Data Recieved!');
},
});
Here is the output for using console.log();:
cur: NGN
transaction_id: 5a3182d82a8c6
email: talk2awe2004#example.com
total_amount: 1016.7000
total: 1000
merchant_ref:
memo: MLM Bank Union Creation
status: Approved
date: 2017-12-13 20:49:26
method: MasterCard & Verve (Naira)
referrer: https://www.mlmbank.net/Leaders/create.html
total_credited_to_merchant: 1001.450000
extra_charges_by_merchant: 16.700000
charges_paid_by_merchant: 15.250000
fund_maturity: 2017-12-15
merchant_id: 3362-0054095
total_paid_by_buyer: 1000
process_duration: 0.000395
I want same using a html tag instead.
You can return your array in JSON format with application/json content-type
<?php
if(isset($_POST['transaction_id'])) {
//get the full transaction details
$json = file_get_contents('https://example.com');
//create new array to store our transaction
$transaction = json_decode($json, true);
// Here you can do something with $transaction
// And return it in JSON format for ajax request
header('Content-Type: application/json');
echo json_encode($transaction);
}
After that you can get this json in ajax like this
<script>
$.get('transaction.php', {transaction_id: 'SOME ID'}, function(data) {
console.log(data);
});
</script>
jQuery will parse data as javascript object because of content-type
If the link you reach out to has raw json, you can simply echo it out :
PHP
if (isset($_POST['transaction_id']))
{
$TransactionId = $_POST['transaction_id'];
echo file_get_contents('https://example.com');
}
You want to add the success event handler in your ajax call and then $.each through your response. :
*Note : Make sure you have dataType: 'json', this tells jquery to parse the json response.
Javascript :
$.ajax({
type: 'POST',
url: '/yourphpfile.php',
data : {
transaction_id: '0'
},
dataType: 'json',
success : function(response) {
$.each(response, function(key, value) {
console.log(value.whatever);
});
}
});
Read more on accessing json values : jQuery Ajax: get specific object value

Getting JSON data with jquery ajax not working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to understand how to fetch and display data with jquery ajax. I have a php page (data.php)that successfully retrieves data from a mysql database and encodes that data into a json array. Client side I have a page called get.php. I just can't figure out why my script will not fetch any data from data.php I get nothing in the firebug console.
data.php
echo json_encode($mydata);
which outputs:
[
{
"id":"236",
"title":"The Jungle Book"
},
{
"id":"235",
"title":"The Shallows"
},
{
"id":"232",
"title":"For Your Eyes Only"
},
{
"id":"231",
"title":"Ice Giants"
}
]
get.php
<script>
("button").click(function(){
{
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var title = data[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});
</script>
<h3>Output: </h3>
<button>Get Data</button>
<div id="output"></div>
You have few mistake like: you didn't specify jquery($) for button
selector, you use multiple bracket { inside click function, inside
ajax success you have assigned full object against id and title it
should be id=data[0]['id'] and title=data[0]['title] and another
mistake there no defined variable vname. php better json output you should use header('Content-Type: application/json'); in data.php.
Try this:
index.php
<h3>Output: </h3>
<button>Get Data</button>
<div id="output"></div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$("button").click(function(){
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(data){
//console.log(data);
var id = data[0].id;
var title = data[1].title;
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+title);
}
});
});
</script>
data.php
<?php
header('Content-Type: application/json'); //use header to specify data type
//echo json_encode($mydata); // un-comment this line
echo '[{"id":"236", "title":"The Jungle Book"}, {"id":"235", "title":"The Shallows"}, {"id":"232", "title":"For Your Eyes Only"}, {"id":"231", "title":"Ice Giants"} ]'; // comment this line
?>
<script>
$("button").click(function()
{
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var title = data[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});
try like this

How to handle click event on Submit Button [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Here is my script for handling submit button click event
$('#subbtn').on("click",function(){
var stcode = $('.stcode11').val();
var sem = $('.sem11').val();
var doa = $('.doa11').val();
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: 'stcode='+stocde+'&sem='+sem+'&doa='+doa,
success: function(msg)
{
$('.atnresult').html(msg);
}
});
});
And here is the button code
<button id='subbtn' type='submit' class='button'> Change </button>
But it not working properly. Please help me to handle click event of submit button.
You should handle the submit event of form Then you can use event.preventDefault() to cancel the default action.
$('YourFormSelector').on("submit",function(event){
//Cancel default event
event.preventDefault();
//Rest of your code
});
First, the way you are doing the submit requires you using e.preventDefault(); to prevent your form from being submited via html.
Second, the way you pass the data is wrong/the way you would do for a GET operation. As you are trying to submit via POST, you need to create data like this:
data: {
stcode : stocde
sem : sem
doa : doa
}
Full code:
$('#subbtn').on("click",function(e)
{
e.preventDefault();
var stcode = $('.stcode11').val();
var sem = $('.sem11').val();
var doa = $('.doa11').val();
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: {
stcode : stocde
sem : sem
doa : doa
}
success: function(msg)
{
$('.atnresult').html(msg);
}
});
});
Try this:
$(document).on("click","#subbtn",function(e)
{
e.preventDefault();
var formData = new FormData();
formData.append( 'stcode', $('.stcode11').val());
formData.append( 'sem', $('.sem11').val());
formData.append( 'doa', $('.doa11').val());
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: formData,
success: function(msg)
{
$('.atnresult').html(msg);
}
});
});
replace this line
data: 'stcode='+stcde+'&sem='+sem+'&doa='+doa,
with
data: 'stcode='+stcode+'&sem='+sem+'&doa='+doa,
full code with preventdefault
$('#subbtn').on("click",function(e) {
var stcode = $('.stcode11').val();
var sem = $('.sem11').val();
var doa = $('.doa11').val();
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: 'stcode='+stcode+'&sem='+sem+'&doa='+doa,
success: function(msg)
{
$('.atnresult').html(msg);
}
});
e.preventDefault();
});

refreshing php content inside div when input onchange [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a simple <input> and when user writes there something I need to refresh php inside div so it will look like some.php?key=thevaluefrominput. How would I do that? I guess I need to use query but I'm not sure how.
I want something like this when you write something to Type to find tags it changes the the tags bellow.
Thanks for the answers.
This sounds like a job for AngularJS :)
However this is jQuery solution:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'some.php',
data: 'key=' + escape($.trim($('#myinputfield').val())),
dataType: 'html'
}).done(function (data) {
if (data) {
$('#divtopresent').html(data);
}
});
});
});
If you mean that while user types (before submission), div content changes? Then remove
$('form').submit(function (e) {
e.preventDefault();
and instead put
$('#myinputfield').keydown(function () {
There is a setInterval method that I mentioned in comment, so the first chunk of code I posted, replace it with this one:
$(function () {
var old_val = '';
var curr_val = '';
setInterval(function () {
curr_val = $.trim($('#myinputfield').val());
if (old_val != curr_val) {
old_val = curr_val;
$.ajax({
type: 'POST',
url: 'some.php',
data: 'key=' + escape(curr_val),
dataType: 'html'
}).done(function (data) {
if (data) {
$('#divtopresent').html(data);
}
});
}
}, 2000);
});
It checks if value of the field changed every 2s, please replace amount in ms (2000) if you like.

How to store value passed by ajax to database? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to display data or value return by the ajax function to be store in php variable as mentioned below. Any help?
This is my code
function getUserInfo()
{
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
I want to display in php variable as
$name=$_POST['uName'];
$pics=$_POST['imgHolder'];
echo $name;
echo $pics;
I would use PHP to make the request and store the result in an array, since you need to use the result in php
$acToken='your value';
$result = file_get_content('https://www.googleapis.com/oauth2/v1/userinfo?access_token='.$acToken);
echo '<pre>';
print_r($result);
echo '<pre>';
make sure to assing a value to $acToken;
In your javascript, create ajax post request to your php url:
$.ajax({
type: "POST",
url: "some.php",
data: { uName: "John", imgHolder: "img" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
For more information, you can read jQuery AJAX documentation
try below:
$name=$_POST['uName'];
$pics=$_POST['imgHolder'];
echo json_encode(array('name'=>$name,'pics'=>$pics));
as that help for you

Categories