There seems to be a problem with the code I have for calling php from javascript with jquery ajax. The ajax call seems to be successful but I don't get the correct information returned from the php function.
In the php function I create a SQL query. I send back the query as a reponse to debug it before performing a delete query. Here is the HTML for the div to show the query.
<div id="thenode" style="position: absolute; top: 30px; left: 0px; width: 150px; background-color: white; z-index: 9999;"> </div>
Here is the jquery ajax call. There are two variables being sent to the PHP function: nodeid for node to be delete, and option delete for the function.
function deleteitem()
{
//get selected node
var selectnod = getCookie('pnodid');
//define php info and make ajax call
$.ajax({
url: "uptree.php",
type: "POST",
data: { node: selectnod, option: "delete" },
cache: false,
success: function (response) {
$('#thenode').html(response);
}
});
}
Here is the PHP function.
<?php
function uptree() {
$node = $_POST['node'];
$option = $_POST['option'];
if($node == '' || $option == '') {
return '';
}
$dbco = mysql_connect('localhost', 'root', 'mmowebdb');
if (!$dbco)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("pagelinks", $dbco);
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
return $sql;
}
?>
Should be straightforward but this ajax call returns an empty string and causes the div in the HTML to disappear. This is the first time I use ajax in an actual project. The problem must be easy to find for someone who knows what ajax really does. Can you tell the problems?
I found the answer! Thanks to all of you who had suggestions about the SQL call. But here is the actual answer to my question.
There are four steps in making an ajax Javascript to PHP call. The first two steps happen in the Javascript. The other two steps happen in the PHP.
Step 1. In Javascript decide what variables are needed in the PHP function, retrieve them.
Step 2. Make the ajax call to the PHP function. jquery has a convenient way of passing values to PHP. You have a an array of name-value pairs like this in the data item for the ajax call.
data: { node: selectnod, option: "delete" },
Step 3. Have your PHP function ready in a PHP file. Write the function like this.
function updatetree($node, $option) {
Step 4. Echo a call to the php function within that PHP file.
With these four steps you should have a succesful call to PHP and be able to return information to javascript from the PHP function.
Here is the javascript function.
function deleteitem()
{
//Get selected node to send to PHP function
var selectnod = getCookie('pnodid');
//Define php info, specify name of PHP file NOT PHP function
//Note that by loading the PHP file you will probably execute any code in that file
//that does not require a function call
//Send PHP variables in the data item, and make ajax call
//On success perform any action that you want, such as load a div here called thenode
$.ajax({
url: "uptree.php",
type: "POST",
data: { node: selectnod, option: "delete" },
cache: false,
success: function (response) {
$('#thenode').html(response);
}
});
}
Here is the PHP file uptree.PHP. It has a function defined, called updatetree. It also has an echo statement to call that function. This just seems to be the way to cause the function to run. Ajax itself doesn't call the function.
<?php
//Function defined here
//The variables will come from the ajax data statement
function updatetree($node, $option) {
if($node == '' || $option == '') {
return 'Select an item in the tree.';
}
$dbco = mysql_connect('localhost', 'root', 'mmowebdb');
if (!$dbco)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("pagelinks", $dbco);
$sql = '';
switch($option) {
case 'delete':
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
break;
case 'add':
list($pagename, $address) = explode(",", $page);
$pagename = trim($pagename);
$address = trim($address);
$sql = "INSERT INTO dtree_table (nid, pid, name, url) values (NULL, ".$node.", '".$pagename."', '".$address."')";
break;
case 'update':
break;
}
if (!empty($sql)) return $sql;
}
//echo statement to run function, variables sent by ajax are retrieved with $_REQUEST
//they could have also been retrieved with $_GET or $_POST
echo updatetree(trim($_REQUEST['node']),trim($_REQUEST['option']),trim($_REQUEST['page']));
?>
So to recap. Javascript gets variables, makes ajax call to PHP file. Ajax loads PHP file which contains echo statement that causes PHP function to run. That PHP function is defined in that same file. The function return statement sends information back to javascript through ajax. Javascript does something with that information, e.g. load it into a div on the HTML page.
You actually need to execute the query you create:
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
$result = mysql_query($sql);
return $sql;
Then result will contain a Boolean of success status.
Also when you pass it back to the javascript call you may need to set the appropriate page header of plaintext or json (if you decide to use json)
I highly recommend using a tool like Firebug to watch each ajax request. Then you can see the posted data, response data, and headers to help you diagnose your issue further. Currently only Firefox (AFAIK) fully supports the firebug extension, but firebug lite is also available for other browsers.
You haven't passed $sql into mysql_query();
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
mysql_query($sql);
// -------^^^^^^^^
return $sql;
Your code is vulnerable to SQL injection, as it only checks for an empty $node. As an end user, I could delete any id in the database I wish, or all of them if I ran the code in a loop. You will need something to check that the user running the code has permission to delete the node, and also, call mysql_real_escape_string() on $node.
$node = mysql_real_escape_string($node);
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
$result = mysql_query($sql);
// Check for success...
if ($result) {
// return success codes to ajax caller
}
else {
// return error codes to ajax caller
}
ADDENDUM
We don't see the code where you call upTree() in PHP. Are you actually calling the function? If you don't call it and that's your whole PHP script, then it will execute, do nothing, and return a blank HTTP response to your Ajax calling function with a successful 200 response code.
I send back the query as a reponse to debug it before performing a
delete query.
...
this ajax call returns an empty string and causes the div in the HTML
to disappear.
I assume you want the query displayed inside your div. You need echo($sql); or echo(uptree()); or equivalent somewhere in your program. You might also create an HTML form that POSTs the same data as your AJAX to see what PHP is returning.
Related
NOTE - This is a edited snippet. This is testing at the moment and will be improved after.
I'm aiming to learn oop PHP now I got a good understanding of procedural. I'm stuck on sending this Ajax request to my php file.
Html File
<script>
$("#Question").click(function() {
flag = 1;
uid = "<?php echo $uid ?>";
var dataQuestion = {
uid,
flag,
ImageOne: $("#Image1").val()
};
//Post with AJAX
$.ajax({
type: "POST",
url: "../View/class.user.php",
data: dataQuestion,
perform: "QuestionsFunctions",
success: function(Returned){
$(".NotBoxSmall").text("Updated");
$(".NotBox").text("Updated");
flag = 0;
console.log(Returned);
},
error: function(){
$('.NotBox').text("Issue With Site");
$('.NotBoxSmall').text("Issue With Site");
}
});
});
</script>
Php file
<?php
public function QAsk(){
if($_POST['flag'] == 1){
$Image1 = $_POST['ImageOne'];
$uid = $_POST['uid'];
$insertsqlQ = "UPDATE UsersData
SET Image1 = '$Image1'
WHERE uid = $uid";
$resultquestion = mysqli_query($this->db,$insertsqlQ) or die(mysqli_connect_errno().json_encode("Data cannot inserted"));
return $resultquestion;
echo json_encode("Question Updated");
}else{
echo json_encode("Question NOPE");
return false;
}
}
?>
The id sends and iv'e tested this not within the public function and it appears to be fine. The request send back is blank, outside of the function it's the error log.
The issue is it says questions have been updated but no data has been added to the database.
jQuery must be initialized after the DOM ( document object model ).
How should I initialize jQuery?
I'd suggest some tips:
1 - Make the id names lower case #name_of_element
2 - Grab a OO PHP book and try to practice just this, run tests using curl for instance and make your database rules work before going into the client (html, js, css)
3 - Grab a jQuery book and run tests with mock data just printing a array from PHP. At the beginning is easier study stuff separated.
4 - '$Image1' is a varchar rather than the variable $Image1. Remove the quotes
I'm very new to php and SQL so i'm really sorry if this is very trivial.
My site has multiple divs with table names inside it. The HTML is of the form:<p class="listname">(table name)</p>
I am trying to write a function so that when a user clicks on a div, the function gets the text using innerHTML and the contents of that particular table are shown.
The jquery function i wrote is:
$(document).ready(function(){
$(".listname").click(function(){
var x=($(this).html()).toLowerCase(); //this assigns the text in the class listname to the variable x
console.log(x);
$.ajax({
url: 'http://localhost/fullcalendar/events.php',
data: {name:x},
type: "GET",
success: function(json) {
}
});
});
});
And my PHP code is:
<?php
include 'ChromePhp.php';
ChromePhp::log('php running');
$json = array();
if($_POST['name']!=null)//check if any value is passed else use default value
{
$table=$_GET['name'];
ChromePhp::log($table);
}
else
{
$table= 'event';
ChromePhp::log($table);
}
$requete = "SELECT * FROM `$table` ORDER BY id";
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
When i first load the website, the default value for $table is used in the query, and data is retrieved. However, when i try clicking on a div, the correct value is passed to php and assigned to $table (i checked in the console) but the data displayed is of the default table i.e 'event' table.
How can i fix this?
PS: all my tables are in the same database.
You're checking the POST data:
if($_POST['name']!=null)
But using GET data:
type: "GET"
So the $_POST array will always be empty and your if condition will always be false. You probably meant to check the GET data:
if($_GET['name']!=null)
Also of note are a couple of other problems in this code:
Your success callback is empty, so this AJAX call isn't going to actually do anything client-side. Whatever you want to do with the returned data needs to be done in that success function.
This code is wide open to SQL injection. It's... very unorthodox to dynamically use table names like that. And this is probably an indication that the design is wrong. But if you must get schema object names from user input then you should at least be taking a white-list approach to validate that the user input is exactly one of the expected values. Never blindly execute user input as code.
I am having a problem with setInterval in the $(document).ready(function(){}
What I am doing is setting the interval to do is call a PHP script that runs some MySQL queries to check the condition of 4 switches and then updating the screen with the values are in the database like so:
$(document).ready(function(){
setInterval(function(){
<?php require('fetchSwitchStatuses.php'); ?>
$("#switch1").css('background', 'rgb(<?php echo $switchColor1 ?>)');
$("#switch1").html('<?php echo $switchState1 ?>');
$("#switch2").css('background', 'rgb(<?php echo $switchColor2 ?>)');
$("#switch2").html('<?php echo $switchState2 ?>');
$("#switch3").css('background', 'rgb(<?php echo $switchColor3 ?>)');
$("#switch3").html('<?php echo $switchState3 ?>');
$("#switch4").css('background', 'rgb(<?php echo $switchColor4 ?>)');
$("#switch4").html('<?php echo $switchState4 ?>');
},1000);
});
Here is the code for fetchSwitchStatuses.php:
$connect = mysqli_connect("localhost", "root", "root");
mysqli_select_db($connect, "db_name");
$fetch1 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '3'"
);
$fetch2 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '5'"
);
$fetch3 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '6'"
);
$fetch4 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '9'"
);
$i = 1;
while($row = mysqli_fetch_array(${'fetch'.$i}))
{
if($row['SwitchStatus'] == 0)
{
${'switchColor'.$i} = "255, 0, 0";
${'switchState'.$i} = "OFF";
}
else if ($row['SwitchStatus'] == 1){
${'switchColor'.$i} = "0, 255, 0";
${'switchState'.$i} = "ON";
}
else {
${'switchColor'.$i} = "100, 100, 100";
${'switchState'.$i} = "ERROR";
}
$i++;
}
mysqli_close($connect);
When the page is loaded the information is correct, whatever is in the database is what is reflected by the colors on the screen.
When I click on the object to change the value, all of the necessary changes are made and the database is updated. However, the problem arises when the Interval is repeated. The values are switched back to whatever the original values were when the page was loaded. So, although the information is correctly changed in the database, for some reason the colors of the buttons is always reset to the first value read by the queries.
How can I fix this so that the information that is reflected on the screen is accurate?
With AJAX technology you can:
Send a request and get results from server by requesting a page (a .txt .js .html or even php).
So with AJAX you can get result of a page save something to database, get something from data base, you can work with sessions and anything you can do with a php file.
When you send an AJAX request to a see a page(i.e /userData.php?userId=5) the page /userData.php?userId=5 will be executed and its output will be returned.(HTML or just a word ‘yes’ or ‘no’ or ‘you can’t access to this user’s information’).
You can send data to file with POST or GET. But the question is how you can get data from page. Because the result AJAX will give you is what the requested page echoed to page like this
<html>
….
</html>
Or
‘Yes’
Or
<?php echo ‘something’; ?>
So what about getting a row of Date or lots of data? Because the only thing you are getting is a text or maybe a long text.
For that you can use JSON which Is something like nested arrays.
[
{
"term": "BACCHUS",
"part": "n.",
"definition": "A convenient deity invented by the...",
"quote": [
"Is public worship, then, a sin,",
"That for devotions paid to Bacchus",
"The lictors dare to run us in,",
"And resolutely thump and whack us?"
],
"author": "Jorace"
},
…
And this is a string too. But you can get Data in it with $.getJSON in jQuery and you can generate JSON data in server side like this.
<?php
$arr=array(
‘data’=>’ffff’,
‘anotherData’=>array(‘rrrrr’,’sssss’);
);
Echo json_encode($arr);
?>
Json_encode() in PHP gets an array and returns json string of it. And we echo it.
Now we can use jQuery to get Data which will be retrieved from server.
This section if from
Learning jQuery 1.3
Better Interaction Design and Web Development with Simple JavaScript Techniques
Jonathan Chaffer
Karl Swedberg
Global jQuery functions
To this point, all jQuery methods that we've used have been attached to a jQuery object that we've built with the $() factory function. The selectors have allowed us to specify a set of DOM nodes to work with, and the methods have operated on them in some way. This $.getJSON() function, however, is different. There is no logical DOM element to which it could apply; the resulting object has to be provided to the script, not injected into the page. For this reason, getJSON() is defined as a method of the global jQuery object (a single object called jQuery or $ defined once by the jQuery library), rather than of an individual jQuery object instance (the objects we create with the $() function).
If JavaScript had classes like other object-oriented languages, we'd call $.getJSON() a class method. For our purposes, we'll refer to this type of method as a global function; in effect, they are functions that use the jQuery namespace so as not to conflict with other function names.
To use this function, we pass it the file name as before:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json');
return false;
});
});
This code has no apparent effect when we click the link. The function call loads the file, but we have not told JavaScript what to do with the resulting data. For this, we need to use a callback function.
The $.getJSON() function takes a second argument, which is a function to be called when the load is complete. As mentioned before, AJAX calls are asynchronous, and the callback provides a way to wait for the data to be transmitted rather than executing code right away. The callback function also takes an argument, which is filled with the resulting data. So, we can write:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
});
return false;
});
});
Here we are using an anonymous function as our callback, as has been common in our jQuery code for brevity. A named function could equally be provided as the callback.
Inside this function, we can use the data variable to traverse the data structure as necessary. We'll need to iterate over the top-level array, building the HTML for each item. We could do this with a standard for loop, but instead we'll introduce another of jQuery's useful global functions, $.each(). We saw its counterpart, the .each() method, in Chapter 5. Instead of operating on a jQuery object, this function takes an array or map as its first parameter and a callback function as its second. Each time through the loop, the current iteration index and the current item in the array or map are passed as two parameters to the callback function.
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
$('#dictionary').empty();
$.each(data, function(entryIndex, entry) {
var html = '<div class="entry">';
html += '<h3 class="term">' + entry['term'] + '</h3>';
html += '<div class="part">' + entry['part'] + '</div>';
html += '<div class="definition">';
html += entry['definition'];
html += '</div>';
html += '</div>';
$('#dictionary').append(html);
});
});
return false;
});
});
Before the loop, we empty out so that we can fill it with our newly-constructed HTML. Then we use $.each() to examine each item in turn, building an HTML structure using the contents of the entry map. Finally, we turn this HTML into a DOM tree by appending it to the .
This approach presumes that the data is safe for HTML consumption; it should not contain any stray < characters, for example.
There are several questions like this on SO but none of the answers have worked for me. I have tried them all.
I tried to minimize the code I am pasting, but it's kind of hard with this script
I have a comment form that is submitted via ajax to a php script which saves the comment and then gets all the comments and redisplays them so the new comment can be displayed without refreshing the page.
Only sometimes will the comments successfully submit to the database and redisplay properly. Usually almost every other submit the comment will be saved. Every other time nothing seems to happen.
My real issue is the comments not being saved every time one is submitted.
Here is the javascript and the ajax call:
$(document).ready(function(){
var working = false;
$('#commentForm').submit(function(e){
if(working) return false;
working = true;
$('#submitComment').val('Working..');
$('span.error').remove();
$.post('/ajax/comment.process.php',$(this).serialize(),function(msg){
working = false;
$('#submitComment').val('Submit');
if(msg.status){
$('#commentArea').slideDown().$(msg.html).prepend('#commentArea');
$('#blogComment').val('');
}
else {
$.each(msg.errors,function(k,v){
$('label[for='+k+']').append('<span class="error">'+v+'</span>');
});
}
},'json');
});
});
and here is the function that submits the comment:
public function addComment($user_id) {
$validate = new data_validation;
$_POST = $validate->sanitize($_POST);
$newCom = $_POST['blogComment'];
$blog_id = intval($_POST['blogID']);
$photoSubmit = $_POST['comPhoto'];
$newComQuery = $this->mysqli->query("INSERT INTO b_comments (blog_id, user_id, date, content, photo) VALUES ('".$blog_id."', '".$user_id."', Now(), '".$newCom."', '".$photoSubmit."')");
if($newComQuery === false) {
echo "Query failed";
}else{
$returnCom = $this->comMarkup($blog_id);
echo $returnCom;
}
}
and here is a piece of the comMarkup() function that echos the comments (it is only the important pieces):
// This method outputs the XHTML markup of the comment
public function comMarkup($blog_id) {
$sql = $this->mysqli->query("SELECT * FROM b_comments WHERE blog_id = '".$blog_id."' ORDER BY date DESC");
while($d = $sql->fetch_assoc()) {
$d = $validate->sanitize($d);
echo "
<div class='comment-block'>
<span class='com-img'><img src='".$photo_path."' /></span>
<h3 style='display: inline;'><a href='".$profile."'>".$userName."</a></h3>
<div class='com-date'>".$d['date']."</div>
<p>".$comContent."</p>
</div>
";
}
}
EDIT: Here is the comment.process.php code as requested:
session_start();
include_once('../classes/comment.class.php');
include_once('../classes/db.class.php');
include_once('../classes/user.class.php');
$user_id = $_SESSION['user_id'];
$db = new DBConnection;
$comments = new Comment($db);
$user = new User($db);
$blogID = intval($_POST['blogID']);
$addCom = $comments->addComment($user_id);
echo json_encode(array('status'=>1,'html'=>$addCom));
Given your description, my guess is that it has something to do with your working variable, and the fact that it is not set to false at the end of your $.post().
But there are a few logic, efficiency, and manageability issues with the way you've drawn up the process. I'd recommend having a look at the official jQuery docs for $.post(), specifically the .done(), .fail(), and .always() chained methods.
I'd also recommend naming your PHP variable something other than $_POST, so it does not become confused with the PHP super global.
Finally, I'd recommend treating your comment as an object and using PDO (this is a link to PDO:query as a kind of "immersion" approach but be sure to read all the docs). It will save you a ton of headaches in database interaction.
It looks like you've got a race condition caused by the working flag. Since you're just using that flag to show the "working..." message and prevent submits while a request is processing, I would just use the normal $.ajax call and put the "working" logic in the beforeSend option. Here's an example:
$(document).ready(function(){
$('#commentForm').submit(function(e){
$.ajax({
type: 'POST'
url: '/ajax/comment.process.php',
dataType: 'json',
beforeSend: function(jqXHR, settings) {
$('#submitComment').val('Working..');
$('span.error').remove();
},
data: $(this).serialize(),
complete: function(jqXHR, textStatus) {
var msg = jqXHR.responseText;
$('#submitComment').val('Submit');
if(msg.status){
$('#commentArea').slideDown().$(msg.html).prepend('#commentArea');
$('#blogComment').val('');
}
else {
$.each(msg.errors,function(k,v){
$('label[for='+k+']').append('<span class="error">'+v+'</span>');
});
}
};
});
});
});
are you using json_encode()? if not all your echo-backs will be received as "text" and not as an json-object which you're accessing in your jquery
I guess you should use encodeURIComponent($('#blogComment').val()) somwhere for passing your blogcomment value to PHP file for insert.
Edit 1:
public function addComment($user_id) {
$validate = new data_validation;
$_POST = $validate->sanitize($_POST);
$newCom = rawurlencode($_POST['blogComment']);
if rawurlencode() did not work. use following function:
function encodeURIComponentNew($str) {
$revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')');
return strtr(rawurlencode($str), $revert);
}
(function from What is the equivalent of JavaScript's encodeURIcomponent in PHP?)
and then
public function addComment($user_id) {
$validate = new data_validation;
$_POST = $validate->sanitize($_POST);
$newCom = encodeURIComponentNew($_POST['blogComment']);
Doubt this is related, but I've had issues in the past when doing ajax stuff using "echo" inside a function, and then trying to echo the returned value again.
Try changing your echo's inside all your functions for "return" instead like so:
public function addComment($user_id) {
$validate = new data_validation;
$_POST = $validate->sanitize($_POST);
$newCom = $_POST['blogComment'];
$blog_id = intval($_POST['blogID']);
$photoSubmit = $_POST['comPhoto'];
$newComQuery = $this->mysqli->query("INSERT INTO b_comments (blog_id, user_id, date, content, photo) VALUES ('".$blog_id."', '".$user_id."', Now(), '".$newCom."', '".$photoSubmit."')");
if($newComQuery === false) {
return "Query failed";
}else{
$returnCom = $this->comMarkup($blog_id);
return $returnCom;
}
}
If the user send a comment with ' maybe will happens an error. When you send a comment, the string will broke a mmysqli_query. It can help you, MAYBE.
public function addComment($user_id) {
$validate = new data_validation;
$_POST = $validate->sanitize($_POST);
$newCom = htmlspecialchars($_POST['blogComment'], ENT_QUOTES);
$blog_id = intval($_POST['blogID']);
$photoSubmit = htmlspecialchars($_POST['comPhoto'], ENT_QUOTES);
$newComQuery = $this->mysqli->query("INSERT INTO b_comments (blog_id, user_id, date, content, photo) VALUES ('".$blog_id."', '".$user_id."', Now(), '".$newCom."', '".$photoSubmit."')");
if($newComQuery === false) {
echo "Query failed";
}else{
$returnCom = $this->comMarkup($blog_id);
echo $returnCom;
}
}
It might cause of Browser cookiess. So that In your URL just add addtional queryString for unique URL pattern.
Example:
$.post('/ajax/comment.process.php?random=randamnumber');
You have a SQL Injection vulnerability in your PHP code, make sure you're escaping your variables properly or use a prepared query.
As for the JS part, make sure to return true; at the end of your .submit() function. (for you it would be after the $.post() call)
Also, your 'working' variable can be set forever to true if there's an error in your php script, which is very likely to happen with the SQL Injection Vuln in place.
Explanation: You set it to true, success callback possibly doesn't get called because of error 500 from PHP Backend, so it never gets set to false by your callback, and then you can't ever submit anymore till next page refresh.
So, if I understand the problem correctly, you're submitting the comment and it's not inserting into the database, and it's also presumably not showing you a database error or printing out your Query failed string?
It seems as though your PHP script isn't being executed at all?
If this is the case, I would normally say the most likely culprit for an intermittent error like this is your browser cache. Your browser is looking at the URL, thinks it already knows what content goes with that URL, and returns that content without ever even sending your info to the server. The simplest way to beat that is to add a random querystring to your file call, e.g.:
cachebuster = new Date();
'/ajax/comment.process.php?cachebuster='.cachebuster.getTime();
... I say "normally" since you're using POST and under "normal" circumstances the browser does not cache POST requests. But it is possible, and it's trivial to combat, so give it a shot. This can also be diagnosed, if you use Chrome, by hitting f12, going to the "network" tab, and then running your form. It should tell you if the result was retrieved from cache.
Beyond that, if you're relying on magic_quotes (or worse, you're not relying on magic_quotes), you need to learn the proper way to deal with SQL injection. You should never be inserting untrusted data from the browser directly into the database. Escape it or use parameterized queries. If you're experiencing an intermittent problem with your query, it's probably related to the content of your comment throwing the query off under certain circumstances, as mentioned above, most likely with the inclusion of an apostrophe in a contraction. Diagnose by submitting two forms back to back: trythis and then try'this. If the first one goes and the second one fails, you've likely found your answer. Properly escaping your input would solve this problem.
Ultimately, all of these suggestions have already been given above, but hopefully this provides a little context to help understand the whys and wherefores.
Edit: I see, now that I look closer, that you are in fact escaping your query with a method you haven't shared here. Assuming that's working correctly, then that shouldn't be a concern.
Try echoing out a valid response at the beginning of your script without even executing anything. If that always returns, then you at least know the script is being called successfully.
There could be a problem with your working variable in the event that the ajax call returns with an error. It would never, under those circumstances, set it back to false.
Your #1 ally is the "network" tab in Chrome Developer Tools or watching the response in the console tab in Firefox Firebug extension.
Edit 2:
$.post('/ajax/comment.process.php',$(this).serialize(),function(msg){
// post stuff, REMOVING the working variable set, cuz it won't be necessary here...
},'json').always(function() { working = false; });
What I'm trying to do is create a slideshow by grabbing database information and putting it into a javascript array. I am currently using the jquery ajax function to call information from a separate php file. Here is my php code:
mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$i = 0;
$sql = mysql_query("SELECT comicname FROM comics ORDER BY upldate ASC");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
echo "comics[" .$i. "]='comics/" .$row['comicname']. "';";
$i++;
}
What I want is to create the array in php from the mysql query and then be able to reference it with javascript in order to build a simple slideshow script. Please let me know if you have any questions or suggestions.
Ok have your .php echo json_encode('name of your php array');
Then on the javascript side your ajax should look something like this:
$.ajax({
data: "query string to send to your php file if you need it",
url: "youphpfile.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]); //this should tell you if your pulling the right information in
}
});
maybe replace data.length by 3 or something if you have alot of data...if your getting the right data use a yourJSArray.push(data[i]); I'm sure there's a more direct way actually...
You may want to fetch all rows into a large array and then encode it as a JSON:
$ret = array();
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
$ret[] = $row
echo json_encode($ret);
Then, on the client side, call something like this:
function mycallback(data)
{
console.log(data[0].comicname); // outputs the first returned comicname
}
$.ajax
(
{
url: 'myscript.php',
dataType: 'json',
success: mycallback
}
);
Upon successful request completion, mycallback will be called and passed an array of maps, each map representing a record from your resultset.
It's a little hard to tell from your question, but it sounds like:
You are making an AJAX call to your server in JS
Your server (using PHP) responds with the results
When the results come back jQuery invokes the callback you passed to it ...
And you're lost at this point? ie. the point of putting those AJAX results in to an array so that your slideshow can use them?
If so, the solution is very simple: inside your AJAX callback, put the results in to a global variable (eg. window.myResults = resultsFromAjax;) and then reference that variable when you want to start the slideshow.
However, since timing will probably be an issue, what might make more sense is to actually start your slideshow from within your callback instead. As an added bonus, that approach doesn't require a global variable.
If this isn't where you are stuck, please post more info.