Using Ajax to call PHP that updates data in MySQL - php

I've been researching this for awhile and there are a lot of similar questions that have been asked. I tried researching as much as I could and came up with a code that should work in theory... but for whatever reason, it just doesn't. I can't seem to figure it out!
I am using JQuery/AJax to call a php file and update SQL records. Here is the general gist of the code. Whats left out is essentially a button click action which calls the ajax function. The Php is going to (eventually) add the StoreID value to an array, serialize it and add it into mysql.
Each piece of the code works on their own, but when put together it just doesn't work!
Java Script Code:
jQuery.ajax({
type: 'POST',
url: 'storeid.php',
data: {StoreID: IDjs[x] },
success: function(reponse) {
$('#error').html('Success! SkipID: ' + IDjs[x]);
onStateNext(); },
error : function(code, message){
$('#error').html('Error Code: ' + JSON.stringify(code) + ', Error Message: ' + JSON.stringify(message));}
});
The weird thing about this code, is that the "Success" functions get output. The success callback is displayed and the proceeding script is run.. despite the fact that it doesn't appear to actually send the StoreID variable to the php file.
The PHP Code (storeid.php):
$test=$_POST['StoreID'];
if (isset($test))
{
global $conn2;
$memberid = $_SESSION['memberID'];
$testarray = array(7,8,$test);
$serialized_data = serialize($testarray);
$insertsql = "UPDATE StoreIDs SET IDs = '$serialized_data' WHERE MemberID = $memberid";
if (mysqli_query($conn2, $insertsql))
{
echo "Updated with StoreID: " . $test;
} else {
echo "Error updating record: " . mysqli_error($conn2);
}
} else {echo "no isset value"; }
This code also works when run without the ajax. It'll properly update the record when called directly by php but not when called by the ajax script above.
Any ideas of what I could have done wrong?

Figured out thanks to #JayBlanchard. You can use the firefox developer tools to see server responses, which allowed to see the error messages and realize that it was communicating but simply not getting the credentials from the database.
Turns out you can't use global variables if the database file isn't included. I thought it didn't need it, since it works fine when running server side, but since ajax is run client side after the server has closed the connections for the database, it needs to be opened again!

Related

AJAX issues (Cannot get ajax to successfully work) PHP, AJAX, JAVASCRIPT, WORDPRESS (NO PLUGIN)

I asked a question earlier today with little luck:
AJAX within a foreach loop
i was put on the right path but the answer provided has got me more confused than ever.
Whenever i click on my anchor tag with the ajax call, nothing happens. When i go into console view and check the network tab, it says the call was a success. when i go further into the call details it shows all the data i sent and the page it went too. The code on page_id=252 does not fire whatsoever.
I am using wordpress for this assignment.
I am using custom templates to hold my PHP code. not a plugin.
I have two pages:
Index.php
ajaxcall.php
Index.php (?page_id=## is default permalinks to my wp pages. this location is valid.)
<script type="text/javascript">
function onClickingThis(rem_opt,vidid){
$.ajax({
url: '?page_id=252',
type: 'POST',
data: {action: 'update_this_func', remove_option: rem_opt, uservideo_id: vidid },
dataType: 'json',
success: function(response){
console.log('works');
}
});
}
</script>
// all my php code, for everything on the page.
<a href="#" onclick="onClickingThis(0,1)></a>
ajaxcall.php
function update_this_func(){
$remove_option = $_POST['remove_option'];
$uservideo_id = $_POST['uservideo_id'];
global $wpdb;
$wpdb->query("UPDATE " . $wpdb->prefix."uservideo
SET is_removed =" . $remove_option . "
WHERE uservideo_id =" . $uservideo_id );
return json_encode(['status' => 'Updated!']); // return status as json
}
This code was provided by user: Ervald, but he did not want to elaborate on his code.
My success message is not working for the ajax, but i am not getting any errors in the console.
How do i debug my ajax? is my ajax not set up properly? If this is not the right way to use ajax please let me know. Any help is GREATLY appreciated.
there have been 2 problems in your PHP script:
1. the function was not called
2. the return-value of the function was not echoed.
(in order to respond to an AJAX call, the called url always needs to output something - JSON in the most cases. AJAX can't access PHPand thus can't read PHP return values.)
here is the fixed version:
function update_this_func($remove_option, $uservideo_id){
global $wpdb;
$wpdb->query("UPDATE " . $wpdb->prefix."uservideo
SET is_removed =" . $remove_option . "
WHERE uservideo_id =" . $uservideo_id );
return json_encode(['status' => 'Updated!']); // return status as json
}
echo update_this_func($_POST['remove_option'], $_POST['uservideo_id']);

Is it possible to 'echo' a sequence of responses from an ajax call

I'm learning and experimenting with jquery/ajax as I develop a website. I have a page that updates a database. I would like a 'sequence' of responses to display on the screen when the user submits their data (I've seen this done on many other sites).
For instance... user submits form and the page displays:
Received Input
Checking Database - recond number xy
Updating Database
Retrieving Information
etc etc
This is just an example but you get the idea.
I have an ajax call that is initiated on 'click' of the submit button (getFormData just serialises all the form data for me and works fine):
var toSend = getFormData($upgrade_db_form);
var formMessageBox = $("#displayResults");
$.ajax({
url: ajaxurl,
data: {
action: "database_action",
formData : toSend
},
type: 'POST',
dataType: 'TEXT',
beforeSend: function() {
//$form.fadeOut('slow');
formMessageBox.html("starting it up");
},
success: function (data) {
formMessageBox.empty();
formMessageBox.html(data);
error: function (xhr) {
// formMessageBox.html("Oops error!");
}
});
I have a function which gets called by ajax:
function upgrade_database_function() {
echo "testing ";
for($i = 0; $i < 99; $i++) {
echo "percent complete ".$i."%";
}
echo "done ";
die(); // this is required to return a proper result
}
I'm using Wordpress and all the ajax side of things works fine, it passes the form data correctly etc, it's just that I get one long output as though it's cache'ing all the echo's up instead of outputting them in sequence.
I've gone through the jquery ajax documentation and couldn't find how to make it behave the way I want it to. I can live with it the way it is but I think it would look a lot better if I could get it working the way I would like.
Can this be done this way or do I need lots of sequential ajax calls to make it work?
I don't know PHP, but i'm guessing that the echo is just writing to the response buffer... so when all the echos are done the whole response will be returned and you would get the effect that you are seeing... You would need to go with a polling system or something along those lines to get the latest status' from the server and display them I would think... Maybe there is some system in PHP that allows this, but as I said, I don't know PHP.
An Example of Long Polling can be found in this article.
http://www.abrandao.com/2013/05/11/php-http-long-poll-server-push/
WARNING: You may have to do some manual managing of locking of the session in PHP so that your long running call doesn't lock your polling ajax calls: See here:
http://konrness.com/php5/how-to-prevent-blocking-php-requests/
Note that you would likely be wanting to:
create one ajax call that starts the execution of some coded that will take a while... you could put messages that have been generated into a session variable for example in a list of some sort. You would need to lock/unlock the session as mentioned to prevent suspension of AJAX polling calls.
you would create a polling method like in the article that might check the session every 500ms or something to see whether there are any more messages, lock the session, remove those messages and return those messages to the client side and display them.
WARNING: Again, I'm not a PHP person, I may have done this once in my life in PHP (can't remember exactly) but I may be wrong and this may not work, from what I've seen though it looks like it is achievable. Hope this gets you on your way!

Massive jQuery update -> My ajax doesn't work anymore

I've been using stackoverflow for months now as it really is the the most reliable resource I can think about. However, I now have my own question.
I'm working on a script that displays available courses in an HTML5 page using ajax after calling some php/MySQL interaction. I was using jQuery 1.4.1 (yeah... i know) and due to some interesting new plugins available, I updated to 1.10.2.
Now my page doesn't display the product of the PHP/SQL processing anymore, nor does the autoscroll work.
I did some search and didn't find any answer.
I was hoping you guys would see directly the incompatibility in my code, or the usage of a too old syntax.
Trigger :
<a class="internal-link" href="#" onclick="goToByScroll('reanimation');"></a>
Script :
function goToByScroll(id){
$.ajax({
type: "POST",
url: "kernel/appel-tableaux-ajax.php",
dataType: "script",
data:{type_cours : id},
success: function(array){
var objet = JSON.parse(array);
var message = objet["message"];
var nombre = objet["nombre"];
$("#conteneur-tableaux").html(message);
$("#nombre-cours").html(nombre);
if(nombre==0)
{
$("#titre-section-tableaux").css("color","darkred");
}else{
$("#titre-section-tableaux").css("color","darkgreen");
}
$('html,body').animate({scrollTop: $("#section-tableaux").offset().top},'slow');
}
});
}
PHP code (I erased stuff where mistakes are less probable) :
ob_start(); // I want to catch all the 'echos' to insert them in an array.
while ($donnees = $reponse->fetch())
{
// Lots of Date comparison stuff and many ECHOS.
}
$out = utf8_encode(ob_get_contents()); // --- I put every echos inside the 'OUT' variable.
ob_end_clean();
// --- I want to send back 2 things to my script, some infos about the courses available, and the total number of available courses. So I create an array.
$output_final = array ("message" => $out, "nombre" => $compteur_cours);
echo json_encode($output_final);
?>
As you can see, I'm a beginner in Ajax and jQuery usage.
UPDATE :
Thanks a lot to all those who already helped.
I tried the debug tools in Chrome, the php generates exactly what it's supposed to do, which means that my ajax is able to call the PHP code placed in kernel/appel-tableau-ajax.php. The Console.log() placed in the success case doesn't display anything.
I'm adding a screenshot of the syntax errors that Chrome detected. If someone could help me to understand how to handle those errors it would be wonderful.
Link to the screenshot
Also, Safari's debugger says : SyntaxError: JSON Parse error: Unexpected identifier "object".
I can't believe all this worked on the old jQuery version...
Thanks a lot, I hope I'm not asking too much!
if your php code return json why the 'dataType' in your ajax is 'script'? try change it to json.
hope it will work! :)

PHP function on close with jQuery AJAX

I've been working this problem for awhile and seen a lot of different approaches. I have code that I believe should be working, but for one reason or another is not.
Here is my JavaScript code file name - test.js:
function deleteTempTable() {
$.ajax({
url: "exit.php",
success: function(data) {
alert("Deleting Temp Table");
}
});
}
I placed the alert purely for testing purposes to make sure the AJAX call was being made, and it is.
Here is the HTML for the button that makes the AJAX call file name - form.template:
<input type="button" title="Click to close window" value="Close"
onclick="deleteTempTable();" style="width:80px" name="close">
This does work as I get the JavaScript alert just fine.
Here is an EXAMPLE of the php code I'm using (it's not exact as it has some stuff I can't share, custom classes etc, either way I've reused this same pattern else where and it works fine and drops the tables as needed) file name - exit.php :
<?php
session_start();
require $_SERVER['DOCUMENT_ROOT'] . "path/to/file.php";
$tempTableName = $_SESSION['tempTableName'];
//Not really hard coding this it's just an example
$odbcConn = odbc_connect('DataBaseName', 'UserName', 'Password');
$sqlCmd = "DROP TABLE IF EXISTS $tempTableName;";
odbc_exec($odbcConn, $sqlCmd);
?>
When I click the button the JavaScript alert pops up, but it appears as the the php is ignored since the table still exists. Elsewhere in my code use the same php pattern to drop tables when new sets of data are requested, and they drop fine. Just not when I try to do it with this button.
Any ideas or pointers would be great!
Also I saw this question, "Calling PHP function using JQuery .ajax()", but his problem was syntax, and I'm pretty sure with my IDE I'm not having a syntax error, and from what I've seen this is the solution posted.
UPDATE
Thanks to some suggestions I was able to get a test that would confirm the php code itself works, but is not actually being executed by the AJAX call. Essentially I just ran the page that created the table, ie index.php, and then directed the browser to exit.php and the table was deleted as I would have expected. So the only conclusion is that exit.php is not actually being called/executed by the AJAX call.
I don't know if this could be the problem but here is my actual url assignment (more or less): url: "/folder1/folder2/folder3/folder4/exit.php" I had tried url: "exit.php" as well, so I don't know if I need the full root path to the file or not, or if this is some how the issue. At this point I'm just brain storming since I at least now know the php is not being executed or opened properly.
UPDATE
Well thanks to Salivador walking me through some trouble shooting the problem is solved. Basically the code is correct. So feel free to use it if you need to do something like this, however don't do what I did and mess up the PATH TO THE FILE!
face palm
Your ajax call is executed, but are you sure that your PHP code is executed correctly and as intended?
Try to output the $tempTableName to see do you actually getting the right name for your table, try to see the response of odbc_exec(...) command to see what is the result of deletion.
quick reaction is that the sqlcommand is including a semi-colon, remove that
heres an alternate method, do this in your php code
html
<input type="button" title="Click to close window" value="Close"
onclick="deleteTempTable('mytable');" style="width:80px" name="close">
exit.php
if($_REQUEST['command'] == 'droptable') {
echo dropTable($_REQUEST['tablename'] ));
}
...
function dropTable($tableName){
/*your sql stuff/code here*/
$sqlCmd = 'Drop Table '.$tablename;
$rz = odbc_exec($odbcConn, $sqlCmd);
if (!$rz){
$result = true;
} else {
$result = false;
}
return $result;
}
then you could do this
function deleteTempTable(tablename) {
var params = 'command=droptable&tablename='+tablename;
$.ajax({
url: "exit.php?"+params,
success: function(data) {
if(data == true) {
alert("Deleting Temp Table");
} else {
alert("Didnt work");
}
}
});
}
Just one way of doing it , i personally wouldnt use an onclick to fire the function, i prefer selector bound events
why are you storing this table name in session data? wouldnt a form var work out better?

Running a PHP file using AJAX and sending parameters

I am trying to edit a file on my server when a user clicks a button on my web page. I generate a table of buttons using php. STRING1, STRING2 and BOOL are variables I pass to my function. The editPlist() function I made is called and the test alert() shows. The problem is that the php file is to run. I am not getting any errors either. I can't seem to figure out what is wrong.
Sample HTML button:
1 : Round 1
The button click runs this script: (the PHP in the url line generates the address of the file I want to run.)
<script type='text/javascript'>
function editPlist(stage, dance, oldValue)
{
alert('test ' + stage + dance + oldValue);
$.ajax({
type: "POST",
url: <?php echo '"'.dirname(curPageURL()).'/PlistEditorFunction.php"' ?>,
data: {"var1" : stage , "var2" : dance , "var3" : oldValue},
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
}
In the external php file PlistEditorFunction.php, I try to log a fake error and load the variables, but the error never shows. this is the beginning of the php file:
$msg = 'test error message';
error_log('['.date("F j, Y, g:i a e O").']'.$msg."<br /> \n", 3, $phperrorPath);
if (isset($_POST['data']) and trim($_POST['data']) != '' ) {
$stage = trim($_POST['var1']);
$dance = trim($_POST['var2'])
$oldValue = trim($_POST['var3']);
}
I know that the php script will only be run if the domain name matches file where the ajax is being run from. The two files are next to each other so I know that this isn't the problem.
What can I do to fix this?
change this line
url: <?php echo '"'.dirname(curPageURL()).'/PlistEditorFunction.php"' ?>
to
url: 'PlistEditorFunction.php'
and see if it works
Several things look strange.
Please verify that the url you call is in fact what you think it is. In order to do that, use a console / inspector. I recommend firebug. When you make the ajax call, it will display the url of the page you're requesting with ajax.
If it is correct, then your url param is not the problem. Next I would look at the php file itself. Try throwing an echo statement in the php file so that way your ajax response can verify that its being run. whatever you echo in the file PlistEditorFunction.php will be the response param in the success function
success: function( response ) {
console.log(response); //should be the echo'd statement of PlistEditorFunction.php
}
After mwotton's comment, I figured out that ajax was undefined. jQuery was imported, so that wan't the problem. I found the answer was I had to change $.ajax to jquery.ajax.
Some hosts don't use "$" to denote jQuery. My web host uses "jquery" instead.

Categories