Passing multiple parameters via json.stringify/ajax not working - php

I have tried searching through SO for an answer to my issue, but all the posts I find still aren't helping me resolve my issue. I don't know if I am overlooking something or if it's just my lack of knowledge that is preventing my code from working.
I have two JS prompts that ask for an ID and then an amount to adjust my stock level. I want it to pass that along to my php file to run a mysql update query.
My script:
<script type="text/javascript">
function sendArray()
{
var ourObj = {};
ourObj.itemId = prompt("Scan ID:");
ourObj.adjAmt = prompt("Enter amount:");
alert(ourObj.itemId);
alert(ourObj.adjAmt);
$.ajax({
url: "save.php",
type: "POST",
data: { invAdj : JSON.stringify(ourObj)},
success: function(response)
{
alert("data sent response is "+response);
},
error: function(e)
{
alert("data not sent"+e);
}
});
}
</script>
<button onclick="sendArray();">Send Array</button>
My php:
if(isset($_POST['invAdj'])) {
$invAdj = json_decode($_POST['invAdj']);
$itemId = $invAdj->itemId;
$amtAdj = $invAdj->amtAdj;
}
mysqli_query($link, "UPDATE stock_levels SET stocklevel = stocklevel + " . $amtAdj . " WHERE id = " . $itemId);
?>
Presently, I get a successful alert, but the level does not change in the db. I know that the db info works and the sql query works because if comment out the post block an add solid variables, it runs perfectly. I have something screwed up in the POST block.
Any help would be greatly appreciated! Again, sorry if this has been answered, but I couldn't find a post that worked...
Also, I know that I shouldn't put the SQL directly into my query. I am just trying to get this working first.
Thanks

Related

tooltipster dynamic content does not work

i'm very frustrated, because i can't find the answer how can i show tooltip with ajax dinamic content. If i use static contet it works, but it doesn7t work with dinamic contect. Can you please help me?
Here is my tooltipster script:
<script type="text/javascript">
$(document).ready(function () {
$('.pomoctools').tooltipster({
multiple: true,
content: 'Loading...',
functionBefore: function (origin, continueTooltip) {
continueTooltip();
// next, we want to check if our data has already been cached
//if (origin.data('ajax') !== 'cached') {
$.ajax({
type: 'POST',
url: 'person/index_person_test.php',
success: function (data) {
// update our tooltip content with our returned data and cache it
origin.tooltipster('content', $(data)).data('ajax', 'cached');
}
});
}
});
});
Then I have this php page (here is just the code for displaying the data of person: person/index_person_test.php) :
$person_id = $_GET['person_id'];//person id
//find person's data
$sql = mysql_query("SELECT * FROM person WHERE person_id='$person_id'");
$row = mysql_fetch_array($sql);
$titleText = stripslashes($row[person_name]);
$sql = mysql_query("SELECT user FROM `users` WHERE id='$row[user_id_updt]'");
$user_name_updt = mysql_fetch_array($sql);
echo $person_id;
I want to show the tooltipster on my other php page, let's call it cast.php, here is just the part for tooltipster:
echo '</td>
<td width="100%" valign="top">'.$row[person_name].'</div>';
So my problem is that the toltipster does not show data when hovering on the link in cast.php.
If i change in person_index_test.php to:
$person_id = $_POST['person_id']; //person id
it does not help.
If i go to "person/index_person_test&person_id=56774"
the data is displayed correctly and if i echo the person id, i get the correct value:
echo $person_id;
I know i need to change things in javacript to fetch my mysql data correctly, but i can't find the answer. I have tried also adding to my jaascript after
url: 'person/index_person_test.php',
data: person_id,
or
data: 'person_id'
or
data: { 'person_id': person_id},
I have tried everything but it doesn't work.
If i cange in my javascript to static person_id then the tooltipster shows the content, but of course on hover the data is always the same. So for static i have changed this:
$.ajax({
type: 'POST',
url: '**?main=person/index_person_test&person_id=56774**',
success: function(data) {
would you please help me? I have read all the tooltipster questions here on ostackoverflow, but i can't find the answer...
Thanks! Misko

send value to php file using ajax to update database

I am new at this, and am not quite sure what I'm doing, I'm learning as I go ahead.
I have assigned a variable to store the value of rowID. Now I want to send that rowID value to a php file so I can use it in a where clause.
This is my ajax part.
$.ajax(
{
type: "POST",
url: "completed.php",
data: { complete: "$rowID" }
})
.done(function( msg )
{
alert( "Data Saved" + msg );
});
I am unsure of what the next step it. Could anyone help me out please? What do I need to do in order to use that value in a query.
This is part of the query in the completed.php file. (I have the connection and all before it)
$query = "UPDATE tbl_todo SET completed=1 WHERE id= $rowID ";
You can't use PHP variables in your script like that.
You will have to use PHP to echo it.
<script type="text/javascript">
var rowId = "<?php echo $rowID; ?>";
</script>
And in your PHP (completed.php) you will have to refer to it as 'complete', that is the name you are using when sending it.

jQuery $.ajax post to PHP file not working

So this stems from a problem yesterday that quickly spiraled out of control as the errors were unusual. This problem still exists but the question was put on hold, here, and I was asked to reform a new question that now relates to the current problem. So here we go.
The problem is basic in nature. If you were helping yesterday I have switched from a $.post to an $.ajax post to deliver a variable to my PHP file. However my PHP file seems to never receive this variable stating that the index is 'undefined'.
Now this would normally mean that the variable holds no value, is named incorrectly, or was sent incorrectly. Well after a full day of messing with this (kill me) I still see no reason my PHP file should not be receiving this data. As I'm fairly new to this I'm really hoping someone can spot an obvious error or reccommend another possible solution.
Here's the code
jQuery
$('#projects').click(function (e) {
alert(aid);
$.ajax({
url:'core/functions/projects.php',
type: 'post',
data: {'aid' : aid},
done: function(data) {
// this is for testing
}
}).fail (function() {
alert('error');
}).always(function(data) {
alert(data);
$('#home_div').hide();
$('#pcd').fadeIn(1000);
$('#project_table').html(data);
});
});
PHP
<?php
include "$_SERVER[DOCUMENT_ROOT]/TrakFlex/core/init.php";
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
try {
$query_projectInfo = $db->prepare("
SELECT projects.account_id,
projects.project_name,
projects.pm,
//..irrelevant code
FROM projects
WHERE account_id = ?
");
$query_projectInfo->bindValue(1, $aid, PDO::PARAM_STR);
$query_projectInfo->execute();
$count = $query_projectInfo->rowCount();
if ($count > 0) {
echo "<table class='contentTable'>";
echo "<th class='content_th'>" . "Job #" . "</th>";
echo "<th class='content_th'>" . "Project Name" . "</th>";
//..irrelevant code
while ($row = $query_projectInfo->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td class='content_td'>" . "<a href='#'>" . $row['account_id'] . "</a>" . "</td>";
echo "<td class='content_td'>" . $row['project_name'] . "</td>";
//..irrelevant code
echo "</tr>";
}
echo "</table>";
}
} catch(PDOException $e) {
die($e->getMessage());
}
} else {
echo 'could not load projects table';
}
?>
When I run this code by pressing '#projects' I get 2 alerts. This first alert says '6', which is the value of the variable 'aid' and is expected. The second alert is blank.
Now here is where I get confused. If the post is being sent with a value of 6. Isn't the $_POST['aid'] set? Also if that's true shouldn't my code execute the if portion of my conditional statement rather than my else?. Either way this strikes me as odd. Shouldn't I receive something back from my PHP file?
So in Firebug we trust, right? If I open up Firebug and go through like this
Firebug -> POST projects.php -> XHR -> POST(tab) ->
I see 6 in the 'Parameter' window and '6' in the 'Source' window. Then if I click the 'Response' and 'HTML' tabs they both hold no value.
So anyways, that wall of text is my problem. Again, I'm really hoping someone can help me out here. I would hate to waste anymore time on what should be a simple solution.
EDIT
If I change my php file to look like this
<?php
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
echo $aid;
} else {
echo 'fail';
}
The response is now '6'! Hooray! We made a breakthrough! Now why won't it load my table that results from my query?
side note
This should of been noted originally if I take away the
if(isset($_POST['aid'])){
//all my code
} else {
//response
}
and just hard code the variable $aid like this
$aid = '6';
Then run the PHP file directly the query is successful and the page loads the table its dynamically creating.
Also in response to one of the answers asking me to use
$('#projects').click(function (e) {
alert(aid);
$.ajax({
url:'core/functions/projects.php',
type: 'post',
data: aid,
success: function(data) {
// this is for testing
}
}).error (function() {
alert('error');
}).complete (function(data) {
alert(data);
$('#home_div').hide();
$('#pcd').fadeIn(1000);
$('#project_table').html(data);
});
});
I was using that, but I'm using jQuery v1.10.2 and according to this those methods are or will be deprecated. Either way it made 0 difference in the outcome.
Anyways the question is now. Why is it if I used the simple version I get echo'd back my $aid variable of '6'. However when I try and run my query with it I get nothing. Also please try to remember if I hard code the 6, the table creates.
I think this may be the error:
data: aid,
it should be
data: {'aid':aid},
That will provide the $_POST['aid'] label and value you're looking for in your php page.
EDIT:
If you're having trouble with this, I'd simplify it for testing, the main reasons for things like this not working in my experience are:
it's not reaching the file
it's reaching the file but the file's expecting something different than it's receiving and due to control structures it's not returning anything
it's reaching the file with the correct data, but there are other errors in the php file that are preventing it from ever returning it.
You can easily rule out each of these in your case.
The jQuery data parameter to the ajax method should be an object, such as {'aid': aid}. I think that's your problem. I also noticed your always method is missing a parameter for data.
If you're now posting the data correctly could the problem be in your PHP page?
The init.php include couldn't be changing the value of $_POST['aid'] could it?
I'm not sure done is suppose to behave like that, normally you use done like this:
$.ajax({
//...
})
.done(function(data){
//...
});
Just do it like this:
var fetch = true;
var url = 'someurl.php';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'aid' : aid
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
}
},
complete : function(data)
{
// do something, not critical.
}
});
You can add the failure part in if you want. This is, anyway, guaranteed to work. I'm just not familiar enough with done to make more comments about it.
Try
include "{$_SERVER['DOCUMENT_ROOT']}/TrakFlex/core/init.php";
instead cause $_SERVER[DOCUMENT_ROOT] witout bracket won't work. When you are using an array in a string, you need those brackets.
Since some browsers caches the ajax requests, it doesn't responds as expected. So explicitly disabling the cache for the particular ajax request helped to make it work. Refer below:
$.ajax({
type: 'POST',
data: {'data': postValue},
cache: false,
url: 'postAjaxHandling.php'
}).done(function(response){
});

Changing url from JavaScript code and adding another value

I have following mysql query:
$colname_profile = "-1";
if (isset($_GET['user'])) {
$colname_profile = $_GET['user'];
}
mysql_select_db($database_conn, $conn);
$query_profile = sprintf("SELECT * FROM users WHERE user_id = %s", GetSQLValueString($colname_profile, "int"));
$profile = mysql_query($query_profile, $conn) or die(mysql_error());
$row_profile = mysql_fetch_assoc($profile);
$totalRows_profile = mysql_num_rows($profile);
and following JS part of code I need to change:
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id"),
now, how do I add another value inside JS code from above query which should be in format of
user='.$row_profile['user_id'].'
so I need to keep whats already inside that JS url and at the end add that user ID. In case you need complete JS here it is
<script type="text/javascript">
$(document).ready(function(){
$("#loadmorebutton").click(function (){
$('#loadmorebutton').html('<img src="../images/body/icons/ajax-loader.gif" />');
$.ajax({
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id"),
success: function(html){
if(html){
$("#historywrapper").append(html);
$('#loadmorebutton').html('Load More');
}else{
$('#loadmorebutton').replaceWith('<center>No more posts to show.</center>');
}
}
});
});
});
</script>
Thanks for help.
maybe change url line to something like this:
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id") + "&user=<?php echo urlencode($row_profile['user_id']); ?>",
Given the way the question is asked, this will work:
url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id") + "user=<?php echo $row_profile['user_id']; ?>",
However I don't know if that is what you are looking for. Is $row_profile['user_id'] only a single value on a page or is this like a list of users and for each row in the table is there a different $row_profile['user_id'] that might exist? If this is a single value, for example the user_id of the user visiting the page and you want to pass that along with every ajax request, you might be better off storing that value is sessions elsewhere as it is unlikely to change unless the user logs out and back in under another account.

ajax POST not working, can't figure why

I have a simple AJAX function to send an id of an object to a php page
My function looks like this:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
My vote.php looks like this:
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
When I execute my AJAX function, it appears that the vote.php is never run
I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.
I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.
Can anyone see what's wrong?
Thank you
You're trying to send your variables in the URL, not as POST variables. Should be something like:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!
The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:
data: {
id: the_id
}
This lets jQuery do the URL-encoding for you.
As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.
Your data value shouldn't need a question mark at the beginning.

Categories