Use Javascript array in PHP - javascript

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";
}
?>

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

Ajax Call, how to access $_POST var

Sorry if this is a silly question but I'm completely new to AJAX and I'm wondering why my code is not working like I want..
I have the following:
an Ajax Call looking like that:
$.ajax({
type: "POST",
url: "/newnote.php",
data: {
content: content
},
success: function() {
}
});
and on the beginning of the page newnote.php (which is exactly the one, where the ajax-call is on, I have the following PHP:
if(!empty($_POST)){
header("Location:index.php");
}
But the php on the beginning of the page is not executed, of course, because the site seems not to be reloaded, but, when looking in developer tools under "network", i see that there is a post request on newnote.php with the values I want. But the question is: How can I access them? So for example, if I post the following data: content: "test", that I can write in PHP sth. like <?=$_POST['content'];?>... So how can I access the $_POST-Data from AJAX? Do I need to refresh the page or how does this work?
Thanks for your help
after exchanging I now got the question:
to access to your code you must use the callback of your ajax call
success: function(result){
$("#div1").html(result); // here you put the content that echoes your php inside your div1 on the actual page without reload
}
On the php side where the content is posted you must echo something that will be caught by this ajax call

Sending data from javascript to php using via Ajax using jQuery. How to view the data back?

I know this question has been asked a lot as I have been googling since morning but I just can't think what's going on in my code.
I have a index.php (which is my website) that uses forms to receive information from user, then invokes a javascript file separately which in turn invokes another backend php file (this backend php file queries a database using mysql and does some stuff).
The problem is I am not sure what information is getting passed to the backend php from my js. I have just learnt jQuery and Ajax so I really don't know what is that small mistake I am making.
From my understanding, the backend php does its stuff and passes the value to javascript to be displayed on the web page. But my data is not getting sent / displayed. I am getting a error 500 internal server error.
Here are the pieces of code that are currently is question:
Javascript:
var data1 = {week:week, group:grp_name};
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
success : function(response){
alert ("success !");
},
error : function(response){
console.log(response);
alert("fail!");
}
})
});
PHP backend (remindUsers.php):
<?php
if (isset($_POST['week'])) {
$week = $_POST['week'];
}
if (isset($_POST['group'])) {
$group_name = $_POST['group'];
}
echo $week;
?>
I am ommiting out the sql code pieces because they work fine.
Edit: Now my status code is 200, response text is also ok . My response text shows a weird "enter' sign next to the actual response text expected. Is this normal ? And it is still going into the error block , not the success block of code.
I can not fully answer your question because I need more debug information about whats going on but theres 2-3 things about your code bugging me a little that might fix your bug.
First, use isset in your backend like this:
if (isset($_GET['your_input_name'])) {
$someData = $_GET['your_input_name'];
}
The isset part is very important here. Set it up and try it again. If you stop having a 500 error. Its probably because your data was never send to your backend or because your not checking the good input name.
Second, About input name. I can see in your code that you send:
var data1 = {week:week, group:grp_name};
So in your backend you should use the name of the value like this to retrieve your data:
$week = $_POST("week");
Third, I am not a json pro but maybe your json is not valid. Even if he is ok I suggest you build a "cleaner" one like this:
var data = [
{ 'name' : 'week', 'value' : week}
];
And finally, if you are using forms to send data to php then you can use something like that :
var myForm = $("#myForm").serializeArray();
$.ajax({
url: 'yourUrl',
type: "GET",
data: myForm,
dataType: 'json',
success: function(res){
//your success code
},
error: function(){
//your error code
}
});
I hope this helps.
You can't have these tags <body>,... in your PHP response over json.
It must be only:
<?php
$week = $_POST("data");
$json = json_decode($week);
echo json_encode($json);
?>
Remove the comment on
//data : {week :week}
And set a variable week with a valid value:
data : {week :week}
and so:
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
data : {week :week} ,
success : function(response){
console.log(response);
},
In order to see what is the shape of response.
You are doing a couple things wrong. First, you don't want to stringify your data before sending it to the server. You want to send JSON, so your commented line is the correct one. There is also a problem with the PHP. The data going to the server will look like:
{week: "Something"}
So in your PHP, you want to access the data like:
$_POST["week"];
USE THIS
PHP
$week = $_POST['data'];
$json = json_encode($week);
echo $json;
JS
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php"
//data : {week :week} ,
data: {data:{week:'week', group:'grp_name'}} ,
success : function(response){
alert ("success !");
},
error : function(response){
alert("fail!");
}
})
I would say wrap the php in a function and echo the json. Also its good to check if there was POSTed data, and if not return an error message. This is not tested, but will hopefully point you in the right direction.
<?php
function getJSON() {
if (isset($_POST["data"] && !empty($_POST['data']) ) {
$week = $_POST["data"];
$json = json_decode($week);
echo $json;
} else {
echo "There was a problem returning your data";
}
}
getJSON();
?>
Actually as I write this, I realized you could try these headers in your AJAX POST:
accepts: 'application/json',
contentType: 'application/json',
dataType: 'json'
Hope that helps.
It worked. I figured out the answer thanks to another SO post.
TIL : Even if server response is ok, the error condition will be triggered because the data returned to javascript from php is not json,since i had explicitly mentioned dataType: "json" in the ajax request.
Link here:
Ajax request returns 200 OK, but an error event is fired instead of success
Thanks folks for helping me and steering me in the right direction. Cheers!

JQuery Form No reload : how to pass the $_POST info after success?

First the code below works, but truth be told i don't know why :) it just worked after many trial and errors
I need the $_POST data submitted through the #filter-form, for loading the page as action1 function will require $_POST data.
If i remove +data or .html(data) it doesn't work anymore.
Also if i change url:"..." it does not work anymore either and i don't understand why as i don't need to to anything here, all i need is to load this page.php page and pass the $_POST so that it can output properly.
My QUESTION is, WHY does it work ? (i want to understand why putting +data or html(data) is so important to make sure $_POST is passed) and how can i make it more proper ?
Thanks for your help
<script type="text/javascript">
$("#filter-form").submit(function(event) {
$.ajax({
type: "POST",
url: "includes/page.php?action=action1",
//Specify the datatype of response if necessary
data: $("#filter-form").serialize(),
success: function(data){
alert("succeess");
$("#tableresult").load("includes/page.php?action=action1"+data).html(data);
}
});
event.preventDefault();
return false;
});
</script>';
You don't need to use .load() at all. It should be:
success: function(data) {
alert("success");
$("#tableresult").html(data);
}
This takes the response that the AJAX server returned, which should be HTML code, and puts it into the tableresult element.
The way you had it written, you're calling the server twice, which doesn't seem right.

Categories

Resources