Not clear on syntax of ajax post - javascript

I am new to php and javascript. I am trying to post some variables to another php file using ajax. From my main php file, I have a javascript setInterval calling a function to send data every 500ms. The function called is:
function UpdateDB(xval, yval) {
TimeCount++;
// console.log(xval, yval, TimeCount);
$.ajax({
type: "POST",
url: "ud.php",
data: { x: xval.toString(), y: yval.toString(), t: TimeCount.toString() }
});
return TimeCount;
}
This function runs fine as I get the console log data (if I uncomment). I can also see in developer tools (chrome) in the network, the file ud.php appears to be run, but I do not believe this is the case. ud.php is a simple file that updates data in a table:
//<script type="text/javascript">console.log("ud");</script>
<?php
if (!isset($_SESSION['id'])) {
exit();
}
//require "includes/dbh.inc.php";
$sql = "UPDATE units SET JoyX='$x', SET JoyY='$y', SET JoyTimeStamp='$t', WHERE SN='$serial'";
//$sql = "UPDATE units SET JoyTimeStamp='$t' WHERE SeralNumber='$serial'";
mysqli_query($conn, $sql);
mysqli_close($conn);
exit();
?>
I wrote the commented out line at the top to see if the file was run, but when uncommented it does not log to the console.
I suspect my ajax query is incorrectly formatted, but again I am new to this and have searched for the last few days to find an answer without success.
Thanks for any help.

The PHP file is successfully being invoked, you just have an invalid expectation of the result. Check the network tab in your browser's debugging tools. Are there any error codes in the request/response? Does the response contain the information you expect? If so then it's working.
The question is... What are you doing with that response?
The AJAX operation by itself doesn't do anything with the response. But it gives you an opportunity to do something with it. For example, in the jQuery .ajax() call you're using, there's a success callback which gets invoked on a successful result. So you can do something like this:
$.ajax({
type: "POST",
url: "ud.php",
data: { x: xval.toString(), y: yval.toString(), t: TimeCount.toString() },
success: function () {
console.log("ud");
}
});
So instead of trying to return new JavaScript from the server, you write the JavaScript here that you want to invoke when the operation successfully completes. (Alternatively you can use an error callback for a failed response.)
If you want to send data back from the server, anything you echo to the response would be available as the first argument to the success function. For example, if you do this on the server:
echo "ud";
Then in the success callback you can show that text:
success: function (result) {
console.log(result);
}

Related

Uncaught TypeError Message using Javascript variable as argument for PHP function that initiates mySQL query

I spent most of my day yesterday trying to solve this puzzle so today I've decided to reach out for some help. Before I begin, let me state that I am very aware that JavaScript is client-side and PHP is server-side and I use Ajax successfully for various other things. In this case, I can't find any S/O references that are similar to what I'm trying to accomplish. I would've thought this was very basic but I'm missing something here and could use some direction. Thank you.
In essence, I have a Javascript function that produces a JavaScript variable and then calls a PHP function that initiates a mySQL query (all on the same page). If I "hard-code" the argument in my PHP function call (e.g., sc_bdls = <?php echo Candidates::getBDLs(1000033); ?>;), the function runs perfectly and I receive the expected outcome (an array).
However, if I try and use a JavaScript variable in place of the argument, I receive a "Uncaught TypeError: Cannot read property 'id' of undefined" error. I have tried several iterations without success and I suspect I am missing something basic. Here is my code:
function tab_pos3(row){
var sc_id = row.toString();
var sc_bdls = [];
$.ajax({
type: "POST",
url: '/phpscripts/pass.php',
data: {row : row},
success:(function(data){
console.log("success");
alert(data);
})
});
sc_bdls = <?php echo Candidates::getBDLs($uid); ?>;
}
Here is the code from the pass.php file:
if(isset($_POST['row']))
{
$uid = $_POST['row'];
echo $uid;
}
Please notice that the console.log("success") and the alert(data) both show that the Ajax POST is working. Any thoughts on what might be going wrong? Thank you.
1st EDIT (comment from Swati)
I tried moving the PHP function call as suggested and then used $UID, $data, data, among others, and I still get the exact same error. Here is the edited code:
$.ajax({
type: "POST",
url: '/phpscripts/pass.php', //
data: {row : row},
success:(function(data){
console.log("success");
alert(data);
<?php $row = $_POST['row'];?>; // I tried this based on something I read.
sc_bdls = <?php echo Candidates::getBDLs(data); ?>;
})
The fact that the error doesn't change is gnawing at me. Could the argument be passed but in a format that is not being read right? Is the "TypeError" referring to data type?
Try moving the
sc_bdls = <?php echo Candidates::getBDLs($uid); ?>; to pass.php and read the returned data in ajax success function.
Please note php is executed before the browser sees it. And JS code is called client side.
This is how your function will look like
$.ajax({
type: "POST",
url: '/phpscripts/pass.php', //
data: {row : row},
success:(function(response){
console.log("success");
sc_bdls=response; // Just to show that response has the value you need.
alert(sc_bdls);
})
The pass.php will look like this
// I prefer using !empty here (unless you are expecting 0 as a valid input.
// This ensure $uid isset and is not empty.
// Also if $uid is supposed to be numeric you may want to add a validation here.
if(isset($_POST['row']))
{
$uid = $_POST['row'];
$response_array = Candidates::getBDLs($uid); //Your question says you are expecting an array
echo json_encode($response_array);
}

issue using $.ajax with php effectively

I'm having trouble understanding what I'm missing or not doing here (obviously something), and maybe someone can help.
I have a database site that displays a table generated from a SQL database on the client side. When the table is initialized, this code is executed and pulls the data needed for the dropdown in question (comments added by me for this post):
$selectOwner = "SELECT DISTINCT [Contacts].[Alias], [Contacts].[Last Name], [Contacts].[ID] FROM [TechInv].[dbo].[Contacts]";
//this is the file that contains the above query variable
require('custom/Connection.php');
$owner_arr = array();
//$conn is our connection string
$response = sqlsrv_query($conn, $selectOwner);
while ($row = sqlsrv_fetch_array($response)){
array_push($owner_arr, $row['Alias'] . " " . $row['Last Name']);
}
This generates a list of name records pulled from the database in a Alias(first name) Last Name format.
Here's where I'm having trouble
Another function of the site is a menu that allows users of a certain priveledge level to add additional contacts to the table. Everything works fine with that except nowhere in the code is the above array updated when a contact is added, which forces the user to reload the page, ew.
I know i need to use $.ajax for this, so I took a stab at it, and put the following code into the click handler for the 'add contact' submit button:
$.ajax({
type: 'POST',
data: 'listRefresh();',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function() {
alert("this succeeded?");
}
});
The data: 'listRefresh();' line refers to a function I created that is the same as the first block of code, in an attempt to just refresh the variables with new data. That's obviously where I've gone wrong, (try not to laugh) but I am out of ideas here. Can anyone shed some light?
Your ajax call is wrong. The 'data' value is what you send to the server.
Try this:
$.ajax({
type: 'POST',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function(data) {
listRefresh(data);
alert("this succeeded?");
}
});
The data variable is what the server gives you back, so you can pass that data to the listRefresh() function and re-render the upated list.
In alternative, you could just reload the page putting location.reload(); into success function

Use Javascript array in PHP

I know this question has been asked before several times on this forum, but I think I am missing something. Or maybe it is because I don't know JSON/AJAX that well.
Here is the thing.
I got some javascript/JQuery code on a page, say on index.php, (not yet in a seperate JS file) which let you put any number in an array from 1 to 10. If it's already in it, it will be removed if clicked again.
Now I want to pass that JS array to PHP, so I can create tables with it.
Here's what I have done.
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
elements: enc
},
success: function(data) {
console.log(enc);
}
});
});
And in my calc.php I got this to get the values to PHP.
<?php
$data = json_decode($_POST['elements'],true);
echo $data;
?>
Now here comes the noob question:
If I click my (.Go) button, what really happens?
Because the console.log let's me see the correct values, but how do I access it? The page (index.php) doesn't automatically go to the calc.php.
When I use a <form> tag it will take me there, but it shows this error:
Undefined index: elements
I am sure I am looking at this the wrong way, interpreting it wrong.
Can someone please help me understand what it is I should be doing to continue with the JS array in PHP.
With a XHR request you don't do a page reload. With your $.ajax method you post data to the server and receive information back. Since you can see information in your console, the success method is triggered.
You might want to take a look at your DevTools in for example Chrome. When you open your Network tab and filter on XHR you see what happens. You can inspect your XHR further by looking into the data you've send and received.
So my question to you is: what do you want to happen onSuccess()? What should happen with the data you receive from your backend?
In JavaScript:
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
"elements="+enc;
},
success: function(data) {
console.log(data);// You can use the value of data to anywhere.
}
});
});
In PHP:
<?php
if(isSet($_POST[elements]))
{
$data = json_decode($_POST['elements'],true);
echo $data;
}
else
{
echo "Elements not set";
}
?>

Jquery Ajax success function never called

I have the following Ajax call:
$.ajax({
type: 'POST',
url: myBaseUrl + 'Products/addItemToBasket',
dataType: 'json',
data: {
id: window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1),
amount: amount
},
success: function (data) {
alert(data);
var dat = JSON.parse(data);
}
}
});
Now this calls the following method in php:
public function addItemToBasket()
{
if ($this->request->is('post')) {
//todo delete efter at have insat fancybox med valg af antal styk. (sendes via ajax).
$shopping = null;
$item = $this->Product->find('first',array('conditions' => array('Product.id' =>$this->request->data['id'])));
if(isset($_SESSION['basket'])){
$shopping = $_SESSION['basket'];
}else{
$shopping = array();
}
array_push($shopping,$item);
$_SESSION['basket'] = $shopping;
echo json_encode($_SESSION['basket']);
}
}
When i try to debug it everything is working (it gets into the php function) and updates my $_SESSION variable.
BUT it never runs the success function and it never alerts the data.
What am i doing wrong?
NOTE: I know this question is from a couple of months ago, but any help will be useful for people looking for answers to this kind of problems.
As far as I know, because I'm running with a similar problem, it all depends on the response you get from the webservice (you can check it out with Chrome debugging console). For instance, I'm getting this now:
readyState: 4
statusText: "OK"
responseText: (The result I am looking for)
The problem is, as you say, I always get to run the Error part of the callback, never the Success, even if I'm getting the right responseText. As I've read, that's because the call to the WS was OK, but the parsing from JSON wasn't, so it calls "error".
So far I don't know how to fix it, but maybe this will give a clue.

Return info from jQuery AJAX call and execute additional jQuery on success

I have the following jQuery AJAX to duplicate a background image. I am stumped as to how to effectively return information back to the original page. Here is the AJAX I send on click of "'#dupBtn"...
//DUPLICATE BACKGROUND
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
"user":<?= $_POST['user'] ?>,
"bgID":bgID,
"refID2":<?= $_POST['refID2'] ?>,
"refTable":"<?= $_POST['refTable'] ?>",
"bgTitle":($('#bgTitle').val()),
"path":path,
"bgColor":bgColor,
"bgPoz":bgPoz,
"bgRepeat":bgRepeat,
"attach":attach
}
});
});
Here is the basic MySQL query on the PHP page bgUpdate.php.
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
What I want to do is have the following code fired on the original page upon successful execution of the MySQL entry, dynamically catching the '$bgIDnew' from the MySQL PHP page.
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
You can accomplish this with the success attribute of the .ajax() function:
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
...
},
success:
function(response)
{
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
});
});
That's only part of it though... The other half is that your PHP needs to return something that jQuery can understand as a "successful" call. My preference is to use HTTP status codes. In your case, your PHP script should return a 200 code if it was successful; otherwise, it should return something in the 400 range. (By the way, if you want jQuery to do something separate with errors, you can use the error property of .ajax().)
However, if you need to return data from the server to the client-side script, then your PHP can print out that information like this:
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
// Best practice to keep it in some sort of understandable format
// Here, we'll put it in an associative array:
$response = array('id' => $bgIDnew);
print_r(json_encode($response));
This PHP script sends back to the ajax() method a JSON representation of the $response variable. You've already configured that ajax() method to read the response dataType as JSON, so it already knows how to read the response parameter... Which means your success function can look something like this:
success:
function(response)
{
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=' + response.id);
}
jQuery.ajax() has a success property that acts as a callback that you can use. Another is complete which is fired if the request is successful or not.
jQuery.ajax({
/* your stuff here */
success: function(response) {
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
});
You can write up the logic in the success callback function of your ajax Request..
This is fired when an ajax request is successfully returned..
success: function(response) {
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
Add this to your ajax Request...

Categories

Resources