I am tring to write a page, which takes a RSS feed from a news site via AJAX and then sends it to PHP where I can work with it. The news feed is returned as an object array. I have tried posting it as it is, and also as a json string. The post method seems to be a success, but PHP gives an undefined index notice. This is my first time using AJAX and PHP and I seem to have problem with getting the data from the PHP side.
The error:
Notice: Undefined index: data in ...\index.php on line 33
Current code is the following:
ajax side
url = 'http://feeds.bbci.co.uk/news/rss.xml?edition=int';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('LOAD ERROR, INVALID URL');
},
success: function(xml){
values = xml.responseData.feed.entries;
var senddata = JSON.stringify(values);
console.log(senddata);
$.ajax({
type: "POST",
url: "index.php",
data: {data : senddata},
success: function(){
alert("postdone!");
},
error: function(){
alert("posterror!")
}
});
}
});
php side
<?php
$data = json_decode(stripslashes($_POST['data']));
echo $data;
?>
Wrap your code in an if to avoid that warning:
if (isset($_POST['data'])) {
$data = json_decode(stripslashes($_POST['data']));
echo $data;
}
The problem is when you visit that index.php from browser, there is no POST request, so of course $_POST is empty and $_POST['data'] is not set.
Hope you get the point.
EDIT:
Hmm I can't see anything seriously wrong. And actually now I recommend you to use php.net/manual/en/book.curl.php to get the data directly from the RSS, instead of nesting 2 ajax calls.
Related
I am trying to pass data from a JS script to a PHP file.
I am using JQuery post as follows:
const Url2 = 'MainPage2.php?action=updatePurchaseToDB';
const data = {
action: "updatePurchaseToDB",
name: "test name"
}
//takes 3 arg, url, data to send, call back function, data in callback holds the page reqeusted in data
$.post(Url2,data, function(data, status){
console.log(`status is ${status} data : ${data}`);
alert("PHP Retrned form server: Status " + status + " Data: " + data);
});
}
This appears to execute correctly as the status is returned as successful.
The PHP code I am looking to reach :
if ($_POST['action'] == 'updatePurchaseToDB'){
echo "<script>$(`#purchaseButton`).html('Test- received data');</script>";
}
The following error is thrown:
Undefined Index: action
Not sure why as the action is declared in the URL and data parameters.
If I try same with a Ajax call:
$.ajax({
url: 'MainPage2.php?action=updatePurchaseToDB',
type: 'POST',
success: function(data)
{
console.log(data);
}
});
Again I get a successful response form the server and same error.
I read this post but I must be reading it incorrectly.
I understand there are allot of answers with a similar question but I was having difficulty finding same for my situation.
Input appreciated.
Contents of $_POST is data lines after HTTP headers.
But your action=updatePurchaseToDB is part of the request url. You should access it thru $_GET["updatePurchaseToDB"].
And one question about
echo "<script>$(`#purchaseButton`).html('Test- received data');</script>";
Isn't it should be
echo "<script>$('#purchaseButton').html('Test- received data');</script>";
In the first case, even if the parameter is in the url or as a data parameter, you are calling as a GET, so the Post is index unavailable.
In the second case you are doing a post, but the parameter 'updatePurchaseToDB' is a GET parameter, you aren't sending any data to PHP file. again, the index will be unavailable.
Try it:
const data = {
action: "updatePurchaseToDB",
name: "test name"
}
$.ajax({
url: 'MainPage2.php?action=updatePurchaseToDB',
type: 'POST',
data: data,
success: function(data){
console.log(data);
}
});
I am trying to send a variable from JS to php through ajax but I'm not able to get in php file.
JS
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
PHP
print_r($_POST);
this is showing an empty array but when I do console.log(data) it shows an array in console.log
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function(data) {
console.log(data) ;
});
Edit: (by mega6382) I believe OP wants to open a page in browser with post params, which cannot be done by AJAX. All others who answered got mistaken by the AJAX code in the question and started providing AJAX solutions, without realizing what OP is trying to do. If you were to read OP's comments on Jeroen's answer.
The problem is with what you do when the ajax request finishes:
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
Here you are re-directing to http://localhost/test/ajax.php (requesting it a second time...), using a GET request so $_POST is indeed empty.
Just do the following in your php file to receive a json formatted string
echo json_encode(['success' => true]);
Instead of ajax try sending a dynamically generated form like:
var names = ['lee','carter'] ;
var newForm = $('<form>', {
'action': "http://localhost/test/ajax.php",
'target': '_top',
'method': 'POST'
});
names.forEach(function (item, index)
{
newForm.append($('<input>', {
'name': 'name[]',
'value': item,
'type': 'hidden'
}));
});
$(document.body).append(newForm);
newForm.submit();
This will send the values over POST via a form. It will do both redirect to the new page and send post vals.
Since you're using an AJAX request, in this case POST, you could use the _REQUEST method in php for obtaining the JS variable. In your case try:
$names = $_REQUEST['name']
echo $names;
/* Or try JSON_ENCODE if echo isn't working*/
$json = json_encode($names)
echo ($json);
var names = ['lee','carter'] ;
JSON.stringify(names);
$.ajax({
type: "POST",
dataType: 'json',
url: "http://localhost/test/ajax.php",
data: {name:names}
}).done(function() {
console.log('ok');
});
This is a successful ajax call. Now in order to "check by yourself" that is working you don't have to redirect to the other page because that way you refresh and lose the data. What you have to do is:
Open developer tab in your browser
Go to network tab
Locate your ajax call (it has the name of your php class that you do
the call)
go to response tab and there you have your php output
This link is to help you understand how to debug ajax call
The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}
My PHP code on Xampp
<?php
$data = ((**Refer the JS fiddle Link below for JSON data**));
//header('Content-Type: application/json');
echo $data;
?>
my client Javascript code
function clickbtn(){
$.ajax({
url: 'http://localhost/json/index.php',
type: 'GET',
contentType:'json',
//data: JSON.stringify(data),
success:function(dataF){
console.log('SuccessMsg:'+dataF);
alert(dataF.surveyId);
},
error:function(){
alert('Error: Unable to connect to the server');
}
});
}
I am able to dump the JSON from the php server on my browser console. But i am unable to see the alert "SurveyID" value on alert box.
Kindly take the JSON data available in JS fiddle link and paste it in your PHP script and test it.
If you are testing on chrome Please add the ((Chrome installation path))--disable-web-security to allow cross domain origin policy and then run the JSfiddle link at your end.
JSfiddle for client JS and PHP JSON data
You should use the dataType option instead of contentType if you need the response to be JSON parsed automatically by jQuery.
$.ajax({
url: 'http://localhost/json/index.php',
type: 'GET',
dataType:'json', /* dataType instead of contentType */
...
success:function(dataF){
console.log('SuccessMsg:'+dataF);
alert(dataF.surveyId);
},
...
});
Sometimes jQuery (or the browser?) respone with a string instead of an object.
You have to ckeck this an parse it to json maybe. I've encountered this problem too often, so i' checking this every time.
function clickbtn(){
$.ajax({
url: 'http://localhost/json/index.php',
type: 'GET',
success:function(dataF){
console.log('SuccessMsg:'+dataF);
if(typeof dataF != 'object')
{
dataF = jQuery.parseJSON(dataF);
}
alert(dataF.surveyId);
},
error:function(){
alert('Error: Unable to connect to the server');
}
});
}
I think that the dataType parameter is sometimes ignored :(
So I am adding a list of stores to a web page via a jQuery AJAX request. This little utility is not dynamic, just database driven. I have decided to use jQuery/AJAX to transfer the data because when I try to embed PHP in our current PHP CMS, I get a bunch of conflicting errors.
The problem I am having is that I am getting a jQuery AJAX error when trying to make the request to the PHP script, and I am not sure why.
Here is my AJAX request
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(data) {
console.log(data.error);
}
});
});
The cryptic console error i am getting is this
function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
Here is my PHP code if it will be helpful:
//database connection
$return_arr = array();
$sql = mysql_query("SELECT * FROM where_to_buy");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$row_array['store_name'] = $row['store_name'];
$row_array['store_url'] = $row['store_url'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
I think the problem might be because I wrapping my JSON in an array?
EDIT:: JSON output from php script as requested
[{"store_name":"Example 1","store_url":"http:\/\/www.example1.com"},{"store_name":"Example 2","store_url":"http:\/\/www.example2.com"}]
Thanks for any help!
The reason you are getting that weird error message is that the error callback for the jQuery ajax function takes 3 arguments instead of 1, as described in the docs here: http://api.jquery.com/jQuery.ajax/
The first argument is a jQuery-special XMLHttpRequest object, which has a property called error that contains the function you are seeing logged to your console. The actual error that occurred during execution of your ajax call is the passed in to the error callback as the 3rd argument.
To see it, you should do something like:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
That will get you closer to the real problem.
UPDATE:
Please show the output from your php script. It may be that it is not returning valid json. As noted in the php docs ( http://php.net/manual/en/function.json-encode.php ), [json_encode] only works with UTF-8 encoded data.
You might also check in to json_last_error ( http://php.net/manual/en/function.json-last-error.php ) to see if the encoding failed for some reason.
UPDATE 3:
It seems like your problem may be the path to the php script.
try it with:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php", // <-- notice the leading slash!!!
//dataType: "json",
success:function(data){
//results(data);
console.log(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
or, putting it all back together if the above logs the correct json output to the console...
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});