I have a javascript object like below
var customerinfo = {
customer_name : $('#customer_name').val(),
customer_address: $('#customer_address').val(),
customer_city : $('#customer_city').val(),
customer_state : $('#customer_state').val(),
customer_zip : $('#customer_zip').val(),
};
Then I try to pass that to php using $.ajax like below
$.ajax({
url: "../folder/file.php",
type: "POST",
data: {
'customerinfo' : customerinfo,
},
success:function(){
window.location = "file.php";
}
})
In php I try to print the object out
$customerinfo = json_decode($_POST['customerinfo']);
print_r($customerinfo);
or
$customerinfo = $_POST['customerinfo'];
print_r($customerinfo);
I get undefined index customerinfo
I also tried to json.stringify in the javascript before passing it but get same error.
I found a very similar post such as
jquery ajax object array php but I couldnt get the code to work either.I think the ajax was able to pass the data through, just I dont know how to decode it on the php side.
I know I could just post it from html submit button, but This is simplified testing for a larger issue where I want to pass object that have many objects inside of it using jquery.
if the javascript side is correct, the question is "how to access objects passed through jquery ajax in PHP."
if not, the question would be "how to pass objects from javascript to php."
from what i see the problem might be in the data.
try posting with static data, meaning replace the
var customerinfo = {
customer_name : $('#customer_name').val(),
customer_address: $('#customer_address').val(),
customer_city : $('#customer_city').val(),
customer_state : $('#customer_state').val(),
customer_zip : $('#customer_zip').val(),
};
with
var customerinfo = {
customer_name : 'ddd',
customer_address: 'ddd',
customer_city : 'ddd',
customer_state : 'ddd',
customer_zip : 'ddd'
};
also try sending the ajax from the browser console, that way you'll be able to see the data being posted
Related
Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});
I'm trying to deserialize an array from an URL I've sent from a JQuery Ajax call to a PHP script in the server.
What I have done
I've been sending variables with values to the server successfully with jQuery Ajax this way:
// A simple text from an HTML element:
var price = $("#price option:selected").val();
// Yet another simple text:
var term1 = $('#term1').val();
Then I prepare the data to be sent via Ajax this way:
var data = 'price=' + price + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString
And send it with jQuery Ajax like this:
$.ajax({
url: "script.php",
type: "GET",
data: data,
cache: false,
dataType:'html',
success: function (html) {
// Do something successful
}
});
Then I get it in the server this way:
$price = (isset($_GET['price'])) ? $_GET['price'] : null;
$term1 = (isset($_GET['term1'])) ? $_GET['term1'] : null;
And I'm able to use my variables easily as I need. However, I need to do this with an array.
Main question
Reading a lot, I've managed to learn the professional way to send an array to the server: serialize it! I've learnt this way to do it with jQuery:
var array_selected = [];
// This is used to get all options in a listbox, no problems here:
$('#SelectIt option:not(:selected), #SelectIt option:selected').each(function() {
array_selected.push({ name: $(this).val(), value: $(this).html().substring($(this).html().indexOf(' '))});
});
var array_serialized = jQuery.param(array_selected);
// If I alert this I get my array serialized successfully with in the form of number=string:
//Ex. 123=stringOne&321=StringTwo
This seems to be right. I add this to the data as before:
var data = 'price=' + price + '&' + array_selected + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString&123=stringOne&321=StringTwo
How do I reconstruct (unserialize) my array in the server? I've tried the same as before:
$array_serialized = (isset($_GET['array_serialized'])) ? $_GET['array_serialized'] : null;
with no success! Any ideas why? How can I get my serialized array passed this way in the server as another array which PHP can handle so I can use it?
Or am I complicating my life myself needlessly? All I want is to send an array to the server.
If you name a variable with [] in the end of it, it will create an array out of the values passed with that name.
For example, http://www.example.com/?data[]=hello&data[]=world&data[]=test, will result in the array $_GET["data"] == array('hello', 'world', 'test'); created in PHP.
In the same way, you can create an associative array in PHP: http://www.example.com/?data[first]=foo&data[second]=bar will result in $_GET["data"] == array("first" => "foo", "second" => "bar");
BTW, you might be interested in using jQuery's .serialize() or .serializeArray(), if those fit your client side serializing needs.
I'm not too knowledgeable with PHP, but I think you may have overlooked something pretty simple, <?--php unserialize($string) ?>.
I have an AJAX call using the following;
$.ajax({
type: "POST",
url: "php/customheader.php",
data: {
update: 1,
header : {
1 : custom[1].header,
2 : custom[2].header,
3 : custom[3].header,
4 : custom[4].header
},
header_key : {
1 : custom[1].key,
2 : custom[2].key,
3 : custom[3].key,
4 : custom[4].key
}
},
dataType : 'json',
success: function(data) ajaxSuccessCallback(this_dialog, data)
});
On the PHP end, I am struggling to get this data into a proper associative array to use in loops etc. I've tried;
$_POST['update']
which returns 1. So I know how to use JSON -> PHP when the data is not in an associative/multidimensional array.
Calling this however;
$_POST['header[1]']
returns nothing.
What is the best method for getting this multidimensional data into a proper format for iteration within PHP?
Thanks,
Did you try $_POST['header']?
First convert it to json text first on the client side
e.g
var obj = {'update':1,'header':{'key1':custom[1].key,'key2':custom[2].key,'keyN':custom[N].key},...}
var jsonstring = JSON.stringify(obj);
after setting up the object, use the stringify function to convert it to JSON string (please read more about the json format, it would help you in setting up the object correctly), send it with $.get() or $.post() (makes ajax request easier)
//example
$.get("serverside.php",{'data':jsonstring});
then on the server side lets say you used $.get() on the client side , you'll say
$str = $_GET['data'];
$Obj = json_decode($str,true);
then you can now say:
echo $Obj['update'];
I hope this helps, and be warned, there's lot of debugging ahead, so make good use of the internet
Hey everyone. This one is puzzling me. I'm using PHP and Jquery. I am making an ajax request to a PHP file containing a get url. Eg. Path/to/file/?ID=369
The request goes out fine, I've watched it in fire bug.
However in the PHP file, the ID variable doesn't exist. When I do
var_dump($_GET)
I can see that there are two arrays inside the GET array. These are JSON and action.
Can anyone explain to me what's going on here and how I can receive my ID variable?
here are my codes:
<?php
$program_price_id = $_GET['id'];
$programDepatures = getProgramDepaturesGreaterThanToday($program_price_id);
echo "[{optionValue: 0, optionDisplay: 'Select a date'}";
while ($programDepartureData = mysql_fetch_array($programDepatures)) {
echo ", {optionValue: ".
$programDepartureData['id'].", optionDisplay: '".
tidyDateEnglish($programDepartureData['departure_date'])."'}";
}
echo "]";
?>
Best wishes,
Mike
i think you need to specify the ajax method you are using.It might be a $.ajax, $.get or $.getJson.
but i use $.ajax and here is a snippet
$.ajax({
url:"event/service_ajax_handler.php",
type: "GET",
data: {action:"getTime"},
dataType : "json",
success: function(data) {
$("#cmbTimeRange").html("<option value='-1'>Please select time range</option>");
$.each(data, function(){
$("#cmbTimeRange").append("<option value='"+ this.id +"'>" + this.hours +"</option>")
});
},
error: function(){
alert("error");
}
});
pay attention to the data parameter. see also
getJSON
This may be obvious, but I noticed in the sample URL you have ID capitalized, but in your PHP code you have it lowercase. PHP is case sensitive, so it could be as simple as that.
I want to create a jeditable text area that posts the values entered in to a database and then returns the new value to the div that replaces the textarea. I found this on Stackoverflow that handles returning the new value to the div.
$(document).ready(function() {
$('.edit_area').editable(submitEdit, {
indicator : "Saving...",
tooltip : "Click to edit...",
type : "textarea",
submit : "OK",
cancel : "Cancel",
name : "Editable.FieldName",
id : "elementid",
});
function submitEdit(value, settings)
{
var edits = new Object();
var origvalue = this.revert;
var textbox = this;
var result = value;
edits[settings.name] = [value];
var returned = $.ajax({
url: "http://jimmymorris.co.uk/xmas/record_xmas_msg.php",
type: "POST",
data : edits,
dataType : "json",
complete : function (xhr, textStatus)
{
var response = $.secureEvalJSON(xhr.responseText);
if (response.Message != "")
{
alert(Message);
}
}
});
return(result);
}
});
My problems is I don't know what my POST vars are called so I can insert in to my db. Does it even return POST var to php or does it send php json and how do I know what that is called?
Please help, Cheers in advance.
What it sends to the server depends on what you supply to the "post" mamber of the $.ajax options paremeter.
If you pass a query string parementer data : "name=foo&surname=bar" The PHP script would recieve it in the $_POST variable and could be accessed by means of $_POST['name'] $_POST['surname']
However if you passed an object to the data parameter it would be changed to a query string i.e
data : {name : 'foo', surname : 'bar'},
JQuery.ajax would change it into a query string like the example above then It would be sent to the server, and the PHP script would also access it same as mentioned above.
P.S I highly recommend using some type of encoding when sending data to the server, encodeURIComponent(variable) and accordingly decode it in PHP by using urldecode.
You have the id posted which you can retrieve in the PHP page as $_POST['id']. The text is posted as value which you can retrieve in the PHP page as $_POST['value']. You can of course change the default names.