php can't get data from #.ajax post in Jquery mobile - javascript

I am using jquery mobile to develop a small website. Now I want to pass variables from javascript to php. I am using #.ajax post
Here is my code in javascript:
var link_id = $(".templateLink").attr("id");
var link_name = $(".templateLink").attr("name");
$.ajax({
type:"POST",
url: "test.php",
data: {id:link_id, name:link_name},
success: function(){
//do sth.
}
});
Here is my php code:
<?php
$survey_link_id = $_POST["id"];
$survey_link_name = $_POST["name"];
?>
However, I keep getting this error:
Notice: Undefined index: id in /Applications/XAMPP/xamppfiles/htdocs/iQ_1/test.php on line 3
Notice: Undefined index: name in /Applications/XAMPP/xamppfiles/htdocs/iQ_1/test.php on line 4
It is really annoying. Is it because I'm using jquery mobile??
Can anyone help me? Or provide other ways to pass variable from javascript to php.
Thanks a lot!!!!

i think u can use set data like this
data: "id="+link_id+"&name="+link_name,
because i'm using this for post the variable with ajax jquery every time and running nice...

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);
}

Ajax doesn't get to success function. Always error function. It fails to post data to another file

Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.

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

How do i use a javascript variable in wordpress query string?

I need to find a way to use a js variable in wordpress query string. I know it involves ajax but i don't know how to go about it. Please help!
<script>
$(document).ready(function(e) {
var x=$(this).find('.resp-tabs-list li').attr('id');
//alert(x);
});
$('.resp-tabs-list').on('click',function(e){
var x = $(this).find('.resp-tab-active').attr('id');
//alert(x);
});
</script>
In the code above, i fetch 'x', which is the category id, based on which i want to fetch posts in a loop.
You are correct that it does involve ajax. You'll need to do something like the following (I haven't tested it, but it should put you on the right track):
Javascript (assuming you have jQuery loaded, and that you've used PHP to output the admin url as a javascript variable ajaxurl):
$(document).ready(function() {
bindCategoryFilter();
}
function bindCategoryFilter() {
$('.resp-tabs-list').on('click',function(e){
var x = $(this).find('.resp-tab-active').attr('id');
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
//this is the name of our Wordpress action we'll perform
'action' : 'get_ajax_posts',
//this is the important line--send 'x' to the server as category
'category' : x
},
success: function(data) {
//do whatever with the data you're getting back
//with the PHP below, it's an array of the post objects
}
});
});
This will POST data to our server, with the variable 'category' set to x in the $_POST variable. To access this, in your functions.php you would want to add something like the following:
//add our action hooks--wp_ajax_XXXXX is defined in the ajax query as 'action'
//the second argument is the name of the PHP function we're calling
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
function get_ajax_posts() {
if(isset($_POST['category'])) {
//get all the posts in the category, add more arguments as needed
$posts = get_posts(array('category' => $_POST['category']));
//data is returned to javascript by echoing it back out
//for example, to return all of the post objects (which you probably don't wnat to do)
echo json_encode($posts);
//we're done
die();
}
}
See the wordpress codex for more information about AJAX and Wordpress.

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!

Categories

Resources