hi i am calling a php file using ajax after an interval of time. In my php file i simply echo a text line. But it didnt show me any output after time interval..
here is my ajax code form where i am calling my php file..
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"}, });
}, 5000);
});
</script>
code inside the process.php file
<?php
echo "hello testing";
?>
You aren't handling the response from php script. You need to get it by success parameter in ajax. Try this:
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: 'x=1&y=2', // data here! use query strings like this or;
// data: { x: '1', y: '2' }
success: function(response) { alert(response); } // alert the response text
// returns 'hello testing'
error: function(){ alert('error while posting data'); }
});
}, 5000);
});
User the success and error function of ajax. for eg
$.ajax ({
url: 'process.php',
type:'post'
data:data1,
success: function (response) {
//alert response here you will get the value hello testing
alert (response);
},
error {
alert ('error');
}
});
You should modify your code to use the response.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"},
success:function(str){
$("#YOUR_ELEMENT").html(str);
}
});
}, 5000);
});
Just change your JQuery script to show the response after successful request it can be done with done() or success functions.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: { token: "your_token"}}).done(function(msg){
$("#response").append(msg);
};
}, 5000);
});
This will append reponses to #response every 5s when ajax request is successful.
the success block, which handles the data returned from remote script is present in your code. you may need to add something like this .
JS CODE:
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"},
}).done(function( data) {
//data received from remote script
});
}, 5000);
});
Happy Coding :)
Timeout is not the culprit here.
We need to make sure that you have a server where process.php resides and its running fine.
Make sure the path for the file process.php is right. You can use browser's developer tools. When the request is made you will see a new entry under "Network" tab of the developer tools. Exploring it you can get the url at which it the file should be available.
I would suggest using Google Chrome's "postman" extension to test the ajax call before implementing it in your code.
Also you need to have a callback that will run in case of request success or failure. Once you get the string in success response, you can do whatever you intend to do with it.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"} //removed the comma from last argument
}).done(function(serverResponse) {
alert( "Success: " + serverResponse ); //Will show success alert with concatenated text string if the request is successful
}).fail(function(serverResponse) {
alert( "Error: " + serverResponse.message); //Will show error alert with concatenated error message
});
}, 5000);
});
</script>
the php page sends the string "hello testing", and you have to manage it.
take a look here for an example: click me
Related
i want to call thingspeak rest api and want to show the value in html page. im getting the value as undefined.
code
<script type="text/javascript">
$(document).ready(function() {
var response;
$.ajax({
url: 'https://api.thingspeak.com/channels/channelid/fields/field1/last?api_key=key',
type: 'GET',
data: {
format: 'json'
},
success: function(response) {
response = response.field1;
},
error: function() {
$('#errors').text("There was an error processing your request. Please try again.");
}
});
document.getElementById("field1").innerHTML=response;
});
</script>
api response data
{response = {created_at: "2018-03-28T09:36:48Z", entry_id: 2476, field1: "0}
Following the API docs (https://www.mathworks.com/help/thingspeak/readlastfieldentry.html) I found the response if you wanna get the text result you should fix your method. The new method should be something like this:
$(document).ready(function() {
$.ajax({
url: 'https://api.thingspeak.com/channels/147878/fields/field1/last.txt?api_key=S4O9F5QP5QC',
type: 'GET',
data: {
format: 'text'
},
success: function(response) {
alert(response);
},
error: function() {
$('#errors').text("There was an error processing your request. Please try again.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
if you believe that you're using the api in the correct way, as you can see in api response data that you mentioned, there is no "text" key, so you get undefined when you try to access response.text
if you want to convert the response to string format, you should use JSON.stringify(response)
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'https://api.thingspeak.com/channels/channelid/fields/field1/last?api_key=ur_app_key',
type: 'GET',
data: {
format: 'json'
},
success: function(response) {
$("#field1").text(response.field1);
},
error: function() {
$('#errors').text("There was an error processing your request. Please try again.");
}
});
});
</script>
For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.
I have problems to pass the variables to another file, I already realize the code and I do not find the solution, it sends me error in the function
onclick="limit();javascript:AyudaTipos(2)"/>
function
function limit (){
$.ajax({
url: 'Tipos.php',
type: 'POST', // GET or POST
data: {"acreedor":$("#acreedor").val(),"importe2":$("#importe2").val(),
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error! Funcion Limite Anual");
}
}
});
}
Resolved:
$(function(){
$('#help').click(function(){
$.ajax({
url: 'Tipos.php',
type: 'POST', // GET or POST
data: {"acreedor":$("#acreedor").val(),"importe2":$("#importe2").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error!nuevo");
}
});
});
});
Thank You
I am currently using the dark sky forecast api https://developer.forecast.io/ to retrieve json object via jquery get request.the required url parameters format is (api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE") while the valid format with the parameters is:
https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115
inputting this url in your browser will show you a json object.
First thing i tried was a jquery get request :
$.ajax({
type: 'GET'
, data: ''
, url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115"
, success: function (data) {
alert("works");
}
, datatype: 'json'
, error: function (err) {
alert("Could not get forecast");
}
});
this is not succesful- it triggers the error function. i try again using a post request it doesnt work either.please help
This is a simple CORS issue which can be easily resolved by using jsonp datatype:
$.ajax({
url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115",
dataType: "jsonp",
success: function(data) {
console.log(data.latitude, data.longitude);
console.log(data.timezone);
console.log(data.daily.summary);
},
error: function(err) {
console.log("Could not get forecast");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<em>Loading . . .<em>
I am having trouble getting an ajax GET request (or any request for that matter) to retrieve the response. I am simply trying to return the response in an alert event:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(data);
}
});
});
});
</script>
I can get this and other similar post requests to work by taking away the function in the success option and editing the code like this:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: alert('success')
});
});
});
</script>
Why is this? And more importantly, how can I retrieve the response data and transfer it to an alert message? Any help is appreciated!
** Update:
Upon reading the first two users' responses on this question, this is what I have:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'GET',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=418431ea64141079860d96c85ee41916&scope=crmapi&criteria=(((Potential%20Email:test#email.com))&selectColumns=Potentials(Potential%20Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function(data) {
alert(JSON.stringify(data));
}
});
});
});
</script>
I am able to get the error response, so I can confirm there is some kind of error. I also want to point out that I am making the request from a different domain (not crm.zoho.com) so should I be using jsonp? If so, how would I alter the code?
When you have
success: alert('success')
you do NOT have a successful request, you are actually executing this function at the start of AJAX method. The success parameter requires a pointer to a function, and when you use alert('success') you are executing a function instead of providing a pointer to it.
First thing that you need to try is to update type to GET instead of Get:
$.ajax ({
type: 'GET',
Try using the .done() function as follows:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'yourUrl',
dataType: 'json',
}
}).done(function(result) {alert(data);}) //try adding:
.error(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);})
});
});
the error function will also give you some information in your console as to the status of your request.