display the array values-ajax - php

I want to display the values in datatable. How to retrieve the object value in ajax success function..
AJAX
$(function(){
$(document).on("click", "#submits", function(e) {
e.preventDefault();
var password = $("#password").val();
alert(password);
$.ajax({
type: "POST",
url: "db/add.php",
data: "password="+password,
success: function(results){
alert( "Data Saved: " + results );
var obj = JSON.parse(results);
}
});
e.preventDefault();
});
});
</script>

Perhaps you can try this -
$("#submits").bind("click", function(e) {
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "db/add.php",
data : "password="+password,
success : function(results) {
alert("Data Saved: "+results);
var userInfo = JSON.parse(results);
//Output the data to an HTML element - example...
$(".user-name").html(userInfo.patient_name);
}else{
console.log('No user info found');
}
},
error : function(a,b,c) {
console.log('There was an error getting user info.');
}
});
});
//HTML element for data
<p class="user-name"></p>
I've added an HTML element you can simply output the data to. Not sure how you'd like the data to be output but this is simply an example.
Just some quick notes on your code from your original post -
You must set the dataType to json when working with/parsing json. See Documentation.
Once you assign your data to a variable, you need to access that data by declaring the variable and then the data name, such as obj.patient_name.
I've done the best I can to help.
Good luck.

Try this code :
$(results.patient_password).each(function(i,v){
console.log(v.id);
});

use data-type:json,
in your jquery

Related

stucking data sending throw ajax in php

i have a footer.php file and i already wrote the code in ajax which is blow here when i alert data variable then i got id but in success function i didn't get anything .olease somebody help me
© Copyright 2013-2015 Khan's
Boutique
<script>
jQuery(window).scroll(function(){
var vscroll = jQuery(this).scrollTop();
jQuery('#logotext').css({
"transform" : "translate(0px, "+vscroll/2+"px)"
});
jQuery('#back-flower').css({
"transform" : "translate("+0+vscroll/5+"px, -"+vscroll/12+"px)"
});
jQuery('#fore-flower').css({
"transform" : "translate(0px, -"+vscroll/2+"px)"
});
});
function detailsmodal(id){
var data = 'id='+ id;
//alert(data);
jQuery.ajax({
url: '/boutique/includes/detailsmodal.php',
method:"post",
data : data,
success: function(data){
//alert(data);
jQuery('body').append(data);
jQuery('#details-modal').modal('toggle');
},
error: function(){
alert("something went wrong!");
}
});
};
</script>
</body>
</html>`
Your var data should be like this :
var data = {
id: id
}
And in success, the data is the returned to the ajax where the ajax request is sent.

Send variable to PHP using AJAX

I've got a variable that I want to send to my PHP code that is on top of the code but I keep getting an error and undefined. dTotaal is the variable name and it contains a number. All this code is in the same page, so i am posting to the same page.
$('#emailVerzenden').click(function() {
$.ajax({
url: "content.php",
type: "post",
data: ({
totaal: dTotaal
}),
success: function(msg) {
alert('Data saved: ' + msg);
},
error: function(error) {
alert("couldnt be sent " + error);
}
});
On top of my page I've got this code. I'm not sure if it's correct, I am new at this.
if(isset($_POST['emailVerzenden']))
{
$totaal = $_POST['totaal'];
var_dump($totaal);
}
What I wanted was to put the value of the totaal data in $totaal but that is not working. The data is not being sent. I keep getting the error alert().
In your PHP code, you are checking the presence of a variable to use another. For me it should be:
if(isset($_POST['totaal']))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
You are on right track but seperate PHP codes with jQuery codes then you will have full control of processing data asynchronously.
index.php
$('#emailVerzenden').click(function()
{
$.ajax
({
url: "content.php",
type: "post",
data:{totaal: dTotaal},
success: function(msg)
{
alert('Data saved: ' + msg);
},
error: function(error)
{
alert("couldnt be sent ".error);
}
});
And in your php file first check whether $_POST data is set
content.php
if(isset($_POST))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
Mention your data which you wanna send in html & give it an ID.
<div id="total"> HERE COMES THE VARIABLE YOU WISH TO SEND </div>
Then pick up the data in that <div> by its ID document.getElementById('total').value like below:
var total=document.getElementById('total').value;
<script> var total=document.getElementById('total').value;
$.post('content.php',
{'total':total},
function(response){
if(response == 'YES'){}
});
</script>
Hope this will resolve your problem. Good Luck!
Kind of look like i didnt use preventDefault() thats why it wasnt working.
$('#emailVerzenden').click(function(e)
{
cms=$('#sCms').val();
templates= $('#templates').val();
onderdelen = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
email = $('#email').val();
e.preventDefault();
$.ajax
({
type: "POST",
url:"test.php",
data:{postEmail : email,postOnderdelen : onderdelen,postCms : cms,postTotaal : postTotaal, postTemplates : templates},
success: function(rs)
{
alert("Data saved:" + rs);
},
error: function(error)
{
alert("couldnt be sent" + error);
}
});
e.preventDefault();
});

JSON matching data and using data

I've only every used json to fetch data to use on pages or set as variables. But now I would like to search json for a matching name then fetch its views from the json
[{"id":1,"name":"Pale","description":"This is a description","url":"http://domain.com//1/pale","views":2212,"createdBy":{"name":"Bill Lumbergh","url":"http://domain.com"},"createdOn":"2013-10-24T22:54:34.183"},
Above is a little example and using the below code only console.logs the entire json which has about 20 id's
$.getJSON( "content.php", { name: 'Pale' } ,function(data){
console.log(data);
});
$.ajax({
url: 'content.php',
dataType: "json",
success: function (data) {
$.each(data, function(k,v){
if (v.name == theme){
console.log(v.views);
}
});
}
});
The Object you put in the code is the one you are passing to the Server, not receiving. {name:'Pale'} is being sent to the server. If you want the name from the JSON file, it's like:
$.getJSON('content.php', function(data){
console.log(data.name);
});
However, if my guess is correct try the following:
$.getJSON('content.php', function(data){
var ary = data.arrayThatHoldsYourObjects, store;
$.each(ary, function(i, v){
if(v.name === 'Pale'){
store = v.views;
}
});
});
store now holds v.views.

Php does not echo the data from a jQuery Ajax submit

I am fiddling with jQuery.ajax() and php, and I need some pointers in order to make everything work:
Here is the php code:
if(!empty($_POST["fname"])){
$firstName = $_POST["fname"];
echo $firstName."<br />";
}
if(!empty($_POST["id"])){
$age = $_POST["id"];
echo $age;
}
Here is the jQuery code:
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
});
var result;
console.log(result);
});
The values from jQuery exist, I get the alert, telling me the data has been submitted, firebug shows the Ajax post as working.
Why doesn't php gets my data and echo it?
You need to get the returned data by the php and do something with it. See the added line of code below.
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
alert("This is the data returned by the php script: " + result)
});
});
You have to use the success callback function to process the response from the POST to your Php page.
As stated in this thread
Your code could look similar to the following:
/* Send the data using post and put the results in a div */
$.ajax({
url: "test.php",
type: "post",
data: values,
success: function(returnval){
alert("success");
$("#result").html('submitted successfully:' + returnval);
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
So, you have to somehow append the response from your Php to an HTML element like a DIV using jQuery
Hope this helps you
The correct way:
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
Then the jquery script:
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>

Retrieve JSON Data with AJAX

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);
}
});
}

Categories