jQuery ajax not working properly - javascript

I'm trying to implement some ajax function in my php website. I basically know how to use jQuery, but for some reason, the returned value is always empty when I alert() it. This is the code I use:
PHP:
if(_POST('ajax'))
{
$ajax_action = _POST('ajax');
if($ajax_action == "gwonline")
{
return 'test';
}
}
JS / jQuery:
$.ajax({
url: './include/ajax.php',
data: {ajax: 'gwonline'},
type: 'post',
success: function(output) {
alert(output);
}
});
I debugged it and it does call the file with an ajax request and returns the value, but not received apparently.. What am I doing wrong here? I sincerely don't know..

The response should be pass by echo function, not return. So you must use echo 'test'; instead of return 'test';

Don't forget using $ sign in front of every variable in php.

Related

Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key"

I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.
I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.
Here is my JavaScript code:
<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>
<script>
var variable = "hello";
console.log(variable);
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function() {
alert("Success");
}
});
</script>
Here is my PHP code:
$variable = $_POST['pass'];
echo($variable);
Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'
What is causing this? Thank you?
Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.
Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.
By default, jQuery send ajax POST data as formData.
Try to send data as JSON
$.ajax({
url: "ajax.php",
type: "POST",
data: JSON.stringify({pass : variable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){alert(data);},
});
And then you will probably have to adapt your php code:
$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);
Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file.
Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.
Also can you please use
data: {'pass':variable}
instead of
data: {pass:variable}
let me know if it works for you.
If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data.
If you want to receive data that you send you can do this:
Your JS code I call this file index:
var variable = "hello";
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(res) {
alert(res);
}
});
The PHP file:
$variable = $_POST['pass'];
echo($variable);
Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).
Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.
Re: #puckloe your code is working, php echo wouldn't be printed with ajax(correction echo is working but wouldn't show on page if you don't print it with JS too), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }
you ajax code should look like
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(response) {
alert("hi look this is echo from php" + response);
}
});

Run php script inside JavaScript at regular intervals using ajax or any method

I have a index.php with a javascript function Loaddata()
function loaddata(){
<?php
$data = //connects to database and gives new data
?>
var data = <?php echo json_encode($data); ?>;
}
setInterval(loaddata,3000);
I understand the fact that php scripts can only be run once when the page is loaded and it cannot be run again using set interval method. Can someone please guide me how to run the php script at regular intervals inside my index.php using ajax or some other method. My javascript variable "data" depends upon the php script to gets its value. Thanks a lot
Generally, using ajax to get data from a PHP page on the front page is a good way. The way you write this code is fine, too. I suggest writing like this,
var data = <?php echo json_encode($data);?>;
function loaddata(){
// use data
}
setInterval(loaddata,3000);
I think it is more clear
You could use an ajax call to retrive data from php and call that function in setInterval function something like this.
function demofunc()
{
$.ajax({
url: '<?php echo base_url();?>',
type: 'POST',
data: formdata,
dataType: 'json',
success: function(data) {
// do your thing
}
});
}
setInterval(demofunc,3000);
If anyone wondering how to do it.
Echo the PHP value that you want ajax to get for you.
Do an ajax request to the php page to get the data.
$.ajax({
method: 'get',
url: 'time.php',
data: {
'ajax': true
},
success: function(data) {
console.log(data)
}
});
// Second Method
$.get('time.php',function(data){
console.log(data);
});
PHP file
if ($_GET['ajax']) {
echo "HELOOO";
}
//if using the 2nd method just echo
echo "hi second method";

Parsing Javascript variable to AS3

I'm trying to write a simple 2 way chat but got a problem. I'm sure it's very basic but couldn't figure out since I'm new to this.
Below is my JS code to pass a streamID to AS3:
jQuery.ajax({
url: ajaxurl,
type: 'POST',
data: 'action=sd_chat_code&chat_code='+chat_code,
success: function(data){
object.streamCompanion(data);
},
error: function(data) {
console.log(data);
}
});
and in AS file, I got the streamID passed through as below:
public function streamCompanion(data):void {
var netStreamObj:NetStream = new NetStream(_nc);
netStreamObj.play(data);
_client.attachNetStream(netStreamObj);
}
Here's my code so you can check https://codepen.io/adamboy_1802/pen/MpqyML
The variable data above returns "12345" correctly. I tried to output is via JS and there's nothing wrong:
ExternalInterface.call("function() { console.log("+data+") }")
Any advice would be greatly appreciated.
(Solved)
So after trying to create a text box and output the variable data in Flash instead of alert it out via jQuery, the problem relied in my ajax call, where I use echo json_encode(my_var), simply change it to echo my_var fixed the problem.

Send array with Ajax to PHP script in wordpress

I'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress.
Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
Send array with Ajax to PHP script
Passing JavaScript array to PHP through jQuery $.ajax
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps

AJAX call with jQuery and get result

jQuery.ajax({
type: "POST",
url: "index.php?page=Chat",
data: { action: "sendMessage" },
}).done(function(msg) {
jQuery("#main").append(msg);
});
and my PHP code simple returns a string
return 'myString';
Unfortunately myString is not added to the #main-container. What is wrong with this code?
The OP tried to treat php pages as functions but php pages cannot return value like functions.
Therefore the solution of this question is to print $mystring in php page instead of returning it.

Categories