.ajax posts and gets response on local server, no response on web host - ajax

I'm using an ajax call to do a minor calculation then return the value and display it in the page same page where the form is submitted. In Firebug it says it calls the function, however doesn't get a response. (I have a similar form that writes to a database that works fine, seemingly because it doesn't need a response - firebug says it fails to get a response on that script as well.) The odd thing is that I wrote this on my local server before implementing it on the site and everything worked as planned. I'm using Code Igniter on both the local server and the web server, but I don't know if that has something to do with it. Anyways, any help would be great. I'm marginally new so this is kinda outta my realm at this moment.
Thanks
EDIT: .js
$(document).ready(function() {
$('#submit').click(function(){
var formdata = {
years: $('#years').val(),
rate: $('#rate').val(),
principle: $('#principle').val(),
periods: $('#periods').val(),
continuous: $('#continuous').val()
}
$.ajax({
url: "http://localhost:8888/CodeIgniter_1.7.2/index.php/timevalueshow/submit",
type: 'POST',
data: formdata,
success: function(data){
$('#replace').replaceWith('<p>'+data+'</p>');
}
});
return false;
});
});
php submit function
function submit(){
$years = $this->input->post('years');
$rate = $this->input->post('rate');
$principle = $this->input->post('principle');
$periods = $this->input->post('periods');
$isCont = $this->input->post('continuous');
$params = array(
'years' => $years,
'rate' => $rate,
'principle' => $principle,
'periods' => $periods,
'isCont' => $isCont
);
$this->load->library('timevalue', $params);
return $this->timevalue->FVFactor();
}

Could it be that the request is being made cross-domain? Remember that mydomain.com is considered a different domain to www.mydomain.com.
I ran into a similar situation recently. I requested a page from mydomain.com which made an AJAX request to a script on www.mydomain.com. The request was not made because it was considered cross-domain. It had the same symptoms that you describe. In Firebug and Chrome Developer Console I saw an empty response and no error message.
The problem is that CodeIgniter generates absolute URLs based on the $config['base_url'] setting. If you access the site using a different domain name to what is configured in $config['base_url'] you can run into this type of problem.

This works on the dev and not on the server because you are calling localhost!
// this will have the client call itself on this particular page (wont work)
url: "http://localhost:8888/CodeIgniter_1.7.2/index.php/timevalueshow/submit",
The above code should be just:
// this is relative to the document ROOT, will work on server but not on dev!
// you can set it relative to the calling page using ../ as needed
url: "/index.php/timevalueshow/submit",

Related

I can't seem to generate content for dynamic content load

I am using wordpress and php along with ajax to create a random loading of customer reviews on our main page
function loadContent() {
$.ajax({
type: "GET",
url: 'http://skillsetsonline.ssosv.com/contentLoader.php',
data: {
company: 1
},
success: function(data) {
alert(data);
var currReview = document.getElementById('reviewRand');
currReview.innerHTML = data;
}
});
}
setTimeout(loadContent, 10000); // milliseconds, so 10 seconds = 10000ms
<div id="reviewRand" class="elementToFadeInAndOut" style="font-color:#FFF;">Hi how are you</div>
I pasted the ajax command in from a stackoverflow posting that was an accepted answer but may not have it exactly right this does not include the fading CSS code I use but that is working I just need to change the content.
Currently "Hi how are you" fades in every 10 seconds. One thing I have not learned about yet with this ajax command is the
data:{company:1}
I know it simply passes &company=1 to the GET URL but in my case I do not need to send anything and since it should not break anything if it is sent I left it alone not sure if
data:{}
would work and be cleaner
I have verified that the url used does get a random review
formatted like this
I love this program.blah blah.<br>
A USER<br>
A location<br>
June 2016<br>
Each line is formatted in CSS via a class tag
Any ideas would be greatly appreciated
Since the domain you're making the AJAX request to is on a different domain/origin, what you're running in to is a CORS issue. By default, the client will not allow you to update the page with data from an AJAX request that is served on a different origin than the site where the request originated. You can read about making CORS changes here https://enable-cors.org/
A common way around this is to serve the response via JSONP. You can do this in your script at http://skillsetsonline.ssosv.com/contentLoader.php if you have access to change that file. There are also third-party sites that will request that URL for you and create a proxy that serves the response via JSONP, then you can use it on your website.
Here's an example utilizing a JSONP proxy on https://crossorigin.me
function loadContent() {
$.ajax({
type: "GET",
url: 'https://crossorigin.me/http://skillsetsonline.ssosv.com/contentLoader.php',
success: function(data) {
var currReview = document.getElementById('reviewRand');
currReview.classList.add('ready');
currReview.innerHTML = data;
}
});
}
setTimeout(loadContent, 0); /* changed this for the demo */
#reviewRand:not(.ready) {
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reviewRand"><img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif"></div>

Single Cross Domain AJAX Request needed

Trying to implement sending sms features in my ecommerce store.
I use service called esteria.lv and they provided me with API link that looks like this: http://api1.esteria.lv/send?api-key=api_key&sender=example.com&number=11223344&text=message
If the message is sent then it outputs message ID, now it outputs error number 3(unable to authenticate).
To get it working with my ecommerce store, I found this resource: http://www.ajax-cross-origin.com/examples/cross-origin.htm, and made this code:
$(function() {
$( '#btn' ).click(function(){
$.ajax({
crossOrigin: true,
url: 'http://api1.esteria.lv/send?api-key=api_key&sender=example.com&number=11223344&text=message',
success: function(data) {
$( '#test' ).html(data);
}
});
});
});
It works, but the problem is, it sends 6 messages (requests) instead of just one. I need just 1 request and one sent sms. Anyone have any suggestions?
To answer your comment, this is what you should do.
In your javascript you should have an ajax call to your server
// collect sms data
$.ajax({
url: 'yourserver/handlesms',
method: 'post',
data: {
sender: 'email#mail.com',
number: '1234567',
message: 'Test message'
}
}).then(function (data) {
alert("Message sent!");
});
In your server you should have an handler for sending the sms, something like (I don't know what's your platform, I'll just write a really simple php example)
$data = $_POST;
$apiKey = '12345643223213ds';
$endpoint = 'http://api1.esteria.lv/send';
// Create new curl request
$ch = curl_init($endpoint);
// curl settings, add your data, api key etc...
$result = curl_exec($ch);
// Result will contain the response from your api call
// Then you can send a result back to your client (js)
echo json_encode(['status' => 'Message sent!']);
This is just an example, the server code depends on your platform.
In this case you don't have any cross origin request (all the js request will be sent to your server, that then is in charge of contacting your sms provider and send the messages.
The problem that's executed 6 times I think depends on something else but it's hard to say without looking at the rest of the code (you can try debugging the click event on #btn and see how many times is executed every time you click on the button.

caching issue with jQuery/AJAX

I am getting data through $.ajax multiple times. However the data is not getting refreshed in every call. Rather I am getting the same data in every call to $.ajax. The code was working properly at my home.
However in below code if I substitute console.log("success "); with console.log("success "+data); and observe in chrome console, then the code works fine. I suspect its a caching issue, but can figure it out.
function getDataJSON()
{
originalData="";
new Date().toString();
$.ajax({
url: 'data.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
success: function(data)
{
console.log("success ");
...
...
Thanks
you can set cache Cache. by default it will set to cache=true.
from DOCS
If set to false, it will force requested pages not to be cached by the
browser. Note: Setting cache to false will only work correctly with
HEAD and GET requests. It works by appending "_={timestamp}" to the
GET parameters. The parameter is not needed for other types of
requests, except in IE8 when a POST is made to a URL that has already
been requested by a GET.
$.ajax({
url:'url',
cache:false,
.....
})
Like #Ravi said cache priperty is you're frined.
You should realy spend more time on studying you're weapon of choice!
Link => first hit on google if you search jquery ajax
There is another method of preventing caching. Just append some random number to url you are accessing.
For example:
"www.url.com?" + new Date().getTime()
or
"www.url.com?" + Math.random()
from Stack answer

Why does Ajax never return a value even with callbacks

Ajax never returns a value. I have tried setting the async:false option and also tried to setup a callback function it still never returns a value. When i browse to the url using firefox i see the expected response but when i make the request via ajax, there is no reponse. Firebug also confirms it.
I have tried lots of code samples i found but they never return a value. I have also tried using a different version jquery and other browsers.
Does anyone know what could be wrong?
Thanks
Below is the code that gets called when a user clicks a button on the form.
function login() {
var username = $("#uname").val();
var password = $("#password").val();
$.ajax({
type: 'POST',
url: 'http://localhost/mConnect/login.php',
data: { username: username, password: password },
async: false,
success: function(html) {
slim(html);
}
});
}
function slim(html) {
// var data = $(xml).find("Status").text();
alert(html.responseText);
}
Below is the login.php it just prints static xml
<?php
$array = array('stat' => '1.0',
'mode' => 'whatever',
'content' => 'All');
$new ='<?xml version="1.0" encoding="iso-8859-1"?><response>';
foreach($array as $key => $values) {
$new .= "<$key>$values</$key>";
}
echo $new.'</response>';
?>
You have a success callback, but no failure callback. Probably something along the way is failing and there are about 100 possibilities. Run it in Firebug (or equivalent) and see what happens to the request. (My money: your local webserver isn't responding at all.)
If you sent an AJAX request you will get a response. Even if it is a timeout. So if you don't have a response at all then you more than likely never sent the request.

sencha touch - ajax call to server (url , extra parameter formation)

I am using this to get the result from server
controller.allVisitStore = new Ext.data.Store({
model: 'allVisit',
autoLoad : true,
proxy: {
type: 'ajax',
id: 'allvisit_app_localstore',
url: '/RadMobApp/api',
extraParams:{
action:'query',
queryName:'GET_ALL_VISIT',
authToken: localStorage.getItem("auth_token"),
patTicketId: localStorage.getItem("patientId"),
retFormat:'XML',
keyValuePair:'yes'
},
// the return will be XML, so lets set up a reader
reader: new Ext.data.XmlReader({
// records will have an "T4" tag
record: 'data'
})
}
});
but i am not getting any thing.But i formed this url in browser and checked this i got the correct result. now here i want to check is there any problem in the url formation.How to check the url formation with extra parameter which is pass through ajax. I have checked in Inspect element-> network -> api there is no any api request found there.Is anything wrong in my code. Thanks in advance...
Use Firebug for Firefox or Chrome's developer tools to see what's going on when that store attempts to load itself. My hunch is that your url is incorrect and should be url: '/api' because RadMobApp is probably your app root.

Resources