The Angular $http.jsonp() function can only be executed one time

Upon the first response being successful (alert->done), any subsequent hits will result in an 'error' response.

I attempted to resolve this issue by adding some config parameters with 'cache: false', but it still only works the first time. Should I clear some cache/history or something else?

    $scope.add2 = function() {

    var config = {
        //url : 'http://www.***.pl/index.php/json/getallusers',
        cache: false,
        //type : 'POST',
        crossdomain: true,
        //callback: 'JSON_CALLBACK',
        //data: d,
        contentType: "application/json",
        dataType: "jsonp",
    };

            var r = Math.floor(Math.random() * 1000) + 4;
            var d = {user_type_id:0, user_venue_id:0, fname:r}; 
            var e = objToString(d);


//$http.jsonp('http://www.***.pl/index.php/json/adduserget?callback=JSON_CALLBACK&'+ e, config)

$http.jsonp('http://www.***.pl/index.php/json/adduserget?callback=JSON_CALLBACK&'+ e)
                .success(function(res){
                    console.log('res:' + res.user); 
                    alert('done');
                })
                .error(function(){  
                    console.log('error');       
                    alert('error');
                }); 
        };

This question can also be found on Stack Overflow regarding jsonp and post action in Ionic framework (angular.js)

I have noticed that the server response now includes 'angular.callbacks._0(' before the JSON data... could this be where the mistake lies?

A potential solution for my issue is as follows: I am dynamically retrieving the callback parameter which may vary (not limited to angular.callback_0, but could be: angular.callback_1, angular.callback_2, etc.) from the GET method on the server and inserting it before the response data using PHP:

<?php header('content-type: application/json;');
$json=json_encode($result);
echo $_GET['callback'].'('.$json.')';
?>

Answer №1

The issue arises because the URL is being cached in the browser, causing it to fetch from the cache on subsequent calls. To resolve this, I recommend adding a new dummy parameter within your URL containing the current Date.now(). This will ensure that each time you call the service, the URL will be unique due to the Date.now() component.

Implementation:

$http.jsonp('http://www.where2play.pl/index.php/json/adduserget?callback=JSON_CALLBACK&'+
 e + '&dummy='+ Date.now()) //<--this will add a new unique value every time

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

Searching in jquery not functioning as intended

Greetings! I'm in the process of creating a live search feature similar to what's demonstrated at this link. However, I've encountered a minor issue with this snippet of code: jQuery("#result").on("click",function(e){ var $clicked = $(e.ta ...

I am a beginner in the world of MEAN stack development. Recently, I attempted to save the data from my form submissions to a MongoDB database, but unfortunately, I have encountered

const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); const Schema = new mongoose.Schema({ username: St ...

End your Idp session and log out using passport-saml

Encountering a 400 bad request error when attempting to log out a user from the idp session. Despite successfully logging out the user from the application/passport session, they remain logged in to the idp session. The logout and callback endpoints are c ...

Displaying a loading template within an Angular component

While reviewing some code in AngularJS version 1.2.22, I came across the following snippet in the HTML: <div class="mainContent" ng-include="content"> </div> Within its corresponding controller, I found this: $scope.content = 'templates ...

Serialize a series of select boxes to optimize for AJAX POST requests

To better explain my issue, let's consider a simple example: Imagine I have a form that collects information about a user: <form action="#" method="post" id="myform"> <input type="text" name="fname" /> <input type="text" name= ...

Unable to integrate a new third-party script into a Next.js application

In my attempt to integrate the following script, I have tried adding it first to _document.js, then to app.js, and finally to a specific page. <Script src="https://anywebsite.ai/chatbot/chatbot.js"></Script> <Script id=" ...

Having trouble with the CSS `not` selector?

Below is the code snippet I experimented with XHTML <div> <span>Span1</span> <span>Span12</span> <span>Span13</span> </div> <div> <span>Span1</span> <span> ...

Angular Material - Text currently not displaying

As a student at university, I recently decided to delve into Angular for my academic purposes. To ease myself in, I simply copied some material from the official Angular webpage and pasted it into my editor after using bower to install angular-material ("b ...

Sending a parameter from a click event to a function

Struggling with a jQuery and AJAX issue all night. I am new to both and trying to implement something similar to this example. I have an edit button with the ID stored in a data-ID attribute. Here's an example of what my button looks like: <butto ...

Saving changes made in HTML is not supported when a checkbox is selected and the page is navigated in a React application using Bootstrap

In my array, there are multiple "question" elements with a similar structure like this: <><div className="row"><div className="col-12 col-md-9 col-lg-10 col-xl-10 col-xxl-10"><span>Question 1</span></div ...

Having trouble making an Ajax request in Rails3

I am currently in the process of refactoring my project by incorporating AJAX functionality. I have a link that triggers an action in a controller: = link_to("Please work", "show_recent_chart", :remote => true) This links to a specific controller acti ...

Exploring search results using dynamic multiple dropdown lists in PHP

Be sure to check out this interesting link: There are six drop down boxes available on the page. These include options for STATE, DISTRICT, LOCATION, MEDICINE, SPECIALTY, and GRADE. I successfully retrieved all the necessary data from the SQL database to ...

show a notification once the maximum number of checkboxes has been selected

I came across this code snippet from a previous question and I'm interested in making some modifications to it so that a message can be displayed after the limit is reached. Would adding a slideToggle to the .checkboxmsg within the function be the mos ...

How can I transform a JSON object into a series of nested form fields?

Can anyone suggest a reliable method for converting a JSON object to nested form fields? Let's consider the following JSON object: {'a':{'b':{'c':'1200'}}}, 'z':'foo', 'bar':{&apo ...

Eliminate FormData usage from the Next.JS backend application

Looking to replicate the steps outlined in this guide: https://medium.com/@_hanglucas/file-upload-in-next-js-app-router-13-4-6d24f2e3d00f for file uploads using Next.js, encountering an error with the line const formData = await req.formData();. The error ...

I'm having trouble pulling images from Firebase into my Vue application

Currently, I am experimenting with a Vue application that requires users to upload an image to Firebase. After the image is successfully uploaded, it should be displayed within an img tag in the template. The issue I am encountering is retrieving the uplo ...

Creating a dynamic route in Node Express allows for flexible path handling

Is there a way to incorporate a dynamic route or path using the Express package? The challenge is that the path is an ID passed by the client and we have no control over it. const express = require('express'); const dynamicPath = express(); dyn ...

Executing AJAX requests in an AngularJS application within a Cordova mobile app

After developing an app with Ionic Framework, AngularJS, and Cordova, I encountered a problem with AJAX calls to PHP files. While these calls work flawlessly in a browser, they fail within the app itself. Interestingly, the app is able to render internet p ...

Minimize the cyclomatic complexity of a TypeScript function

I have a typescript function that needs to be refactored to reduce the cyclometric complexity. I am considering implementing an inverted if statement as a solution, but it doesn't seem to make much of a difference. updateSort(s: Sort) { if (s.ac ...

Exploring the functionality of event.target.name.value

I've been struggling to make event.target.name.value work for an input field in my form. When I submit the form, the values appear as null and I have to click twice to get them. This is the code I've written: const [name, setName] = useState(& ...