Jump to content

Multiple AJAX Calls to the Same Page


iwato

Recommended Posts

BACKGROUND:  I have now tried a number of ways to make two cURL calls within the same Javascript (jQuery) routine.  For each new way, I have discovered what I believe to be a reasonable explanation for my failure.  For my most recent attempt, however, a good explanation is not forthcoming.  To be sure, single AJAX calls with a single cURL call for each yield the desired results.  Simply I cannot seem to combine these results simultaneously on the same page.  The scenario given below, for example, returns the desired outcome for the second cURL call, but not the first.

JAVASCRIPT:

$.ajax({
    url: '.../VisitsSummary.php',
    method: 'GET',
    data: {methodName : '_get', methodName : '_getSumVisitsLengthPretty'},
    dataType: 'JSON',
    statusCode: {
        404: function() {
        alert( "Page not found" );
    }},
    success: function(visitsSummary_data) {
        console.log(visitsSummary_data);
        var tv = visitsSummary_data.nb_visits;
        var uv = visitsSummary_data.nb_uniq_visitors;
        var visits_per_unique_visitor = Math.round(tv/uv * 10)/10;				
        $('#so_total_visits').html(visitsSummary_data.nb_visits);
        $('#so_unique_visitors').html(visitsSummary_data.nb_uniq_visitors);
        $('#visits_per_visitor').html(visits_per_unique_visitor);
        $('#so_average_time_spent').html(visitsSummary_data.avg_time_on_site);
    }
});

PHP:

if (isset($_GET['methodName'])) {
    $method_name = $_GET['methodName'];
    if ($_GET['methodName'] == '_get') {
        $url = 'https://.../index.php?module=API&action=index&method=VisitsSummary.get&idSite=1&period=year&date=today&format=json&token_auth=&token_auth=...';
        $curl_request = curl_init();
        curl_setopt($curl_request, CURLOPT_URL, $url);
        curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, false);
        curl_exec($curl_request);
        if(curl_errno($curl_request)) {
            echo 'Curl error: ' . curl_error($curl_request);
        }
        curl_close($curl_request);
    }
    if ($_GET['methodName'] == '_getSumVisitsLengthPretty') {
        $url = 'https://.../index.php?module=API&action=index&method=VisitsSummary.getSumVisitsLengthPretty&idSite=1&period=year&date=today&format=json&token_auth=&token_auth=...';
        $curl_request = curl_init();
        curl_setopt($curl_request, CURLOPT_URL, $url);
        curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, false);
        curl_exec($curl_request);
        if(curl_errno($curl_request)) {
            echo 'Curl error: ' . curl_error($curl_request);
        }
        curl_close($curl_request);
    }
}

QUESTION:  Can you find anything wrong with the above strategy?  If so, what would you recommend to replace it?

Roddy

Edited by iwato
Link to comment
Share on other sites

data: {methodName : '_get', methodName : '_getSumVisitsLengthPretty'},

What do you expect to happen there?  If you want to send multiple values for something as an array, you need to put brackets after the name:

data: {"methodName[]": '_get', "methodName[]" : '_getSumVisitsLengthPretty'},

Assuming jQuery handles that correctly, then $_GET['methodName'] will be an array containing those 2 values.  Also, just so you're aware, the output of that page would be the response from each of those requests concatenated together.

Link to comment
Share on other sites

I am using $.ajax() in this case, not $.get(), and AJAX does not like the following:

{"methodName[]": '_get', "methodName[]" : '_getSumVisitsLengthPretty'}

It returns nothing.

In contrast, if I enter the following, AJAX produces good data for the object returned by the .get() method for the VisitsSummary class.  Nothing, of course, is returned for the .getSumVisitsLengthPretty() method.

{methodName: '_get'}
Link to comment
Share on other sites

I was trying to get too cute, obviously this is not going to do much:

var obj = {prop: 'val1', prop: 'val2'};

That creates an object, and object property names need to be unique.  This might work:

{prop: ['val1', 'val2']}

If you just make it an array in Javascript then maybe jQuery will handle that correctly and do what I was thinking earlier.  Otherwise, just use unique names for each property.

Link to comment
Share on other sites

Yes, the following appears to work: 

method: 'POST',
data: {methodName['_get','_getSumVisitsLengthPretty']},

I know this because it is confirmed by the FireFox Network tab.  The parameters sent are:

methodName[ ] = "_get"
methodName[ ] = "_getSumVisitsLengthPretty"

What is not working is the PHP file, and I am baffled -- even after having cut the file in half and run only one variable.  There is an internal server error, and I cannot find a mistake in the code.  The file permissions have been verified and are correct.

<?php
	ini_set('log_errors', 1);
	ini_set('error_log', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'error.log');
	ini_set('html_errors', 0);
	ini_set('display_errors', 0);
	error_reporting(E_ALL);
	if (isset($_POST['methodName'])) {
		$method_name = filter_var($_POST['methodName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
		if ($method_name[] == '_get') {
			$url = 'https://.../matomo/index.php?module=API&action=index&method=VisitsSummary.get&idSite=1&period=year&date=today&format=json&token_auth=&token_auth=...';
			$curl_request = curl_init();
			curl_setopt($curl_request, CURLOPT_URL, $url);
			curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, false);
			curl_exec($curl_request);
			if(curl_errno($curl_request)) {
				echo 'Curl error: ' . curl_error($curl_request);
			}
			curl_close($curl_request);
		}
	}
?>

In addition to the above problem I do not understand how to combine the two resulting JSON objects into a single JSON object that can be read by the AJAX success function.  Even if I were to set the parameter value of the curl_setopt( ) from false to true and assign the return value of each curl_exec() function to a variable, how would I combine the resulting two values?  Is it a simple concatenation of two strings?  Must I rebuild the two JSON strings/objects from the two values?  Is there a PHP function that handles this sort of thing automatically?

Roddy

Link to comment
Share on other sites

if ($method_name[] == '_get') {

That's your syntax error.  You really need to set this up so it's writing to an error log.  Using commands to set those options at runtime instead of setting them in the config file means that if you have a syntax error, it will not use any of your error settings because it never even starts executing the code to set those options.

$method_name = filter_var($_POST['methodName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);

$_POST['methodName'] is an array, not a string.  You're probably setting $method_name to the string "Array" since filter_var will convert values to strings before sanitizing.

Even if I were to set the parameter value of the curl_setopt( ) from false to true and assign the return value of each curl_exec() function to a variable

That's not an "even if", that's a requirement.  Otherwise you're outputting one block of text after the other with no way to know where one ends and the other starts.

how would I combine the resulting two values?

The most obvious way is probably to return an array or object with all of the values in it.

Is it a simple concatenation of two strings?

If you don't care about separating the two, then yeah you can just dump everything out.

Is there a PHP function that handles this sort of thing automatically?

json_encode

  • Thanks 1
Link to comment
Share on other sites

OK. I managed the AJAX and response, but for some reason I am unable to read properly what was returned.
 
Returned Format:

Array [ "{"nb_uniq_visitors":49,"nb_users":0…", "{"value":"17 hours 23 min"}" ]

Attempted, but Failed Read Format:

$.ajax({
    url: '.../VisitsSummary.php',
    method: 'GET',
    data: {methodName : '_get', methodName : '_getSumVisitsLengthPretty'},
    dataType: 'JSON',
    statusCode: {
        404: function() {
        alert( "Page not found" );
    }},
    success: function(visitsSummary) {
        console.log(visitsSummary);
        var tv = visitsSummary[0].nb_visits;
        var uv = visitsSummary[0].nb_uniq_visitors;
        var visits_per_unique_visitor = Math.round(tv/uv * 10)/10;				
        $('#so_total_visits').html(visitsSummary[0].nb_visits);
        $('#so_unique_visitors').html(visitsSummary[0].nb_uniq_visitors);
        $('#visits_per_visitor').html(visits_per_unique_visitor);
        $('#so_average_time_spent').html(visitsSummary[0].avg_time_on_site);
    }
});

There were no messages.  Simply nothing appeared.  Any suggestions?

Roddy

Link to comment
Share on other sites

This is not proper JSON, the quotation marks are not properly matched and the word "Array" indicates that you're trying to cast an array to a string. What is the PHP code that generated this output?

Link to comment
Share on other sites

	if (isset($_POST['methodName'])) {	
		$result = [];
		foreach ($_POST['methodName'] as $method) {
			$method = filter_var($method, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
			if ($method == '_get') {
				$url = 'https://.../matomo/index.php?module=API&action=index&method=VisitsSummary.get&idSite=1&period=year&date=today&format=json&token_auth=&token_auth=...';
				$curl_request = curl_init();
				curl_setopt($curl_request, CURLOPT_URL, $url);
				curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
				$result[] = curl_exec($curl_request);
				if(curl_errno($curl_request)) {
					echo 'Curl error: ' . curl_error($curl_request);
				}
				curl_close($curl_request);
			}
			if ($method == '_getSumVisitsLengthPretty') {
				$url = 'https://.../matomo/index.php?module=API&action=index&method=VisitsSummary.getSumVisitsLengthPretty&idSite=1&period=year&date=today&format=json&token_auth=&token_auth=...';
				$curl_request = curl_init();
				curl_setopt($curl_request, CURLOPT_URL, $url);
				curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
				$result[] = curl_exec($curl_request);
				if(curl_errno($curl_request)) {
					echo 'Curl error: ' . curl_error($curl_request);
				}
				curl_close($curl_request);
			}				
		}
		echo json_encode($result);
	}

Roddy

Link to comment
Share on other sites

You might want to take a look at the contents of the $result variable. If the content you're getting from the curl requests is already JSON encoded you actually have to decode them before adding them to the array.

  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...