i have a php array:
$Array= array ($eventRow['title'], $eventRow['start_date'], $eventRow['start_time'], $eventRow['end_date'], $eventRow['end_time'], $eventRow['description'], $eventRow['address']);
i am exeucing an ajax script with a html button, and i would like to get these variable's values as the following:
(document).ready(function() {
//##### send add record Ajax request to outlookimport.php #########
$(".exportOutlook").click(function() {
/*var myData = {
title:
startDate:
startTime:
endDate:
endTime:
description:
address:
username:
};*/
...
any idea how to get the values in the JS file when processing the ajax query?
after this, a php file as called by the ajax, when i would like to get the variable as the following:
$title = $_POST['title'];
$startDate = $_POST['startDate'];
...
...
any idea would be appreciated
In jQuery, it's:
$.post('outlookimport.php', myData, function (returnedData) {
//Do something
});
By including myData as the second parameter, its values will be posted to the PHP script.
Use json_encode($Array) and read the JSON response in your ajax request on success.
$.ajax({
type: 'POST',
url: 'outlookimport.php',
data: myData,
success: function(response){
console.log(response);
}
});
Related
Ive finally managed to get this array build and sent to my PHP function via ajax however, I dont seem to be able to decode it / var_dump produces nothing in the response panel on success.
My arrays:
var data = JSON.stringify({
newEmailForm: newEmailForm,
properties: properties
});
Which produces this:
{"newEmailForm":[["coda#knoppys.co.uk","sikjdhf","Youe message here"]],"properties":[["31466","asdasd","asdads"],["31440","asdasd","asdad"]]}
My ajax function which is posting over the following array.
jQuery(function(){
jQuery.ajax({
url: siteUrl,
type:'POST',
action: 'elegantSendEmail',
data:data,
dataType:'json',
success:function(result){
console.log(result); //This returns nothing, not even 0
}
});
});
My PHP function. If i simply echo hello world then it works.
add_action( 'wp_ajax_elegantSendEmail', 'elegantSendEmail' );
function elegantSendEmail() {
$array = json_decode($_POST('data'), true);
var_dump($array);
wp_die();
}
You're not posting the data as form-encoded, so it won't be in $_POST. It will be sitting in the input buffer.
$your_json = file_get_contents('php://input');
$your_array = json_decode($your_json, true);
If you want to access the sent data in you php code through $_POST('data') you would want to send it in the data key
jQuery.ajax({
url: siteUrl,
type:'POST',
action: 'elegantSendEmail',
data: { data: data },
dataType:'json',
success:function(result){
console.log(result); //This returns nothing, not even 0
}
});
I have the following data in a JS script:
$("#holdSave").live('click', function () {
var arr = {};
var cnt = 0;
$('#holdTable tbody tr').each(function () {
arr[cnt] = {
buyer: $(this).find('#tableBuyer').html(),
sku: $(this).find('#tableSku').html(),
isbn: $(this).find('#tableISBN').html(),
cost: $(this).find('#tableCost').val(),
csmt: $(this).find('#tableConsignment').val(),
hold: $(this).find('#tableHold').val()
};
cnt++;
}); //end of holdtable tbody function
console.log(arr);
$.ajax({
type: "POST",
url: "holdSave.php",
dataType: "json",
data: {
data: arr
},
success: function (data) {
} // end of success function
}); // end of ajax call
}); // end of holdSave event
I need to send this to a php file for updating the db and emailing that the update was done. My console.log(arr); shows the objects when I run it in firebug, but I can't get any of the information on the php side. Here is what I have for php code:
$data = $_POST['data'];
print_r($data); die;
At this point I am just trying to verify that there is info being sent over. My print_r($data); returns nothing.
Can anyone point me in the right direction please?
dataType: "json" means you are expecting to retrieve json data in your request not what you are sending.
If you want to send a json string to be retrieved by $_POST['data'] use
data: {data: JSON.stringify(arr)},
Use the json_encode() and json_decode() methods
Use the next way:
data = {key1: 'value1', key2: 'value2'};
$.post('holdSave.php', data, function(response) {
alert(response);
});
Note: haven't tested it, make sure to look for parse errors.
Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}
Am a noob so hope you can help!
I've got the following jquery code:
$("#single-home-container").html(post_id);
It then displays the value I want within the HTML on the page:
<div id="single-home-container"></div>
What I would like is to pass the value into a PHP variable to I can use the info in a MySQL query.
How do I do so? It's in WordPress so no separate files
Thanks
You can use jQuery.post() or jQuery.ajax().
Here some examples:
<script>
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
</script>
<script>
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
</script>
You'd need to use ajax. Something like this:
JQuery:
$('.locationID').click(function(){
var post_id = $(this).attr('rel'),
$container = $("#single-home-container");
old_html = $container.html();
$container.html('loading...');
$.ajax({
url : '/path/to/php/file.php',
data:{"post_id":post_id},
type: 'post',
dataType: 'json',
success: function(data){
$container.html(data.postBody);
},
error: function(data){
// possibly notify the user of the error
$container.html(old_html);
}
});
});
That assumes you have a field in your posts table called postBody
PHP
<?php
header('Content-type: application/json');
// $query_result = do mysql query with $_POST['post_id']
echo json_encode($query_result);
exit();
?>
That assumes that you want all the fields and you're returning all the fields, including postBody - and of course you have PHP 5.2.6+ or whatever version they added json_encode().
My imaginery code:
$(document).ready(function() {
$("#sub").click(function() {
info['moto'] = $("#moto").val();
info['motox'] = $("#motox").val();
$.ajax({
type: "POST",
url: "index.php",
data: "arr="+info,
success: function(msg){
$('.answer').html(msg);
}
})
})
})
How could I make, that after receiving it in .php file I could use POST method like this: $_POST['moto'] and $_POST['motox'] or something like that? What should I change? Thanks.
Just:
data: info,
(And you need to initialize info as an object in the first place: var info = {})
Check out jQuery serialize(), it does all the work for you if you are working with form inputs.
I thinkyoushould go also the same way like jquery-ajax-data-array-from-php