AJAX call with jQuery and get result - javascript

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.

Related

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

jQuery ajax not working properly

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.

Passing variables to PHP script via AJAX

I am truing to pass variables to a PHP script using onclick but obviously I am doing something wrong.
So..I have in my main page somewhere:
<img src="myImage.jpg" id="cart_icon" onclick="addcart('100')">
and the addcart function:
function addcart(id){
$.ajax({
url: "add_item.php",
method: "POST",
data: {prod_id : id}
});
}
The add_item.php looks like this (just a simple example):
if (!isset($_SESSION)) session_start();
if (isset($_POST['prod_id'])){$_SESSION['item_id']=$_POST['prod_id'];}else($_SESSION['item_id']='Not Set');
When I check the value of the SESSION['item_id'] I am getting 'Not set' instead of '100'
Any thoughts? This is just a simple example. The actual code is more complex. Thanks
Firstly, your AJAX call looks incorrect because the method of the call needs to be defined via type and not method.
Read the documentation of $.ajax.
The correct call should be:
function addcart(id){
$.ajax({
url: "add_item.php",
type: "POST", // notice the change over here
data: {prod_id : id}
});
}

Posting JSON string to PHP page

Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.

Categories