Ajax returning undefined

1

I placed an else in my function in php and it is falling on the else, but I have parameters to get from the url.

I have the following code in php:

$utm_source = $_REQUEST['utm_source'];
$utm_campaign = $_REQUEST['utm_campaign'];
$utm_medium = $_REQUEST['utm_medium'];
if($utm_source != '' || $utm_campaign != '' || $utm_medium != '')
{
    $x['x'] = $utm_source;
    $x['y'] = $utm_campaign;
    $x['k'] = $utm_medium;
    echo json_encode($x);
}

When I directly access the file through the browser with the parameters? utm_source = xesquedele & utm_medium = site & utm_campaign = partners it returns me:

{"x":"xesquedele","y":"parceiros","k":"site"}

But when I try to return this to an ajax it does not return anything or undefined.

$j(document).ready(function()
{
    $j.ajax({
        url: '/inchoo_quoteitemrule/ajax/sessiondesconto',
        method: "POST",
        success: function(retorno)
        {
            console.log(retorno);
            alert('utm_medium: '+retorno['k']+' utm_source: '+retorno['x']+' utm_campaign: '+retorno['y']);
        }
    });
});

Return of ajax: utm_medium: undefined utm_source: undefined utm_campaign: undefined

    
asked by anonymous 31.01.2018 / 12:48

1 answer

1

The superglobal $_REQUEST returns information from the superglobals $_GET , $_POST and $_COOKIE . In your first example you are sending this data via GET , that is, through the url. And everything worked fine as the data was being sent. Already in your second example you are not populating any of the 3 superglobals. Your ajax code will work if you send it like this

$j(document).ready(function() {
    $j.ajax({
        url: '/inchoo_quoteitemrule/ajax/sessiondesconto',
        method: "POST",
        data:{utm_source: 'xesquedele',utm_medium:'site',utm_campaign:'parceiros'},
        success: function(retorno) {
            console.log(retorno);
        }
    });
});

See that I am sending the data in the AJAX request via post. and the data returns perfectly.

Remembering that your alert is not working because you are returning a string from your server. You need to transform this string into a Javascript object. For this you can use the jQuery.parseJSON() function. It would look something like:

$j(document).ready(function() {
    $j.ajax({
        url: '/inchoo_quoteitemrule/ajax/sessiondesconto',
        method: "POST",
        data:{utm_source: 'xesquedele',utm_medium:'site',utm_campaign:'parceiros'},
        success: function(retorno) {
            var obj = jQuery.parseJSON(retorno);
            console.log(retorno);
            alert('utm_medium: '+obj.k+' utm_source: '+obj.x+' utm_campaign: '+obj.y);
        }
    });
});
    
31.01.2018 / 13:09