Can someone please give me a simple example how should jquery $.ajax syntax look like in order to pass array from php to jquery.
On server side I have:
$a=array(1,2,3,4,5);
echo json_encode($a);
So, I'd like get this to js and have:
js_array=[1,2,3,4,5];
I'd really appreciate any help, cause I've been trying for some time now and no luck.
Thank you!
$.ajax({
method: 'GET', // or POST
url: 'yourfile.php',
dataType: 'json',
data: {}, // put data to be sent via GET/POST into this object if necessary
success: function(response) {
// response is your array
}
});
you can either use:
$.ajax({
url: 'url',
dataType: 'json',
success: function(data){
//do something with data
}
});
or:
$.getJSON('url', function(data) {
do something with data
})
Related
I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.
I'm using this ajax to pass an array of strings to another page.
This is the array on nomes.php
[ 'Home','A empresa','funcionarios','Quem Somos?','Historia','Inicio',]
This is the code, the alert doesn't work - can anyone help?
$.ajax({
type: 'post',
url: 'nomes.php',
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
v=data;
alert(v);
}
});
You need to encode the PHP-array to a JSON-array.
<?php
echo (json_encode($myPhpArray));
?>
You can serialize the array into JSON using stringify to pass them through. Add this to your Ajax call:
data: JSON.stringify(arr);
Replace arr with your JavaScript array. This needs a plugin though. Have a look at this answer for more info.
Alternatively, if your array is in PHP, not in JavaScript you can echo it out directly like this:
data: <?php echo json_encode($arr) ?>,
If you're trying to pass the json to the server, you can do it like :
var strArray = ['str1', 'str2', 'str3'];
$.ajax({
type: 'post',
url: 'nomes.php',
data: {strarray: strArray},
dataType: "json",
success: function(data){
v=data;
alert(v);
}
});
If you're trying to receive it, you need to set the header on php side :
header('content-type: application/json');
echo json_encode(array('str1', 'str2', 'str3'));
I am new to AJAX and am kind of confused by what PHP passes back to the jQuery.
So you have an AJAX function like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
(I took this from ajax another StackOverflow page.)
But on various other resources they will have the success section look like this:
success: function(data) {functionfoocommandshere}
I am just confused as to what dictates the naming of this variable? If the PHP ultimately echoes an array:
echo $myVar;
How can I get this from the AJAX?
An Ajax-Requests fetches a whole site. So you'll not get any data in variables, but the whole site in the data-parameter. All echos you made together will be in this parameter. If you want to retrieve an array, you should transform it to json before.
echo json_encode($myArray);
Then you can receive it via Ajax in this way
$.ajax({ url: '/my/site',
data: {action: 'test'},
dataType: 'json',
type: 'post',
success: function(output) {
alert(output);
}
});
In you PHP file, use json_encode to turn the array into a more convenient format for use in Javascript. So you would have something like:
echo json_encode($myArray);
Then, in your JavaScript, the data variable of the success method will hold the JSON. Use jQuery's parseJSON to convert this to a JavaScript object, which will then be very easy to manipulate. I don't know what you array contains, but you might do something like this:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.name[0] === "John");
}
});
Again, the data variable here will contain anything your PHP outputs, but JSON is a common and convenient way to transfer data back to your JavaScript.
<script type="text/javascript">
$.ajax({
url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
</script>
<?php
$action = $_POST['action'];
echo $action;?>
Any output that is printed/echoed will be returned to the success function. This is handy when you want to fill an html container with something that you need to run in real time.
Once you get the hang of this, another option is to use JSON to return variables with values.
The data that's returned from the PHP AJAX function, can be retrieved from the success block. Here's the manual
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
dataType: 'json',
success: function(output) {
//output is the data returned from PHP AJAX function in JSON format
alert(output);
}
});
In my view I have an ajax call:
$(".previous").click(function() {
$.ajax({
type: "POST",
url: "planner/get_cal",
data: {current_month: current_month},
success: function(msg){
alert(msg);
}
});
the get_cal function in my Planner controller:
function get_cal()
{
echo "dinosaurs";
}
However, instead of returning "dinosaurs", it returns a full HTML page. I can't figure out why. Thoughts? Thanks a lot.
I solved this by using a leading slash as suggested in the comments to my question.
$.ajax({
type: "POST",
url: "/planner/get_cal",
dataType: "text",
data: {current_month: current_month},
success: function(msg){
alert(msg);
}
});
You can also get it by adding exit after echo in your php file like below:
function get_cal()
{
echo "dinosaurs";exit;
}
It will work. :)
Try setting the dataType to "text"
$.ajax({
type: "POST",
url: "planner/get_cal",
data: {current_month: current_month},
dataType: "text",
success: function(msg){
alert(msg);
}
});
When using the CodeIgniter structure of Controler/Method uri segments I've found it much easier to use ../../controller/method as my URL's in jquery ajax requests. I also recommend specifying a dataType so that the string is parsed and returned as an object.
Here is an example;
$.ajax({
type: "POST",
dataType: "json",
url: "../../controller/method",
success: mySuccessFunction
});
These type of problem come when your php file and html file are not on proper path so that apache server could parse php files.
Without mentioning type:'text' and any other format also, ajax will work.
But be sure that your server is reaching to php file. Otherwise whole file will be treated as text and returned.
For anyone that is using the Zend Framework, I was experiencing the same issues where the AJAX response was returning the full HTML instead of the json_encode() response. This was resolved by adding the following to my controller:
if ($this->getRequest()->isXmlHttpRequest())
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
Just wanted to mention:
the url will really depend on how you have your .htaccess and folder structure set-up.
So the best way is to try several urls, i.e.:
../../controller/method
../controller/method
server_folder/index.php/controller/method
http://example.com/server_folder/index.php/controller/method
and then choose the one that works best in a given situation.
// Main Page view
$("#button").click(function(e)
{
value=$("#input_value").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>path",
data: "type=get_path_details&mobile="+value,
cache: true,
dataType:"html",
async: false,
success: function(data)
{
$('.apend_new_div').empty().append(data);
$('.scroll_card').css('overflow-x','scroll');
}
});
});
// Controller
public function path()
{
$id = $this->input->post("mobile");
// Some function goes here
// $template[''] = ;
$this->load->view('ajax_page',$template);
}
// ajax view page
<?php if($_POST['type']=='get_path_details'){if(!empty($template)){ ?>
// Html code
<?php }} ?>
I'm writing a simple ajax function and looking to populate two text input fields with the 'success' results. I'm wondering what my php syntax has to be to return an object.
Here is my Javascript function
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}
Here is my php doc (so far, this is where I need to know how to return an object)...
<?php
$data = array('title'=>'this');
echo json_encode($data);
When I run the function I just get the alert "undefined".
Suggestions?
Thanks,
-J
Try this. You can specify that you're expecting a JSON object and then you can interpret data accordingly.
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data.title);
}
});
}
I have returned JSON data from the server via a jQuery Ajax call, not in PHP but it should be the same. As long as you set the content-type of your response to application/json jQuery should consider the responseText as a JSON string. Alternatively you can also set dataType: "JSON" in your Ajax call which tells jQuery that you expect JSON.
Your php page returns: {"title":"this"} in this case.
So you can reference the result with:
alert(data.title);
You may need to specify the data type:
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
dataType: 'json',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}