0

I want to run an Ajax query to get the "Datum" from the response "TesterID". Then I want to run the second Ajax with the previously received "Datum" to update with this value on another page, a DB entry.

Here is the code which doesn't work.

<script>

/* Funktionen um Startzeiten für Zyklen aus DB.TesterCycleCount zu erhalten bzw. für Test und Stunden, das aktuelle Datum gerundet auf 30 Minuten */ 
$(document).ready(function(){

var TesterID = "<?php echo $_GET['TesterID']; ?>"; /* value der Tester erhalten */ 


        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID_Testende.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */


                var CID = response['CID'];
                var Datum = response['Datum'];



            },
             error: function(jqxhtt, status, exception) {
         alert('Exception:', exception)

            }
        }




        var TestaufstellungID = "<?php echo $_GET['TestaufstellungID']; ?>";
         $.ajax({ /* AJAX aufrufen */
            url: 'ma_TestendeSQL.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {Testaufstellung:TestaufstellungID, Datum: Datum}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(data){ /* Die zurückgegebenene Daten erhalten */


                 alert('Successfully called');
     },
     error: function(jqxhr, status, exception) {
         alert('Exception:', exception)

            }
        }


        });


</script>

This is the second PHP page, ma_TestendeSQL.php, which doesn't update.

<?php
    $cinfo = array(
        "Database" => $database,
        "UID" => $username,
        "PWD" => $password
    );
    $conn = sqlsrv_connect($server, $cinfo);

    $TestaufstellungID = $_GET['TestaufstellungID'];
    $Datum = $_GET['Datum'];
    $Testdatum = date('Y-d-m');

                    $stop = $conn->prepare("WITH UpdateTestende AS (
      SELECT TOP 1  * from DB.dbo.Testergebnisse 
      WHERE TestaufstellungID = $TestaufstellungID
      ORDER BY TestergebnisID DESC 
    )

    update UpdateTestende 
    set Testende = '$Datum',
    Datum = '$Testdatum'");








        header('Content-type: application/json');

    ?>

The first Ajax works fine with the PHP page ma_get-TesterID_Testende.php. I tested it already alone, but when I add the second Ajax try to update, the code I posted above doesn't work.

So the question: is it possible to run two Ajax like this?

Thanks.

Edit: AJAX Call is empty or is not starting. Further invstigation: The Ajax alert me the error part with empty exception and dont alert me the success part. So it doesnt go to the page ma_get-TesterID_Testende.php or it doesnt return back the Datum . Could be not enabled Cross-Site-Scripting be the Problem?

But in another Page is a similiar Ajax Call working fine.

$(document).ready(function(){

var TesterID = "<?php echo $_GET['TesterID']; ?>"; /* value der Tester erhalten */ 

        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var len = response.length;

                $("#Teststart").empty(); /* Die erhaltenden Daten werden bei der ID angezeigt */
                for( var i = 0; i<len; i++){
                    var CID = response[i]['CID'];
                    var Datum = response[i]['Datum'];

                    $("#Teststart").append("<option value='"+Datum+"'>"+Datum+"</option>");

                }
            }
        });


    $("#TesterID").change(function(){ /* Wenn du änderst und vom Select Feld auswählst */
        var TesterID = $(this).val(); /* value der Tester erhalten */ 

        $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID.php',
            type: 'get', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var len = response.length;

                $("#Teststart").empty(); /* Die erhaltenden Daten werden bei der ID angezeigt */
                for( var i = 0; i<len; i++){
                    var CID = response[i]['CID'];
                    var Datum = response[i]['Datum'];

                    $("#Teststart").append("<option value='"+Datum+"'>"+Datum+"</option>");

                }
            }
        });
    });

});

In this example the Ajax Call starts when i change the value from a Dropdown selection Form. Is there a difference?

How this Ajax should work i try to explain in my other question step by step, how it my application should be execute.

Update SQL Query with populated variables from AJAX functions over multiple PHP Pages

Edit 2: JQuery Version: https://code.jquery.com/jquery-3.4.1.js"

hashed_name
  • 553
  • 6
  • 21
Daniel
  • 668
  • 4
  • 17
  • 3
    That's a lot of code for us to guess about. Can you elaborate on what "doesn't work" means in this case? When you debug, where/how specifically does this fail? – David May 16 '19 at 12:38
  • 2
    “Doesn’t work” doesn’t work as a problem description, and if you are saying that as a developer, it mostly means that _you_ are “not working.” Please go read [ask], and then give us a proper description of the problem. And if you are relying solely on your code to explain what is going on to people here, those comments should at least be in English as well. – 04FS May 16 '19 at 12:39
  • 1
    is it possible to delete option success in the second and third $.ajax? i dont need the echo json_encode variables from the other php page. – Daniel May 16 '19 at 12:40
  • 4
    If you can avoid making a second/third request to the same server for a single operation, that'd be a good thing. Try to make all your server logic happen in one request. – James May 16 '19 at 12:41
  • @David and rest the SQL Server Query on my other Page dont Update with the Ajax called values. So my question is only in this post is it possible to run 2 ajax query like this? – Daniel May 16 '19 at 12:46
  • 1
    @Daniel: Yes, it's possible to execute multiple AJAX requests. Websites do that all the time. If you have something specific that is failing in a specific way then we may be able to help with that, if you can provide details about what's failing and how it's failing. "the SQL query on my other page doesn't update" isn't really something we can help with. When you debug, does the AJAX request in question contain the values you expect? What is the server's response? What is the query being executed? What are the values used in that query? What is the result? Etc. – David May 16 '19 at 12:48
  • ok i startet to try with debug i added alert in success and error and to the end of the page header('Content-type: application/json'); error is: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data – Daniel May 16 '19 at 13:06
  • @David i added the php page with the sql code which i try to combine with the second ajax statement. – Daniel May 16 '19 at 13:13
  • You're coding practice is horrible. You never test `if(isset($_GET['yourGetPropHere'])){}`. You also don't use a prepared statement correctly. You never `->execute();` the statement. https://www.php.net/manual/en/mysqli.prepare.php – StackSlave May 20 '19 at 02:23
  • 1
    One of the probable reasons for the down votes is you never elaborated on "doesn't work". Be more specific, what isn't happening that should, what is happening that shouldn't, what errors are you getting? It would also help of you made your code more readable without masses of white space and using consistent indenting – Jon P May 20 '19 at 04:04
  • i cant enclose the error, always the same: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data. i tryed already the answers, still same error. – Daniel May 21 '19 at 09:15
  • my new question to break down the problem and encapsulate it https://stackoverflow.com/questions/56239790/update-sql-query-with-populated-variables-from-ajax-functions-over-multiple-php – Daniel May 21 '19 at 18:31
  • @Daniel you just need to add `async: true` after `dataType: 'json'` for asynchronous [Read](https://stackoverflow.com/questions/1478295/what-does-async-false-do-in-jquery-ajax). – Jaydeep Mor May 22 '19 at 08:59
  • @JaydeepMor its the same like `await` – Daniel May 24 '19 at 04:30
  • I did an Edit with further Infos. – Daniel May 24 '19 at 05:43

5 Answers5

1

A couple of issues with the original code:

A. First ajax must complete before starting second ajax

Your second ajax call needs the value of Datum which is returned by the first ajax call. Currently the second ajax will start immediately after sending the first ajax, before it has returned Datum. So we need to wait for the first ajax to return Datum before we can use it as an input for the second ajax.

The easy way to do this is with the async/await feature of ECMA2017 (docs here). This allows javascript to run asynchronously and wait for something to complete before we proceed.

To do this, we need to first declare the enclosing function as async (see //1. comments in code below):

$(document).ready(async function(){

Then we add await in front of the first $.(ajax) call (see //3. comments in code below):

 await $.ajax({ /* AJAX aufrufen */

Together, the javascript engine will pause the code at the first ajax call until it returns the Datum value. Then it will continue as normal.

B. Datum needs to be at top level of enclosing function

As written, the variable Datum only exists within the anonymous function attributed to "success" in the first ajax call. So it is not available to the second ajax call ("Datum is not defined").

You can fix this by declaring Datum as global (outside of the $.(ready) {}), or better, you can keep it within your $.(ready) {} by declaring it at the outermost enclosing brackets (see //2. comments in code below).

Lastly, you should replace var Datum = response['Datum']; with Datum = response['Datum'];. (see //4. comment in code below).

/* Funktionen um Startzeiten für Zyklen aus DB.TesterCycleCount zu erhalten bzw. für Test und Stunden, das aktuelle Datum gerundet auf 30 Minuten */ 

// 1. ADD 'ASYNC' IN FRONT OF FUNCTION

$(document).ready(async function(){

// 2. DECLARE 'DATUM' AT TOP

var Datum;
var TesterID = "<?php echo $_GET['TesterID']; ?>"; /* value der Tester erhalten */ 

        // 3. ADD AWAIT IN FRONT OF FIRST AJAX CALL

        await $.ajax({ /* AJAX aufrufen */
            url: 'ma_get-TesterID_Testende.php',
            type: 'GET', /* Methode zum übertragen der Daten */
            data: {TesterID:TesterID}, /* Daten zu übermitteln */
            dataType: 'json',
            success:function(response){ /* Die zurückgegebenene Daten erhalten */

                var CID = response['CID'];

                // 4. REMOVE VAR IN FRONT OF DATUM

                Datum = response['Datum'];

            },
             error: function(jqxhtt, status, exception) {
             console.log(exception);
         alert('Exception:', exception)

            }
        });




    var TestaufstellungID = "<?php echo $_GET['TestaufstellungID']; ?>";
    $.ajax({ /* AJAX aufrufen */
        url: 'ma_TestendeSQL.php',
        type: 'get', /* Methode zum übertragen der Daten */
        data: {Testaufstellung:TestaufstellungID, Datum: Datum}, /* Daten zu übermitteln */
        dataType: 'json',
        success:function(data){ /* Die zurückgegebenene Daten erhalten */


            alert('Successfully called Datum='.Datum);
        },
        error: function(jqxhr, status, exception) {
            alert('Exception:', exception)

        }
    });

});
chatnoir
  • 2,185
  • 1
  • 15
  • 17
  • i still get the error on my ma:Testende.php Page SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data – Daniel May 21 '19 at 08:53
  • That sounds like the JSON data you're submitting is not valid JSON. Can you put a console.log() somewhere to print out JSON data? Then you can compare at https://jsonformatter.curiousconcept.com to see where the formatting error is and correct it before sending it. – chatnoir May 21 '19 at 09:17
  • can u help me where i can place the console.log(), seems to dont work, when i placed in in '; doenst work too – Daniel May 21 '19 at 09:24
  • You can put it after `var TestaufstellungId = ... ` just before the second `ajax` call. Then look in your browser console (you need to enable Developer Tools to see the console (that's where it will send the log contents to). Check your browser details on how to do that). – chatnoir May 21 '19 at 09:39
  • ok i try chatnoir, dunno if somehtning else is wrong. i removed complete the javascript code with ajax and it still says. SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data – Daniel May 21 '19 at 09:43
  • says just Content Security Policy: Die Einstellungen der Seite haben das Laden einer Ressource auf http://1xx.xxx.xx.xxx/favicon.ico blockiert ("default-src"). – Daniel May 21 '19 at 09:54
  • That doesn't sound like it's the same problem. Don't know German, but that sounds like some other part of your page trying to load `favicon.ico` from another website, and it sounds like that website is blocking it because your page is not from that website. – chatnoir May 21 '19 at 10:05
  • favicon.ico is on the xampp htdocs folder. but i use the same head in my other php pages and never had issues with the javascript code there. – Daniel May 21 '19 at 10:10
  • i use firefox. in chrome it show me nothing, but the sql quere didnt update in the db. – Daniel May 21 '19 at 10:38
  • Your question was "Possible run multiple ajax this way?" and the answer is trying to address that. Updating the DB etc. is another thing altogether. – chatnoir May 21 '19 at 11:11
  • yes ok i knew now its possible to run two ajax, but its still didnt do what i want to(better its do nothing, shows only the log i postet). the ma_TestendeSQL.php sql code is working with ajax update i told that already. i use this code in other pages with onchange functions. But in this case i need to work when i stop the test with a button on other page. i cant post everthing here. Dunno rly what do you need for further debug the error i got? – Daniel May 21 '19 at 11:50
  • It's best to break down your problems and only ask about one problem for each question. For each question, supply a [Minimal, Reproducible Example](https://stackoverflow.com/help/reprex). This way you're more likely to get answers to your problems. – chatnoir May 21 '19 at 12:02
  • when i remove this header('Content-type: application/json'); than the console says nothing. what should i ask? – Daniel May 21 '19 at 12:16
  • and this is already a minimal example, no chance to break it down. i will ask now a new question with all steps i do and the result i want. iwill use your edited code to use multiple ajax. – Daniel May 21 '19 at 12:22
  • @ chatnoir my new question to break down the problem and encapsulate it https://stackoverflow.com/questions/56239790/update-sql-query-with-populated-variables-from-ajax-functions-over-multiple-php – Daniel May 21 '19 at 18:32
  • I did an Edit with further Infos. – Daniel May 24 '19 at 05:43
0

Ajax calls are not synchronous and using async:false would also not be preferred solution as it generate warnings. The simplest solution here would to create 2 methods. One to get the datum and second to update database with datum. Call the second method in the success of first method. So it would be like

  $.ajax({ 

        url: 'ma_get-TesterID_Testende.php',
        type: 'get', 
        data: {TesterID:TesterID}, 
        dataType: 'json',
        success:function(response){ 


            var CID = response['CID'];
            var Datum = response['Datum'];

            SecondMethod(Datum);


        },
  • i still get the error on my ma:Testende.php Page SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data – Daniel May 21 '19 at 08:53
  • try updating data: JSON.stringify(your data) and if that doesn't work, then can you please share your code? – DotNet Coder May 23 '19 at 03:14
  • still nothing happens, there is no more code. only the script which load on call from a previous page. for further Information look at this question from me. https://stackoverflow.com/questions/56239790/update-sql-query-with-populated-variables-from-ajax-functions-over-multiple-php – Daniel May 24 '19 at 04:34
  • I did an Edit with further Infos. – Daniel May 24 '19 at 05:44
0

First, you should know that you should separate your JavaScript from your HTML or PHP pages that generate HTML, so the JavaScript can be cached. You should also do this with your CSS, so it's cached, for faster page loads. Here's what your code should probably look like:

//<![CDATA[
/* external.js */
$(function(){
var serialGet = location.search.replace(/^\?/, '').split('&');
if(serialGet.length > 1){
  for(var i=0,a,v,testerId,testaufstellungID,l=serialGet.length; i<l; i++){
    a = serialGet[i].split('='); v = a[1].trim();
    if(a[0].match(/TesterID/i) && v !== ''){
      testerId = v;
    }
    else if(a[0].match(/TestaufstellungID/i) && v !== ''){
      testaufstellungID = v;
    }
  }
  if(testerId && testaufstellungID){
    $.ajax({
      url:'ma_get-TesterID_Testende.php',
      data:{testerID:testerID},
      dataType:'json',
      success:function(response){
        var cid = response.cid, datum = response.datum;
        if(cid === undefined || datum === undefined){
          return;
        }
        // use cid now if needed
        $.ajax({
          url:'ma_TestendeSQL.php',
          data:{testaufstellung:testaufstellungID, datum:datum},
          dataType:'json',
          success:function(data){
            if(data.worked){
              console.log(data);
            }
          }
        });
      }
    });
  }  
}
}); // end load
//]]>
/* external.css */
*{
  box-sizing:border-box; padding:0; margin:0;
}
html,body{
  width:100%; height:100%;
}
body{
  background:#ccc;
}
#test{
  padding:5px 7px; text-align:center;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
    <title>Test Template</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div id='test'>This would be the page that takes your $_GET URL</div>
</body>
</html>

Of course, you should keep a separate and secure copy to you database connection.

restricted/connect.php may look like:

<?php /* restricted/connect.php */
function https(){ // force https
  if(!isset($_SERVER['HTTPS'])){
    header("LOCATION:https://{$_SERVER['SERVER_NAME']}{$_SERVER['PHP_SELF']}"); die;
  }
}
function connect(){ // database connect - change strings as required below
  return new mysqli('host', 'username', 'password', 'database');
}
?>

Now, ma_get-TesterID_Testende.php may look something like:

<?php /* ma_get-TesterID_Testende.php */
require_once 'restricted/connect.php';
// https(); - use if https
if(isset($_GET['testerID'])){
  $db = connect();
  if($db->connect_error)die;
  if($stmt = $db->prepare('SELECT cid,datum FROM some_table WHERE testerID=?')){
    $stmt->bind_param('s', $_GET['testerID']); $stmt->execute();
    $stmt->bind_result($cid, $datum); $c = new StdClass;
    if($stmt->fetch()){ // single result set no loop needed
      $c->cid = $cid; $c->datum = $datum;
    }
    $stmt->free();
    echo json_encode($c);
  }
  $db->close();
}
?>

ma_TestendeSQL.php may look like:

<?php /* ma_get-TesterID_Testende.php */
date_default_timezone_set('America/Vancouver'); require_once 'restricted/connect.php';
// https(); - use if https
if(isset($_GET['testaufstellungID'], $_GET['datum'])){
  $db = connect();
  if($db->connect_error)die;
  if($stmt = $db->prepare('UPDATE updateTestende SET testende=?, datum=? WHERE testaufstellungID=? ORDER BY testergebnisID DESC LIMIT 1')){
    $stmt->bind_param('sss', $_GET['datum'], date('Y-d-m'), $_GET['testaufstellungID']); $stmt->execute(); $c = new StdClass;
    if($db->affected_rows){
      $c->worked = true;
    }
    echo json_encode($c);
  }
  $db->close();
}
?>

Keep in mind that AJAX is Asynchronous, so if a result is dependent on another you should nest your calls, or use Promises (although they don't work in IE). Also, I have no idea what you were trying to achieve with your last AJAX call, so I was just guessing, while showing the process.

StackSlave
  • 10,613
  • 2
  • 18
  • 35
0

There are 2 ways to do this

WAY 1: use 'await' for the first ajax. this is let your second ajax to wait until the first ajax to complete.

    await $.ajax({
    url: 'ma_get-TesterID_Testende.php',
    type: 'get',
    data: {TesterID:TesterID},
    dataType: 'json',
    success:function(response){ /* Die zurückgegebenene Daten erhalten */

    },
     error: function(jqxhtt, status, exception) {
    }
}
$.ajax({
    url: 'ma_TestendeSQL.php',
    type: 'get',
    data: {Testaufstellung:TestaufstellungID, Datum: Datum},
    dataType: 'json',
    success:function(data){

    },
    error: function(jqxhr, status, exception) {
    }
}

WAY 2:

you can put the second ajax in the 'complete' or 'success' method of the first ajax

$.ajax({
    url: 'ma_get-TesterID_Testende.php',
    type: 'get',
    data: {TesterID:TesterID},
    dataType: 'json',
    success:function(response){
        $.ajax({
            url: 'ma_TestendeSQL.php',
            type: 'get',
            data: {Testaufstellung:TestaufstellungID, Datum: Datum},
            dataType: 'json',
            success:function(data){

            },
            error: function(jqxhr, status, exception) {
            }
        }
    },
     error: function(jqxhtt, status, exception) {
    }
}
Bhaumik Belani
  • 652
  • 1
  • 8
  • 19
0

I don't know what you have to achieve. It is an only example I have not run the code but I think it will work properly is as under:

$(document).ready(function() {
    $.ajaxSetup(
        {
         cache : false, 
         crossDomain: true, 
         async : false, 
         type : 'POST', 
         dataType : 'json'
        });

    function FirstAjax($url, $value){
        var def = new $.Deferred();
        var ret_data;

        $.post($url, {type : 1, value : { $value}}, function(data){
            //Do things with Data
            //or
            ret_dat=data;
        }, "json");

        return ret_data;
    }


    var abc = FirstAjax("site address", "data_values");
    var def = FirstAjax("site address", "data_values");
});
Vineet1982
  • 7,730
  • 4
  • 32
  • 67