Not recieving values sent via AJAX POST to PHP - javascript

I'm trying I'm trying to send a specific section of my URL string, to my php file, to then populate my page accordingly. Everything is working fine, except for the AJAX POST method. I've tried doing var_dump of the POST variable in my PHP, and my array is empty (so I know nothing is getting through).
The success DOES return as being passed, so I don't know where the data is going. I'm testing locally on XAMPP, and I've combed through SoF and no luck on any of the fixes. My code is below.
Screen shot of page:
jQuery AJAX Request:
$(document).ready(function() {
str = window.location.href;
pos = str.search("pages/"); //42
send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
tom: send
},
success: function() {
$.get("retrieve.php", function(data, status) {
$("#main").html(data);
}) //ends GET function
},
error: function() {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
echo "<i>hello</i>";
echo var_dump($_POST);
$url = $_POST['tom'];
json_decode($url);
echo $url;

Try the below,
Also you don't need to json_decode unless you send a json request,And please make sure all the post values are passing.
Ajax:
$(document).ready(function() {
var str = window.location.href;
var pos = str.search("pages/"); //42
var send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
'tom': send//make sure this is not empty
},
success: function(data) {
console.log(data);
},
error: function(arguments) {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//echo "<i>hello</i>";
//echo var_dump($_POST);
$url = $_POST['tom'];
json_encode($url);
echo $url;
}

Related

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

Passing a PHP variable to JavaScript For AJAX Request

So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. The $content is a card (similar to KickStarter) of topic data. What I'm trying to do is a pass the 'topic_id' of each topic-instance so that I can then use it in the success function, to then initiate ANOTHER AJAX request (but to Discourse).
With attempt 2), I get a null when viewing its value in the web inspector.
The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console):
$.post( "/wp-content/mu-plugins/topic-search.php", { topicID: $topicFilter, filterBy: $sortByFilter },
function( data ) {
console.log(topic_id);
data = data.trim();
if ( data !== "" ) {
//get the participants data for avatars
$.getJSON('http://ask.example.com/t/' + topic_id + '.json', function() {
The end of topic-search.php, which echoes out the built up card. Script is supposed to return the topic_id variable for use in the success function.
}
//One attempt: echo $content; //
//Another attempt: echo json_encode(array('data' => $content, 'topic_id' => $row['topicid']));//
}
?>
<script>
var topic_id = "<?php echo $row['topicid'] ?>";
</script>
Try this:
In php
$inputJson = file_get_contents('php://input');
$input = json_decode($inputJson, true); //Convert JSON into array
In javascript
var $url = '/wp-content/mu-plugins/topic-search.php';
var $json = JSON.stringify({topicID: $topicFilter, filterBy: $sortByFilter});
$.ajax({
url: $url,
type: "POST",
data: $json,
dataType: "json",
success: function(data){//you will have the body of the response in data
//do something
},
error: function(data){
//do something else
}
});
EDIT:
This will request $url with the $json data. You will have it available on $input on the server side as an array. You can then on the server prepare a response with a json body that you will have available on the success function as the data variable.

Returning html as ajax response

I have web page that submits a form via AJAX in codeigniter, submission works great, and the php script works as well, but when php is done it return an HTML view as a response to Ajax so it repopulates a div but instead of repopulating it try's to download the file. Chrome console shows
Resource interpreted as Document but transferred with MIME type application/text/HTML
has me confused because I use the same code in another page and it works fine.
This is my Jquery script
$("#addpaymentform").submit(function (event) {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
data: formdata,
url: baseurl + 'sales/add_payment',
success: function (data, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
$('#paymets').html();
$('#payments').html(data);
$('#addpaymentform').each(function() { this.reset() });
}
if (ct.indexOf('json') > -1) {
$("#Mynavbar").notify(
data,
{position: "bottom center"}
);
$('#addpaymentform').each(function() { this.reset() });
}
}
});
event.preventDefault(); // this will prevent from submitting the form.
});
and this is my controller
function add_payment()
{
$this->form_validation->set_rules('fpay', 'Type of payment', 'trim|required|alpha');
$this->form_validation->set_rules('payment', 'Payment', 'trim|numeric');
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
header('Content-type: application/json');
echo json_encode(validation_errors());
} else {
$fpay = filter_var($this->input->post('fpay'), FILTER_SANITIZE_STRING);
$payment = filter_var($this->input->post('payment'), FILTER_SANITIZE_STRING);
if(isset($_SESSION['payments'][$fpay]))
{
$temp = $_SESSION['payments'][$fpay] + $payment;
$_SESSION['payments'][$fpay] = $temp;
header('Content-type: application/html');
echo $this->_loadpaymentcontent();
}
}
}
function _loadpaymentcontent() {
$this->load->view('payment_content');
}
Hope someone can point me in the right direction I've been stuck on this for 2 days.
Thanks everyone.
I had the same problem and i successfully solved it by putting an exit; after the value which is returned to the ajax call in the controller method.
In your case it will be:
echo $this->_loadpaymentcontent();
exit;
What exit does here is it limits the returned value to the value which should be returned to the ajax call and exits before the html is appended to the returned value.
This is what is obvious per the effect it produces.
Yo need to set up your AJAX.
$.ajax({
type : 'POST',
url : baseurl + 'sales/add_payment',
dataType : 'html', // Will set the return type of the response as AJAX.
... Keep rest of the code same.

How to avoid 500 Internal Server Error if a JS session variable null

I created this script to read from various web sources. This script updates all notifications (mail, post, friends) and their own drop-down window's details and also two side update bars together. I used this script in my top manu.php page.
This script is working well for login user.
Now I pass a session id variable with JavaScript var uid = '<? echo $session->id; ?>'; So when a user is not logged in, my browser console displays 500 Internal Server Error because here the session has no ID so it passes uid= ''
How do I overcome this problem?
Here is my JavaScript script:
var uid = '<? echo $session->id; ?>';
function addmailno(type, msg){
//Do something for display mail/friend/post notification
}
function addmailup(type, msg){
//Do something for display mail/post/friend drop-down.
}
function addside(type, msg){
//Do something for display all friend/new post in side bar.
}
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
setTimeout(waitFormailno, 15000);
},
error: function(){
setTimeout(waitFormailno, 15000);
}
});
}
$(document).ready(function(){
waitFormailno();
});
serverforupandside.php
<?php
include("db.php");
include_once("mysession.php");
while (true) {
if($_GET['uid']){
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
flush();
mysqli_close($dbh);
}
}
mysqli_close($dbh);
}
?>
Your Javascript code should be modified to:
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
}
});
}
$(document).ready(function(){
setInterval(waitFormailno, 15000); // calls a function or evaluates an expression at specified intervals (in milliseconds)
});
PHP Code:
<?php
include("db.php");
include_once("mysession.php");
if (!empty($_GET['uid'])) {
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
}
}
Also, you should add validations before filling $data array.

Ajax.stop function with json request issue

I am trying to read from a database some data but without waiting for the page to load, so I created an ajax post that starts sending data when page is ready, now after ajax completes I need to read the values from another file. The problem is that after the ajax completes, json that is reading the data is running indefinite.
JQUERY
<?php $url = $_GET['url']; ?>
var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0(document).ready(function () {
var domain = '<?php echo $url; ?>';
$.ajax({
type: 'POST',
url: 'lib/ajax.php',
data: {
action: 'get_all_seo_details', // function that collects data
domain: domain // the domain that is being send to the function in order to get data
},
success: function (data) {
// doesn't need to echo anything only to insert the data, which it done properly
}
});
// Below is the second part of the script that starts when ajax stops
$(document).ajaxStop(function () {
$.getJSON('lib/get-details.php', function(data) {
var twitter_followers = data.twitter_followers;
$('#twitter-followers').html(twitter_followers);
});
// data is being read correctly but it loops repeatedly in the console without finishing
});
});
PHP - get-details.php, reading the data from database after getting inserted with ajax
if (!isset($_SESSION)) {
sec_start();
}
global $db;
$domain = isset($_SESSION['domain']) ? $_SESSION['domain'] : '';
if ($domain == '') {
$domain = $db->query("SELECT * FROM seo_data");
} else {
$domain = $db->query("SELECT * FROM seo_data WHERE domain = '$domain'");
}
$domain_now = $domain->fetch_assoc();
$twitter_followers = (int) $domain_now['twitter_followers'];
echo json_encode(array('twitter_followers' => $twitter_followers));
I'm not sure but when the first AJAX request stops
$(document).ajaxStop(function (){....
starts a new one with
$.getJSON('lib/get-details.php', function(data) { ...
When this second one ends, maybe
$(document).ajaxStop(function (){....
is called again which starts again the 2nd request and so on

Categories