Ajax send javascript variable to php - php

I am trying to send a JS variable to a PHP file but it does not seem to be working. In the console its showing an error as an show.php file. I am not able to understand What I am doing wrong.
function details(id) {
var id = id;
// alert(id);
$.ajax({
type: 'POST',
url: 'show.php',
data: id,
success: function(data) {
alert("hi");
}
});
}
<button onclick="details(<?php echo $id ; ?>)" class="btn btn-rounded btn-primary">Details</button>
show.php:
<?php
if (isset($_POST['id']))
{
$uid = $_POST['id'];
echo json_encode($uid);
}
?>

Write data in json object
see code below
function details(id)
{
var id = id;
// alert(id);
$.ajax({
type: 'POST',
url: 'show.php',
data: {id:id},
success: function(data)
{
alert("hi");
}
});
}

Check your network tab and check the sending parameters list . You have to mention datatype json
Try this
function details(id)
{
var id = id;
// alert(id);
$.ajax({
type: 'POST',
url: 'show.php',
dataType: 'json',
data: {'id':id},
success: function(data)
{
alert("hi");
}
});
}
In your show.php
<?php
if (isset($_POST['id']))
{
$uid = $_POST['id'];
echo json_encode($uid);
}
?>

Related

Get the content of json file on page load

I am using ajax, php and json to store click counts in json file...Let's say the file is this:
count.json
{"countbtn1":28,"countbtn2":25,"countbtn3":39}
downloadsCount.php
<?php
$buttonName=$_POST["buttonName"];
$file = "count.json";
$json = json_decode(file_get_contents($file), true);
echo $json['count'.$buttonName] ;
?>
downloads.php
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'.$buttonName] = $json['count'.$buttonName] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
And I need to place each btn value inside these on page load:
<div class='smallbtn1'>0</div>
<div class='smallbtn2'>0</div>
<div class='smallbtn3'>0</div>
Counting and updating the json file with this:
$('.download').click(function() {
//get name of button
var name= $(this).prop('name');
$.ajax({
url: "downloads.php",
data:{buttonName:name},
method: "POST",
success: function(response) {
if (response = 'success') {
//get count download
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response);
}
});
}
}
});
return true;
});
..and I tried updating the count on page load with this:
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response); }
});
});
...but it doesn't update the values on load, just after the first click.
PS: The whole thing IS wrapped in $(document).ready(function(){..});
After seeing the code on your server, I'd say the issue is how you are calling the AJAX. You are doing this:
$(document).ready(function(){
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response); }
});
});
But you don't have defined what name is (it is defined on the click event, but not when the page is loaded for the first time). You should do something like this:
$(".download").each(function() {
var name = $(this).attr("name");
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name },
method: "POST",
success: function(response){
$('.small'+name).html(response);
}
});
});
So the AJAX is called for each one of the buttons, and you use the attribute name by doing $(this).attr("name").
Try sending the AJAX request after the page completely loads using $(document).ready():
$(document).ready(function() {
$.ajax({
url: "downloadsCount.php",
data: { buttonName:name },
async: false,
method: "POST",
success: function(response) {
$('.small' + name).html(response);
}
});
});

serializeArray not sending the data

This is a sample of the php and javascript.
<form id="image-comment" method="post" action="includes/insert_image_comment.php">
<textarea id="comment-area" name="comment-area"></textarea>
</form>
// javascript
$("#image-comment").submit(function(event) {
event.preventDefault();
var action_url = event.currentTarget.action;
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({imageid: id});
$.ajax({
url: action_url,
type: 'post',
data: params,
success: function(data) {
alert(data);
}
});
});
// insert_image_comment.php
echo $get_image = $_POST['imageid'];
$comment = $_POST['comment-area'];
When echoing $_POST['imageid'] i get an error 'Undefined index: imageid'.
When echoing $_POST['comment-area'] it's ok.
Why one works and the other not?
Thanks
Try to use the format that serializeArray uses: Example:
$("#image-comment").submit(function(event) {
event.preventDefault();
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({name: 'imageid', value: id}); // this one
$.ajax({
url: document.URL,
type: 'POST',
data: params,
success: function(data) {
alert(data);
}
});
});

Ajax PHP: Variable from page url

With the following AJAX call I set pagination for a webpage. It works.
In my PHP file already have:
$page= $_POST[page];
AJAX call:
function pg2(page) {
pag.ajax({
type: "POST",
url: "file.php",
data: { page: page },
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
}
I also need to pass id from the URL.
http://website.com/title/?id=2 **//I need to pass id in php file and echo it out.
How can I do that? many thanks.
var id=<?php echo $_GET['id'];?> // like this you can store php variable in javascript varibale
Now call function pg2(page,id) however you want...
function pg2(page, id) {
pag.ajax({
type: "POST",
url: "file.php",
data: { page: page, id: id },
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
}
hope it may help you
If your JS is embedded:
function pg2(page) {
var id = <?php echo intval($_GET['id']); ?>;
pag.ajax({
type: "POST",
url: "file.php",
data: { page: page, id: id },
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
}
If your JS is in an external file (best option):
var id = <?php echo intval($_GET['id']); ?>;
pg2(page, id);
Read id via GET and pass in the function
$id = $_GET['id'];
function pg2(page, id) {
pag.ajax({
type: "POST",
url: "file.php",
data: { page: page, id: id },
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
}

Access Data from Database with Ajax

I have tried just about every solution and I know my database returns values if i hard code in the php so the issues is returning the values or determining if it is actually sent as post. It gets to the success function and alerts Worked but I am getting undefined for Item ID.
$(document).ready(function() {
$('.check').click(function(){
alert("Step1");
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "GET",
url: "XXX.PHP",
data: { "ID": thisID},
cache: false,
async:true,
datatype: "json",
success: function(data)
{
alert("WORKED");
alert(data.ItemID);
}
});
});
});
Here is the PHP
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
function retrieve($ID)
{
$stmt = $mysqli->query("SELECT * FROM database1.menu WHERE ItemID = $ID");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
You could try something like this. Not sure if this is what you need.
$(".check").click(function(event){
event.preventDefault();
var $this = $(this);
var thisID = $this.attr('id');
$.ajax({
type: "POST",
url: base_url + "url.php",
data: {
id: thisID
},
dataType: "text",
cache:false,
success:
function(data){
alert(data);
}
});
return false;
});

Using AJAX form submit to submit and retrieve data from MySQL

Basically, I'm trying to make it so that when a post is submitted to my site, it sends the post using AJAX so that they don't change page, and then if the AJAX post is successful, retrieve all the posts for said user from MySQL and write them onto the page.
My problem is that the browsers (Chrome, IE) are completely ignoring the AJAX request.
My form:
<div id="updatestatus">
<form action="" method="post" id="ps">
<textarea name="status" id="status"></textarea>
<input type="hidden" name="uid" id="uid" value="<?php echo $uid; ?>" />
<input type="submit" id="poststatus" name="poststatus" value="Share" />
</form>
</div>
My AJAX request:
$(function() {
$("#poststatus").click(function() {
var status = $("textarea#status").val();
if (status == "") {
return false;
}
var uid = $("input#uid").val();
var dataString = 'status='+ status + '&uid=' + uid;
$.ajax({
type: "POST",
url: "updatestatus.php",
data: dataString,
success: function() {
$.ajax({
url: 'ajax/query.php',
data: "uid=<?php echo $uid; ?>",
dataType: 'json',
success: function(data) {
var status = data[0];
var sid = data[1];
$('#mainprofile').html("<div id='statuses'><p>"+status+"</p></div>);
return false;
}
});
return false;
});
});
});
});
My ajax/query.php request
<?php
//connect stuff
$uid = strip_tags(stripslashes(htmlspecialchars(htmlentities(mysql_real_escape_string($_GET['uid'])))));
$result = mysql_query("SELECT * FROM mingle_status WHERE uid = '$uid' ORDER BY timestamp DESC"); //query
$array = mysql_fetch_row($result); //fetch result
echo json_encode($array);
?>
Thanks in advance for any help - Joe
In this section of JS code
$.ajax({
type: "POST",
url: "updatestatus.php",
data: dataString,
success: function() {
$.ajax({
url: 'ajax/query.php',
data: "uid=<?php echo $uid; ?>",
dataType: 'json',
success: function(data) {
var status = data[0];
var sid = data[1];
$('#mainprofile').html("<div id='statuses'><p>"+status+"</p></div>);
return false;
}
});
return false;
});
});
You need to remove the ending bracket after the curly brace which follows the last return false, such as...
$.ajax({
type: "POST",
url: "updatestatus.php",
data: dataString,
success: function() {
$.ajax({
url: 'ajax/query.php',
data: "uid=<?php echo $uid; ?>",
dataType: 'json',
success: function(data) {
var status = data[0];
var sid = data[1];
$('#mainprofile').html("<div id='statuses'><p>"+status+"</p></div>");
return false;
}
});
return false;
};
});
Try this
$(function() {
$("#poststatus").click(function() {
var status = $.trim($("#status").val());
if (status == "") {
return false;
}
var uid = $("#uid").val();
var dataString = 'status='+ status + '&uid=' + uid;
$.ajax({
type: "POST",
url: "updatestatus.php",
data: dataString,
success: function() {
$.ajax({
url: 'ajax/query.php',
data: "uid="+<?php echo $uid; ?>,
dataType: 'json',
success: function(data) {
var status = data[0];
var sid = data[1];
$('#mainprofile').html("<div id='statuses'><p>"+status+"</p></div>);
return false;
}
});
return false;
}
});
});
});

Categories