I have the following code but I am unable to access the content of the objects passed using ajax. What am I missing?
$(".submit").click(function(){
var fruits = {"fruits" : ["apples","banana","oranges"]};
var cars = {"cars" : ["BMW", "Honda", "Toyota"]};
var my_Obj = fruits + cars;
mydata = JSON.stringify(my_Obj);
$("#mydata").val(mydata);
$.ajax({
url: "add.php",
type: "POST",
data: {
name: $('#name').val(),
Address: $('#Address').val(),
my_obj : $mydata
},
datatype: "json",
success: function (status) {
if (status.success == false) {
alert("Failure!");
} else {
alert("Success!");
}
}
});
});
<form id="json" method="post" action="add.php">
<input type="text" name="name" id="name" value="">
<input type="text" name="address" id="Address" value="">
<input type="text" name="mydata" id="mydata" hidden>
<input type="submit" name="submit" id="submit" class="submit" value="send">
</form>
add.php
$new_post['id'] = $_POST['id'];
$new_post['name'] = $_POST['name'];
$new_post['address'] = $_POST['address'];
$new_post['my_obj'] = $_POST['mydata'];
print_r ($new_post);
[my_obj] displays [object Object][object Object]. Thanks for any help.
There are a few things wrong that I see:
1, The form can be submitted by clicking enter, so i would use a .submit()
method rather than 'submit.click()':
$('form').submit(function(){
});
2, The form will submit unless you return false
in your .submit()
method
$('form').submit(function(){
// all of your code
return false;
});
3, In add.php
you need to return json
information:
echo json_encode($new_post);
4, You are not setting status
in add.php
$new_post['status'] = true; // or false depending on what your trying to do
Hopefully this will give you a start.
* *Note: This does not take into account the vars that you are sending to add.php
You cannot send raw objects via a form submit, you need to flatten them to text first. This is done via serialization, and the simplest way to do it is via JSON, since it is understood on both the client and most server languages out of the box.
In your case , replace the my_obj part in the AJAX call with: my_obj: JSON.stringify(my data)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.