Calling JavaScript function after updating table with PHP - javascript

I have a simple website that uses JavaScript to collect user input and sends data to PHP script (script is an external php file) via AJAX request. PHP script updates database with this information.
Now, i have a JS function on my website that i want to call only after PHP script is sucessfuly run and database updated. I don't need any data from database or PHP script, i only want to make sure that database is updated before calling this Javascript function.
This is what AJAX request looks like:
function ajax_post(){
if (typeof featureId !== 'undefined') {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "parse_file.php";
var fn = featureId;
var vars = "featureId="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
hilites.destroyFeatures();
featureId = undefined;
}
else {
window.alert("Select polygon first");
}
}
What is the best way to do this? Some examples would really help.

Looking at your code, you simply need to call the function around this part:
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
// CALL YOUR FUNCTION HERE
}
}
The best solution is to use a Promise. However, this is not supported in IE 11, so you will need to use a polyfill on some browsers.
Here is an example using jQuery.
// This is the function you want to call after the script succeeds
function callbackSuccess() {
console.log('Done!');
}
// This is the data you want to submit to the PHP script
var myData = {
hello: "world"
};
// This is the actual AJAX request
$.post('/my-script.php', myData).done(function(){
callbackSuccess();
});

Add this to the end of your php save-function:
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('status' => 'SUCCESS'));
Making the call:
$.getJSON('url_to_your_php_file.php', function(data) {
if (data.status == 'SUCCESS') {
console.log('Save complete');
}
else {
console.log('oops, something went wrong!!');
}
});
It's possible to return something like ERROR, this will return:
console.log('oops, something went wrong!!');

You may try the following:
In php you can use return code from sql statement
echo $sqlResult = $conn->query($sqlStatement);
On Javascript, you can try the following
$.ajax({
url: 'file.php',
type: 'POST',
data: {
data1 : data1,
data2: data2
},
success: function(data){
if(data == success_code){
alert("Success")
}
}
Hope this helps!

Completing ajax request without errors does not mean that the data is saved to DB without errors.
Even if your PHP script fails to save the data, it probably echos some error message or even empty output as regular HTTP response, and it would show as success as far as the ajax request goes.
If your intention is to make sure that the data is really saved before calling the JS function, then the PHP script should containg enough error handling.
If you write the PHP script to return response status code based on the real outcome of save operation, then you can rely on those status codes in ajax response handling (success = ok, error = not ok).
Bu what I usually do, is that instead of using HTTP status codes, I echo "OK" or something similar at the end of succesfull PHP execution (and "ERROR" if there are any errors), and then check for those strings in ajax response handler (hr.responseText in your code).

Maby you have to try this:
setTimeout(function(){
//your function here...
}, 500);

Related

Unable to make php $_REQUEST from XMLHttpRequest data

I am trying to make XMLHttpRequest from my html frontend to the php microservice backend, sending data from the input to be manipulated, and displayed on html output
The function I am trying to execute is triggered by 'onlick'
Frontend
function markRequired()
{
input_text = document.getElementById('input-text').value
input_text2 = document.getElementById('input-text2').value
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var j = JSON.parse(this.response);
mark_required = j.answer;
displayMark();
}
};
xhttp.open("GET",markURL+"?input_text="+input_text+"?input_text2="+input_text2);
xhttp.send();
return;
}
}
Backend
<?php
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json");
require('functions.inc.php');
//main array
$inputtext = $_REQUEST['input_text'];
$furthertext = $_REQUEST['input_text2'];
$totalsofar = getTotal($inputtext, $furthertext) // In php unittest the function works, so i know it's not the problem
$output['string']=$inputtext."=".$answer;
$output['answer']=$totalsofar;
echo json_encode($output);
exit();
Whenever I run my html front end and call the function, markRequired() I am not getting any response. Status code is 200 and I can see the sent data in the request URL.
When I try to return the input string, I am getting a null response.
I can't use cURL for this particular project otherwise I would have.
Any help would be much appreciated!!

Why is PHP not receiving my AJAX request string?

I am puzzled as to why PHP sees my request string as undefined.
$_GET['ask'] in my php file
produces this error -> Notice: Undefined index: ask.
But when I query the php file from the url bar in the browser like this
localhost/Websites/webProject/data.php?ask=myquery
I have set the php file to echo my string and it does do exactly that but only when I query it from the browser URL bar.
But when running the AJAX code normally from the parent html/php file
request.open("GET", "data.php?ask=myquery", true);
The PHP file does not see the query string and thinks its undefined.
Why is this the case?
I have tried to use
$_REQUEST[]; but to no avail.
I am using pure javascript for the AJAX requests.
Here is the javascript
requestResponse();
function requestResponse()
{
var READY_STATE_DONE = 4; /* request finished and response is ready */
var SUCCESS = 200; /* "OK" */
setInterval(function(){
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(this.readyState == READY_STATE_DONE && this.status == SUCCESS)
{
var response = this.responseText;
console.log(request.responseText);
document.getElementById("test").innerHTML += "<br>" + response;
}
}
request.open("GET", "data.php?ask=myquery", true);
request.send();
}, 3000)
}
Here is the PHP content
testRequest();
function testRequest()
{
$reqString = $_REQUEST['ask'];
include("dbCredentials.php");
include("dbConnect.php");
if($reqString == "myquery")
{
echo("<br />REQUEST IS: " . $reqString);
echo("<br /> Your request is granted");
}
}
DISCLOSURE: I have replaced the previous php file with data.php.
Try using Jquery Ajax request. this is mostly effective when you want to pass strings instead of serialized data
HTML:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
$.ajax({
type: 'post',
url: 'data.php?ask=whut',
success: function(response){
alert(response);
}
});
});
</script>
PHP Content:
echo $_GET['ask'];

How do I use AJAX to communicate with and run code on a server?

I've been learning to use AJAX with the GET request that allows me to access a PHP script with an array of data on a server. I want to be able to send a request that tells the server to run code that will open an application and manipulate some info on this application.
Here is the code I use to firstly communicate with the server, then send a request to the server and finally handle responses from the server.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert("cant create that object hoss");
}
else
{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4) //State were object is free and ready to communicate with server
{
food = 'bacon';
xmlHttp.open("GET", "ExecuteMaya.php?food="+food,true); //Creates request that we are sending to server
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200) //Means communication was successful
{
var xmlResponse = xmlHttp.responseText;
var xmldom = (new DOMParser()).parseFromString(xmlResponse, 'text/xml');
var text = xmldom.getElementsByTagName("response")[0];
var message = text.childNodes[0].nodeValue;
foodTextOutput = message;
setTimeout('process()', 1000);
}
else
{
alert('Something went wrong!');
}
}
}
Here is the PHP I was using while I was learning how to use AJAX. I got the following error when I printed the 'xmldom' variable from the above code to the console and inspected it - "error on line 2 at column 1: Extra content at the end of the document". This may be a different question to my original post, but I thought I'd bring up that this error occurred. This then had a knock on effect for the line 'var message = text.childNodes[0].nodeValue;' which produced the error - "Uncaught TypeError: Cannot read property 'childNodes' of undefined".
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>':
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food, $foodArray))
echo 'We do have '.$food.'!';
elseif($food == '')
echo 'Enter a food you idiot';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
The code that I have been working with to learn AJAX may not be relevant, I just thought I'd post it in case I can use some of this code that has already been written.
To sum up, I want to be able to do be able to send a boolean, or whatever is viable with AJAX, to the server that tells it to run a script. This script will then open a Maya application and run some Python code that I have written.
Thank you in advance!
As soon as you call the PHP file, this begins running code on the server. If you want to run an external application from PHP, take a look at the exec() function:
http://php.net/manual/en/function.exec.php
You have jQuery listed in your question tags. Have you compared the javascript and jQuery code?
The advantages of using jQuery are:
less typing,
simpler structure
automatically cross-browser
easily use Promises interface
Have a look at these examples and see if you prefer the jQuery AJAX methodologies:
Three simple examples
dynamic drop down box?
Chain AJAX Requests with jQuery Deferred

I can't send PHP variables to JavaScript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};

Ajax response problem

I'm handling a very (VERY) simple ajax error, but I cannot manage to fix it:
I have the following structure:
\manager\javascript\ajax.js
\manager\manager.jsp
\manager\test.jsp
In my ajax.js file I have a VERY simple function (without parameter, to make things easier)
function makeAjaxRequest() {
http.open('get', 'test.jsp');
http.onreadystatechange = processResponse();
http.send(null);
}
function processResponse() {
alert("Ready State: " + http.readyState);
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('ajaxResult').innerHTML = response;
}
}
And finally, my test.jsp file contains only:
<% out.print("JSP result");%>
In my manager.jsp I call the function but I receive only one "alert" from the processResponse with readyState = 1...
For sure there is something I'm missing in some step.
Could you help?
Thanks a lot.
Cheers,
Lucas.
EDIT
For sure in my ajax.js file there is also the function to get a xmlHttpObject.
This line is wrong
http.onreadystatechange = processResponse();
Remove the () to assign the actual function, not the result of the function.

Categories

Resources