php post not working using header and ajax - javascript

i am sending a post request using jquery $.post to another domain. every thing works fine but i am not getting the posted data in the requested page please check my code
jquery code
var data = {mydata: 'testing'};
$.post("http://anyurl/file.php",data,function(info){
alert(info);
});
and here is php code
<?php
header('Access-Control-Allow-Origin: *'); // this is to allow another domain
$data = $_POST[“mydata”]; // assigning data to variable
echo $data; // sending back to jquery
?>
it does not return the data please check anyone.
Thanks in advance

Use proper quotes and use isset() to check the data set or not like,
<?php
header('Access-Control-Allow-Origin: *'); // this is to allow another domain
print_r($_POST);// to check the post data
$data = isset($_POST['mydata']) ? $_POST['mydata'] : "No Data";
echo $data; // sending back to jquery
?>

Try to get the POST variable with single quotes and better to put exit after echoing it like
$data = $_POST['mydata'];
echo $data;
exit;
And make sure that it is posting to the given URL or not through console.

OK,It walk well when I test it.In order to reappear the error you've got,I'm trying to set the file.php into a BOM-UTF8 file and it got error in the end.So,please check your file.php if it got a BOM before header().
Another suggess,you can use firebug to test your ajax post process.The link in the console will show you the ajax process,such as what you've post and what is feedback.Just use console.log() instead of alert().

Related

Get php variable to javascript from laravel controller

Im trying to send a variable from a controller to a JavaScript, I have my controller, and I can send an array:
public function index()
{
$casa = new Casa(true);
$result = $casa->where(['show'=>true])->get();
return view('casa', array('casa' => $result));
}
If i go to my HTML and I make and echo:
<html>
<body>
<?php echo $casa ?>
</body>
</html>
I can show my array in the body, I was thinking about make an invisible element and get the array with document.getElementById().innerHTML, but I think this is not the best way.
Also, I think that I could make an Ajax petition sending a post and get the result, but I dont know if I can get my variable in a simpler way.
I tried to make and echo in Javascript and doesn´t work. some ideas?
Can I have 2 method post to get request in my controller? I already have one to get data from a form, and if I set the Ajax request I will have two post request. I would like have just one.
Jeffrey Way created a package for that. He also made a video explaining it in laracasts.com.
The package can be found here: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
You can simply get PHP variable in JavaScript like this:
<script>
var casa = '<?php echo $casa ?>';
</script>
you can use alert to see the result in popup dialog too:
<script>
var casa = alert('<?php echo $casa ?>');
</script>

Reloading url page with ajax

i'm trying to refresh page every 3 second, the url page change with $_GET variable.
i'm trying to save $_GET var into session and cookie, but get error header has already sent.
how to change url after page reload ?
here my script :
Index.php
<?php
session_start();
$skill =$_SESSION['skill'];
?>
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#src2').load('monitor.php?skill=<?php echo $skill;?>').fadeIn("slow");
}, 3000);
</script>
monitor.php
<?php
include "conn.php";
session_start();
$_SESSION['skill'] = $_GET['skill'];
if ($_SESSION['skill']=='')
{
$a ="bro";
$_SESSION['skill']=4;}
elseif ($_SESSION['skill']==4){
$a = "yo";
$_SESSION['skill']='5';
}
elseif ($_SESSION['skill']==5){
$a = "soo";
}
?>
First off, "headers already sent" means that whichever file is triggering that error (read the rest of the error message) has some output. The most common culprit is a space at the start of the file, before the <?php tag, but check for echo and other output keywords. Headers (including setting cookies) must be sent before any output.
From here on, this answer covers how you can implement the "refresh the page" part of the question. The code you provided doesn't really show how you do it right now, so this is all just how I'd recommend going about it.
Secondly, for refreshing the page, you will need to echo something at the end of monitor.php which your JS checks for. The easy way is to just echo a JS refresh:
echo '<script>window.location.reload();</script>';
but it's better to output some JSON which your index.php then checks for:
// monitor.php
echo json_encode(array('reload' => true));
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
if (response.reload) window.location.reload();
}).fadeIn('slow');
One last note: you may find that response is just plain text inside the JS callback function - you may need to do this:
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
response = $.parseJSON( response ); // convert response to a JS object
if (response.reload) window.location.reload();
}).fadeIn('slow');
try putting
ob_start()
before
session_start()
on each page. This will solve your problem.
Without looking at the code where you are setting the session, I do think your problem is there. You need to start the session before sending any data out to the browser.
Take a look at: http://php.net/session_start
EDIT:
Sorry, a bit quick, could it be that you send some data to the browser in the 'conn.php' file? Like a new line at the end of the file?

Setting PHP Session variables with jQuery Ajax

I have a pretty simple issue which I just can't seem to resolve. I have the following ajax request which sets a PHP Session variable
$.post("http://mytestdomain.com/test.php", {"data": 'success'});
And this code in the PHP file to generate and echo the Session variables
session_start();
$_SESSION['test_text']= $_POST['data'];
echo "Pageviews=". $_SESSION['test_text'];
However this keeps returning the following error message
Notice: Undefined index: data in /var/www/test.php on line 2
If I post a demo URL into my browser like this
http://mytestdomain.com/test.php?data=11111
Then the results are echoed correctly.
So my question is, how do I pass via jQuery Ajax data to a PHP session variable and have it saved?
Thanks
In your test.php file, try the following:
session_start();
$_SESSION['test_text']= $_REQUEST['data'];
echo "Pageviews=". $_SESSION['test_text'];

How to get multiple responses to a single ajax request in php

I am making a web app, where I want to provide a search function. I am sending the searched name with an ajax request, and i want to pull the records of that particular person. But since there are many details that are to be displayed, I am finding it difficult to get the response. (I am not able to get more than one response at a time)
I want to know, if there is a way to get multiple responses for a single request, or a way to send all my variables in the target PHP file to the requesting javascript file as an array or something.
Thank you. If this question is asked before, please provide the link.
Use JSON as the datatype to communicate between PHP(Backend) and Javascript(Frontend). Example:
PHP
<?
$person = array("name"=>"Jon Skeet","Reputation"=>"Infinitely Increasing");
header("Content-Type: application/json");
echo json_encode($person);
?>
Javascript/jQuery
$.ajax({
url: "your_script.php",
dataType: "JSON"
}).success(function(person) {
alert(person.name) //alerts Jon Skeet
});
Add everything you want to an array, then call json_encode on it.
$data = array();
$data[] = $person1;
$data[] = $person2;
echo json_encode($data);

$jquery.post() PHP and Mysql

So I half got jQuery's ajax ($.post) to work. But, for some reason, I haven't been successful with finding the right online article to explain to me how PHP retrieves the ajax data that is sent. I've found some stuff on json_decode, but upon me doing that to basically decode it, it wont work (and yes, I am using json for the $.post command).
Here is my javascript code
$.post("notificationNum.php", {"user":"1"},
function(data){
$(".example-number").html(data.amount);
}, "json");
Here is my PHP code
<?php
session_start();
//link to db info here
$user_id_got = json_decode($_REQUEST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>
Mind you all, I've also tried using the $_POST command instead of the $_REQUEST. Any ideas how to send data to the PHP file so I can use it?
"json" in your jQuery call is how your php should write its output, not how jQuery sends it. Use normal $_REQUEST in your php:
$user_id_got = $_REQUEST['user'];
try this
notificationNum.php
<?php
//link to db info here
$user_id_got = intval($_POST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>

Categories