Retrieve the key value pair from the AJAX response

I am trying to retrieve specific values from a cross domain call to a PHP script. The response I receive is as follows:

response=2&count=15&id=84546379&firstname=adsa&emailstatus=

My goal is to extract the values of 'response' and 'id', but I am unsure of how to accomplish this. Below is the code snippet I have been working with:

**

xhr.request({
                    url: "../promo_getstate2.php",
                    method: "POST",
                    data: {
                      email: emailaddress,
                      country: country,
                      lang: lang,
                      source: '1312_XMAS_dly'
                    }
                }, function(response){
                   getstate = response['response'];
                   regID = response['id'];
                   console.log(getstate)
                    console.log(regID)
})

However, I am not able to retrieve those values. Can someone guide me on how to achieve this?

The complete response received is:

" response=2&count=15&id=84546379&firstname=adsa&emailstatus="

**

Answer №1

To effectively handle the response, you can construct a params object containing all parameters:

function extractParams(data) {
    var parts = data.split("&");
    var result, params = [];
    for(var i = 0; i < parts.length; ++i) {
        result = parts[i].split("=");
        params[result[0]] = result[1];
    }
    return params;
}

var details = extractParams("response=3&count=20&id=98876543&name=john&status=")

You can then retrieve values like this:

details['response']; // 3

details['id']; // 98876543

Answer №2

Here is an example of code:

<Script language="javascript">
        var variables = GetRequest("response=2&count=15&id=84546379&firstname=adsa&emailstatus=");
        document.write(JSON.stringify(variables));

        function GetRequest(input) {
           var urlInput = "?"+input;//location.search;
           var requestedData = new Object();
           if (urlInput.indexOf("?") != -1) {
              var dataString = urlInput.substr(1);
              dataArray = dataString.split("&");
              for(var j = 0; j < dataArray.length; j ++) {
                 requestedData[dataArray[j].split("=")[0]]=unescape(dataArray[j].split("=")[1]);
              }
           }
           return requestedData;
        }
        </script>

You can then access the values. The JSON result will look like this:

{"response":"2","count":"15","id":"84546379","firstname":"adsa","emailstatus":""}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

creating a personalized tooltip for every item within a dynamically generated @html.dropdownfor control in mvc3

Currently, I am developing a web project using MVC 3 and Razor in C#. In my code, I have implemented @Html.DropDownListFor to dynamically display items. Now, I would like to add tooltips for each item displayed by @Html.DropDownListFor. Here is the relev ...

Transmitting the identification number of a post with the help of J

I am currently working on a while loop in PHP that fetches associated results from a query and displays them within a class identified by the user who created the post. My goal is to send the id of the class to PHP, similar to how I am sending the num vari ...

What could be causing the issue preventing me from updating my SQL database through AJAX?

$(document).ready(function(){ $('.button').click(function(){ var clickBtnValue = $(this).val(); var ajaxurl = 'functions/delivered.php', data = {'action': clickBtnValue}; $.post(ajaxurl, da ...

Tips on increasing video size upon visiting a website. HTML, JavaScript, and potentially jQuery can be used for video animation

Is there a way to create a video pop-up in the same window when visiting a website? I want the video to increase in height from 0 to a specific height and move slightly upwards. Are there JavaScript or jQuery functions that can achieve this effect? I wou ...

Which specific button is selected out of a variable number of buttons?

In my database, I store an autoincrement id along with the location and date of each trip. The piece of code below helps me display the results of my query. $mysqli = new mysqli("localhost", "root", "password", "trip"); $result = $mysqli->query("SELECT ...

Encountering Issues While Setting Up Magento on WAMP Server

An error occurred while attempting to process your request Issue with file: "C:\wamp\www\magento\app\code\core\Mage\SalesRule\sql\salesrule_setup\upgrade-1.6.0.0-1.6.0.1.php" - SQLSTATE[42000]: Syntax ...

"Utilizing jQuery to select elements for the purpose of preventing default

$('input[name=boxes], .item_add a ').on('click', function(e) { e.preventDefault(); //perform common actions } Is it possible to stop the default scrolling behavior when clicking on a link [.item add a], while still allowing the defa ...

How can jQuery incorporate additional selection criteria for a parent element?

How can I apply a specific criteria to a node that has been selected using jQuery? let objDIV = $("#selindividual").parent(); After retrieving the DIV, I want to target the following: button:contains(\"Submit\") If I had to do this in ...

Regular Expression designed specifically for detecting alternative clicks

When using ngpattern for validation, I have encountered an issue where my error message is displaying for a different reason than intended. The error message should only show if the field is empty or contains only special characters. <textarea name="ti ...

Sometimes, the `undefined` TypeError can unexpectedly pop up while making Ajax calls

Here is my issue with AJAX request and response: I have around 85 HTML pages that all use the same AJAX request. However, when working with these files, I sometimes encounter the following error. AJAX $(document).ready(function(){ localStorage.setIte ...

What is the best approach to execute the jquery script exclusively on mobile devices?

I want to modify this code so that it only functions on mobile devices and is disabled on computers. How can I achieve this? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <ul id="pri ...

The accessibility of private methods when using inheritance

class X { private function bar() { echo "X class success!\n"; } public function test() { echo get_class($this) . PHP_EOL; // Z class here var_dump($this) . PHP_EOL; // $this is object of Z class here ...

Execute JavaScript function after completion of CSS animation using jQuery

I'm working on an accordion feature that uses CSS animation to expand the clicked item. The expansion is triggered by li:target. However, I'm facing an issue where when clicking on an item, the scroll position doesn't align correctly with t ...

Using PHP in combination with Ajax for automatically performing an action when there is an update

My goal is to have the latest value entered in the database trigger the playing of a specific song. For instance, if someone on the other side of the world selects a song on their phone, that same song should automatically start playing on all devices with ...

Barba.js (Pjax.js) and the power of replacing the <head> tag

I have been using barba.js to smoothly transition between pages without having to reload the entire site. If you want to see an example, take a look here. Here is a snippet of code from the example: document.addEventListener("DOMContentLoaded", func ...

I'm confused why this code is functioning in JSFiddle but not on my HTML webpage

For the first time, I am encountering this issue. I am currently attempting to integrate this code into my application http://jsfiddle.net/TC6Gr/119/ My attempts include: Pasting all the jsfiddle code in a new page without my code, but it doesn't w ...

Error encountered while using Google Translate with XMLHttpRequest (Missing 'Access-Control-Allow-Origin' header)

Trying to access a page that utilizes Google Translate is resulting in the following error: XMLHttpRequest cannot load http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit. No 'Access-Control-Allow-Origin' heade ...

Automatically unset session variable 'unsetted' using a simple line of code

Why does the session information not get saved? When I reload the page, the session variable 'mucciusersess' disappears. What could be causing this issue? Thanks... I have a cookie on the client-side with a value like 'mucciuserid' se ...

Identify a specific sequence within a text box, and alternate between two radio buttons

Within my search field, I have integrated two radio buttons that allow the user to choose between a regular keyword search or a license plate search. By default, the "keyword" option is pre-selected. However, I am looking for a way to use jQuery to automa ...

Steps for Setting up PHPmailer with Ajax Form Submission

I'm facing an issue with a website server where I've set up this contact form (which works on other hosting) but seems to be malfunctioning on this new hosting. The Support Center advised me to use the phpmailer class, but I'm unsure of how ...