My ajax call not pulling in dynamic data from PHP/Mysql - javascript

Hello: I am working on a project where I am going to have divisions from a league listed as buttons on a page. And when you click on a button a different team list shows for each division. All divisions and teams are stored in a mysql database and are linked together by the "div_id". The plan was have the buttons use javascript or Jquery to send the 'div_id" to a function; which would then use ajax to access an external php file and then look up all the teams for that division using the div_id and print them on the page. I have been piecing this all together and getting the various pieces to work. But when I put it all together; it seems like the ajax part - does not pull in fresh data from the database if the data is changed. In fact, if I change the PHP file to echo some more data or something, it keeps using the original unaltered file. So, if the data is changed that is not updated, and if the file is changed that is not updated. I did find if I actually copied the file with a new name and then had my ajax call use that file instead; it would run it with new code and the new data at that time. But then everything is now locked in at that point and cannot get any changes.
So - I do not know much about ajax and trying to do this. I am not sure if this is totally normal for what I am using and for a dynamic changing team list, it cannot be done this way with ajax calling a PHP file.
OR - maybe there is something wrong with the ajax code and file I have which is making it behave this way? I will paste in the code of my ajax code and also the php file…
here is the ajax call:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
}
});
and here is the script.php file that it calls (removed db credentials):
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
$div_id=$answer;
echo "div id is: " . $div_id . "<br/>";
mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$result_g1 = mysql_query("SELECT * FROM teams WHERE div_id=$div_id");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$team_id=$row[team_id];
$team_name=$row[team_name];
echo $team_id . " " . $team_name . "<br/>";
}
}
?>
So - to sum up - is there something wrong with this making it do this? Or is what it is doing totally normal and I have to find a different way?
Thanks so much...

Most likely your browser is caching.
Try adding cache: false as such:
$.ajax({
cache: false,
type: 'GET',
...
The jQuery documentation explains that by doing so, it simply adds a GET parameter to make every request unique in URL.
It works by appending "_={timestamp}" to the GET parameters.

I believe this is caused by your browser's cache mechanism.
Try adding a random number to the request so the browser won't cache the results:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php?r=' + Math.random(),
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
}
});
Or turning jQuery's caching option off by:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
},
cache: false
});
Or (globally):
$.ajaxSetup({ cache: false });

Related

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.

jQuery.ajax() just receives an error, however jQuery.post() works

Debated whether to put this on WordPress.SE or here; decided that since it's primarily a jQuery question I'd post it here with the note that it occurred during WordPress development for context.
Long story short, following a guide on how to use AJAX in WordPress to the letter—including pasting in the same code excerpts to see if they run—doesn't work on my dev server. The designated PHP function is never executed, and the call just returns a 0 when I dump the response to a an output div.
I added an error: field to the AJAX call and that triggered, but other than revealing that there was an error, I couldn't figure out what was actually at issue.
Here's a look at the AJAX call, as shown in the guide.
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
jQuery("#vote_counter").html(response.vote_count)
}
else {
alert("Your vote could not be added")
}
}
})
Remembering having had this problem before, I decided to review an old project from a year ago, and found the following workaround, which seems to do the same thing, but actually returns the proper response from the script.
Functional workaround, does what is expected
var ajaxurl = '<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php';
var data = {action: "my_user_vote", post_id : post_id, nonce: nonce};
// Handle any returned values
jQuery.post(ajaxurl, data, function(response) {
if(response.type == "success") {
jQuery("#vote_counter").html(response.vote_count)
}
else {
alert("Your vote could not be added")
}
});
Ostensibly, it seems that the latter is just a longwinded way of executing the former, but for some reason only the latter works. What could be causing the error on the first block?
EDIT: It seems this may be a WordPress problem after all. I've already sent the code I was working on the other night to production, so to reproduce it I put it into a plugin and tried to run it on the default theme. It's working on the front end, but it's not working when I take it to a back-end page (which is what I was working on at the time). According to the console, it appears to be an issue with enqueueing the scripts on the back end.
To mitigate that issue, I dumped the following on an otherwise blank back-end page:
This post has <div id='vote_counter'>0</div> votes<br>
<div id="output">Test</div>
<script>
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php",
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
jQuery("#output").html(response)
jQuery("#vote_counter").html(5)
},
error: function(response) {
jQuery("#output").html(response)
jQuery("#vote_counter").html(10)}
})
})
})
</script>
<?php
$link = admin_url('admin-ajax.php?action=my_user_vote');
echo '<a class="user_vote" href="' . $link . '">vote for this article</a>';
Long story short: There is no longer any external script to enqueue, the link is coded directly into it, and the count should update to 5 on success or 10 on failure (since this is a back-end page and therefore there's no page_id to check for). All extraneous data fields have been dropped, since they won't be used in this form.
To simplify generating the response, I trimmed the code back to just the following:
function my_user_vote() {
$result = array(
'status' => 'success',
'count' => 5
);
$result = json_encode($result);
echo $result;
die();
}
What now happens is we get redirected to a blank page with the JSON response dumped on it. Tried dropping in the .post() method from above and that's doing the same thing for some reason.
TL;DR: This probably needs a move to wp.se.

AJAX post variable to PHP not working

I am trying to get a jQuery variable to a PHP variable. I have looked it up but can't find a solution. I have the following jQuery:
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success');
}
});
When I console.log te "eventID" it correctly displays the number.
My PHP code is in the index.php. This is also where the .eventRow class is.
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
However nothing happens. The console.log just displays: "Number: " Is there something wrong with the code? Thanks for your help!
EDIT: Could it be the problem that the index.php is already loaded before I click on the button? Because this php code is in the index.php and thus the $phpEventId is not yet set.
In your Ajax, the type: "POST" is for jQuery prior to 1.9.0. If you're using the latest jQuery, then use method: "POST".
If you're using the latest jQuery and you don't specify method: "POST", then it defaults to method: "GET" and your PHP needs to capture it with $_GET['phpEventId'];.
After reading your update, let's try one thing. Change your PHP to return something meaningful to Ajax:
<?php
$phpEventId = $_POST['phpEventId'];
echo $phpEventId;
?>
Then try to capture the PHP response in your Ajax:
$.ajax({
url: "index.php",
method: "POST",
data: {'phpEventId': eventID },
success: function (result) {
alert("result: " + result);
}
});
This is just a part of your code, and the problem is somewhere else. In this context your code works just fine:
<div class="eventrow" id="1">This</div>
<div class="eventrow" id="2">That</div>
<script>
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index-1.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success: '+eventID);
}
});
});
</script>
With the matching index-1.php:
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
Not sure though why do you print javascript code (console.log) into an ajax response here...
Error Is Visible Even Here
According to WebZed round statistic report, this error was visible over 84% of web-developers.
Failed to post data to PHP via JQuery while both frameworks and codes were updated.
Possible Solutions Available Today
Try using other methods for posting because JQUERY and AJAX libraries are not as efficient as shown in the surveys.
New frameworks are available which can do better with PHP.
Alternative method is to create a post request via $_GET method.
Regular HTML5 supports <form></form> try method="post". For security reasons try using enctype="" command.
Try using React Native https://nativebase.io/

PHP, Javascript, Ajax and the aspect of getting a result

I have a php file with a lot of checkboxes on the left hand side. I extract the values via javscript and pass them into an array. Which works just fine. I would like to pass then this array via Ajax to PHP in order to mess around with the values and create SQL-statements out of them.
$(document).ready(function(e) {
$('#getSelectedValues').click(function() {
var chkBoxArray = [];
$('.graphselectors:checked').each(function() {
chkBoxArray.push($(this).val());
});
for (var i = 0; i < chkBoxArray.length; i++) {
console.log(i + " = " + chkBoxArray[i]);
}
$.ajax({
url: 'index.php', // (1)
type: 'POST',
dataType:'json',
data: chkBoxArray, //(2)
success: function(data){
console.log(data.length);
console.log(data);
}
});
});
});
Several questions:
(1) what file name do I need to add here? The origion or the target?
(2) I have numerous ways of this: serialization, with these brackets {}, and so on. How to get it done right?
An error that I get is the following:
Notice: Undefined index: data in graph.php
That makes me wondering a bit, because it clearly shows no data is being send.
var_dumps on $_POST and $_SERVER offer these results:
array(0) { }
array(0) { }
which is somewhat unsatisfying.
Where am I doing things wrong? The only puzzling aspect is the ajax, all other stuff is not much of an issue.
The site is supposed to work in the following way:
Page -> Checkbox(clicked) -> Button -> result (ajax) -> PHP fetches result -> SQL DB -> PHP gets DB result -> fetch result (ajax) -> jslibrary uses result for something.
1- You need to point your ajax to the script that will use the data you are sending. I would not recommend to point to index.php, since you'll need to add a if statement checking if there is data on $_POST that is exactly what your're expecting, otherwise it will return the same page that you're in (considering that you are in index.php and is making a request to index.php). A point to consider. Since it is a whole request and it's not a method call to actually return something to your page you need to echo things. That said, consider also to set header('Content-Type: application/json') then, since you're expecting dataType: 'json', echo json_encode($objectorarray);
2- Since you're sending a Javascript array to PHP, it can't interpret correctly the structure, that is why you should use JSON.stringify(chkBoxArray) before sending it. But just setting it on data attribute would send the number of checkboxes you selected as values to POST, so consider to data: {myCheckboxValues: JSON.stringify(chkBoxArray)}
In your PHP script, considering all the security measures to take, you can $foo = json_decode($_POST['myCheckboxValues']);
Well, of course you need to pass the target page as url in your ajax call. It can't guess which file should process the data.
As for the data property. You need to give your data a name.
data: {
something: "something"
}
Becomes: $_POST['something']. (value: something)
$.ajax({
url: 'target.php', // (1)
type: 'POST',
dataType:'json',
data: { data: chkBoxArray }, //(2) Now $_POST['data'] will work
success: function(data){
console.log(data.length);
console.log(data);
}
});

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