I'm using this code to make an Ajax request to a JSON file:
var queries = $("#myform").serialize();
$.getJSON("/files/json.php?" + queries,
function(data){
alert(data);
}
);
But it returns no errors and the alert is not performed. The PHP files send data using the
header('Content-type: application/json');
And if I open the same query within direct URL it returns the JSON data, so the problem is jQuery.
The network tab shows:
json.php?(my queries parameters and values)
/files
GET
200
OK
application/json
jquery.js:9597
How can I fix this problem?
Try this,
var queries = $("#myform").serialize();
$.getJSON("/files/json.php", queries,
function(data){
alert(data);
});
Second parameter for getJSON is actually form data which you have to pass to the php page
Related
I have this php file graph.php
$host = $_POST['hostname'];
echo $type=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type.'.inc.php');
and I trying to send data to this file using this ajax code
var type_char='fortigate_cpu';//$('#graph').val();
var hostname='10.10.0.144';//$(this).attr('id');
//$('#device_host').val(id);
$.ajax({
type: 'POST',
url: 'SNMP/graph.php',
data: { hostname:hostname,type_char:type_char },
success: function(data) {
alert(data);
// show the response
$("#grph").attr("src", 'SNMP/graph.php');
console.log(data);
}
});
the result when I send data to that file is
fortigate_cpu as a value of type_char variable
when I opened error.log file in apache logs
I have this message
include(): Failed opening 'graphs/.inc.php' for inclusion (include_path='.:/usr/share/php')
as you see the value of fortigate not included in include function even if the char_type variable is send by ajax and printed in page
include file must be as this
include( 'graphs/fortigate_cpu.inc.php')
why type not included in the include session even if the variable is received from ajax
As was mentioned by other users in the comments, maybe your issue is that you are setting type to a different value after including rrdtools.inc.php .
Try randomizing ( changing the name), of the type variable:
$host = $_POST['hostname'];
echo $type123456=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type123456.'.inc.php');
It's the only thing I can think of, since both I (and others) have tested your code.
(both front-end and back-end).
PS: Include using post param is a bad practice.
I want to get rid of my html form submits and replace them by Ajax ( X M L H t p Request). I have set the form return value to "false" and I have written a small test to test the Ajax mechanism.
At the Java script side I do receive the ready state 4 and status 200, so sending data succeeds apparently, but at the PHP side the variables never arrive.
I try to pick them up the usual way with the POST method, the same way like I did before when receiving html submits, of which the simplified form is:
$x = $_POST['x'];
echo $x;
'x' having been sent with Ajax, state 4 , status 200.
Can anyone tell what am doing wrong?
Thanks a lot.
most likely you are posting JSON data? Try this snippet:
switch ($httpMethod) {
case 'POST':
$rest_json = file_get_contents("php://input");
$jsonData = json_decode($rest_json,true);
foreach($jsonData as $item){
var_dump($item);
$studentsCollection->insert($item);
}
$response = $studentsCollection->find();
break;
This is from a simple rest api I was using. Just change it to suit yourself without a verb switch statement.
Perhaps your ajax request is being submitted via GET instead of POST. Try $_GET instead of $_POST, or use $_REQUEST to cover both your bases. If you're not using jQuery, I'd recommend using it, ajax is a lot easier with ajax(), post(), etc.
$('form').submit(function(e)
{
e.preventDefault();
$.post("test.php", $(this).serialize(), function(result) {
console.log(result)
});
});
I suggent check the header of your ajax requests (in the chrome or firefox), the you can see if really your data is passing to the PHP side.
To find the issue you can use debug tool Firebug is good to to debug ajax request.
using Firebug you can see the ajax call.
You can see the parameters you send.
You can see the respond of the ajax request.
My suggestion is use Jquery for your javascript function.
Jquery ajax call up code -
$.ajax({
type: 'POST',
url: 'ServerPageUrl.php',
dataType: 'json',
success: function(data){
if(data==true)
{
alert("OK");
}
else
{
alert("Error save data");
}
}
});
You can learn more about jquery ajax from jQuery.ajax()
More help full page
Thanks.
Hi I am using ajax to do a post request. I think what I want to do is call a function within a php file but am a little confused if and how you do this, could anyone shed any light on this? This is what I have in my js file:
function callAjaxAddition2() {
arguments0 = jQuery('#code').val();
$.ajax({
type: "POST",
url: file.php",
data: {code: arguments0},
success: function(data) {
request( $posted )
}
});
return false;
}
'request' is a function within the php file.
Update I think I should be able to trigger what I need to using this: http://docs.woothemes.com/document/wc_api-the-woocommerce-api-callback/ if I put the url into the url field however that doesn't seem to work, how might I use a callback with ajax post?
First fix this line with the missing opening quote file.php".
You cannot call a PHP function through AJAX but can trigger when it needs to be called, the following demonstrates the same:
In your PHP, your code would be:
if(isset($_POST['code'])){
#'code' here is the identifier passed from AJAX
request($_POST['code']);
}
Once your function has been called, does the necessary and returns the output to AJAX, you can use the data parameter you have set to see what output was sent back from PHP:
success: function(data) {
alert(data); //contains the data returned from the
//PHP file after the execution of the function
}
Calling on a php file via ajax call is like running the script that you pass in the url parameter.
You don't get access to the inner functions, all you can do is pass data and get response.
If you want the request() function to be called in the script, you will have to call it in the php script.
Is it possible to read request header and thereafter fetch the variable value (say of example user id) in the jquery mobile + javascript code? If yes any example?
I found this article. How to get read data from response header in jquery/javascript, but not sure how it would work.
use this :
getAllResponseHeaders()
more detail here
Or this:
getResponseHeader()
more detail here
$.ajax({
type: 'POST',
url:'url', //the request url
data: {}, //any param that you want to send in the request
success: function(data){ //'data' is the response
alert(request.getResponseHeader());
}
error: function () {
alert("failed");
}
});
If you want request headers from this page you can get them via php getallheaders and display them as javascript array.
<script>
var headers = <?php echo json_encode(getallheaders()); ?>;
</script>
Can someone explain me how to make a REST call using jQuery/Javascript? I tried using the .getJSON() and .ajax(), but neither helped me.
This is the REST URL :
http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=94954&date=2010-01-15&format=json&key=API_KEY
Code:
$.getJSON('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode='+zip+'&format=json&key=**<KEY HERE>**',
function(data)
{
alert(data.AQI);
}
);
$.ajax({
url: 'http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode',
type: 'GET',
data: 'zipcode='+zip+'&format=json&key=**<KEY HERE>**',
success: function() { alert('get completed'); }
});
there are a couple of problems. First, you need to add &callback=? to the end of the querystring to allow the crossdomain.
$.getJSON('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=94954&format=json&key=B868EA39-1D92-412A-96DE-DCF5ED30236D&callback=?',
function(data)
{
alert(data.forecast[0]);
}
);
You will then get an Uncaught SyntaxError: Unexpected token : error. This is because you are expecting json data, but the headers on the server are sending text/html - not application/json. Take a look at the console when you run this fiddle, you'll see the errors.
Therefore, you can't get the data from cross domain because you have to be using jsonp - which requires the header to be sent correctly.
If this is your api, then you just need to send the correct header, otherwise, you need to get with the developers there and ask them to fix it.
Alternatively
If neither of those above options work, you could always create a proxy script that would get the contents of the json feed for you and echo it out. Here's one in PHP:
<?php
// myproxy.php
header('Content-type: application/json');
$zip = $_GET['zip'];
$results = file_get_contents('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=' . $zip . '&format=json&key=B868EA39-1D92-412A-96DE-DCF5ED30236D');
echo $results;
?>
Then, you would just point your $.getJSON to this script on your server:
$.getJSON('/myproxy.php?zip='+zip,
function(data)
{
var mydata = jQuery.parseJSON(data);
alert(mydata.forecast[0]);
}
);