Hi i don't get retrieve Ajax Data to PhP page its throwing error. i pass data as json object.
The error i'm getting is
Edit.php
$('#regForm').on('submit', function (e) {
var url = document.URL; // Get current url
var id = url.substring(url.lastIndexOf('=') + 1);
var data1 = $("#regForm").serialize();
data = {data:data1,id:id};
console.log(data)
$.ajax({
method:"POST",
url: 'update.php',
dataType : 'json',
data: data,
success: function () {
alert('form was submitted');
}
});
});
update.php
if(isset($_POST["submit"]))
{
print_r($_POST['data']);
// Error::: Undefined index:data in
pass Id using hidden input field and then form data serialize then after you can use by name wise on php page.
$_POST['name'];
Read my comment, then look at this:
JavaScript may look like this
$('#regForm').on('submit', function(e){
var s = location.search.split('&'), serialId = s[s.length-1], idArray = serialId.split('=');
if(idArray.length === 2 && idArray[1].trim() !== '' && idArray[0].match(/^id$/i)){
var serialData = $(this).serialize()+'&'+serialId;
$.ajax({
method:'POST', url:'update.php', dataType:'json', data:serialData},
success:function(jsonObj){
console.log(jsonObj);
}
});
}
e.preventDefault();
});
PHP may look like this
<?php
if($_POST['id']){
// each property as $_POST[propertyHere]
// sending back to JavaScript
$c = new stdClass; $c->someProp = 'some value';
echo json_encode($c); // dataType is json so you should get Object as result
}
?>
Related
I have a PHP page that will return JSON data as output. I get the data as AJAX. I want to display the results from JSON. But when I try to display each value I am getting undefined error.
This is the PHP code for getting data:
if (isset($_POST['dcqid'])) {
$question_id = intval($_POST['dcqid']);
if ($question_id != "") {
$user_id = $session->id;
$questiondetail = getData("dcquestions", "dcqid", "dcqid", $question_id, "", "");
//print_r($questiondetail);
echo json_encode($questiondetail);
?>
}
}
This is the JSON output I am getting
[{"dcqid":"10","current_id":"3","question":"Another Question","answer":"This is another question","description":"This is the description","date":"2017-08-10 11:55:51","active":"1"}]
This is the AJAX code I am using to display data
<script type="text/javascript">
$(".edit-current").on('click', function (e) {
e.preventDefault();
var id = $(this).data('currentid');
alert(id);
var url = "<?php SITE_URL ?>admin/" + "admin_edit_current.php";
var info = 'dcqid=' + id;
$.ajax({
type: "POST",
url: url,
data: info,
success: function (data) {
console.log(data);
console.log(data.dcqid); // undefined
},
error: function (data) {
alert(data.responseText);
alert("Error occured in showing details");
}
})
});
</script>
I am currently getting undefined for the values I want to display.
Its because the data var is an array. it's like this:
data = [
{
dcqid : 123
}
]
so try using
console.log(data[0].dcqid)
1st : Access it like this
console.log(data[0].dcqid);
2nd : Add dataType in ajax
dataType:"json"
Note : your value is inside the 0th index . so you need to access it like above.
var data =[{"dcqid":"10","current_id":"3","question":"Another Question","answer":"This is another question","description":"This is the description","date":"2017-08-10 11:55:51","active":"1"}];
console.log(data[0].dcqid);
I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery
I can't access my variables through ajax using php.
AJAX CODE
$("input[name='absent[]'").change(function() {
var obj = $(this); //checkbox
var valueZero = obj.val();
var Code = obj.attr('data-Code');
var value = obj.attr('data-session');
/*var theTR = $(this).parent('tr').children().find('td:eq(0)').addClass('hidden');*/
/* alert( theTR.text());*/
/*$(this).addClass('hidden');*/
$.ajax({
data: "{ code: '"+ Code +"', abt_prt: "+ valueZero +", InOut: "+ value +" }", // need to access these variables in php
type: "post",
dataType:'json',
url: "insertabsent.php",
success: function(){
obj.addClass('hidden');
}
});
});
PHP CODE
<?php
if(isset($_REQUEST))
{
$code = $_POST['code']; //variable
$absent_present = $_POST['abt_prt']; //variable
$session = $_POST['InOut']; //variable
//need this variables to perform a insert query
}
?>
Do try this :
JAVASCRIPT
var mainString = "code="+Code+"&abt_prt="+valueZero+"&InOut="+value;
IN AJAX
data : mainString
PHP
$code = $_POST['code']; //variable
$absent_present = $_POST['abt_prt']; //variable
$session = $_POST['InOut']; //variable
use data like
data: { code:Code , abt_prt : valueZero , InOut : value },
and in php I don't really know what is $_REQUEST is but you can use
if(isset($_POST)){
}
Try changing data variable to:
data: {"code":Code,"abt_prt":valueZero,"InOut":value},
You are misunderstanding how AJAX parameters have to be sent. You do not need to send an index, you can send a simple Javascript object, like this:
$.ajax({
data: { code: Code, abt_prt: valueZero, InOut:value}, // need to access these variables in php
type: "post",
dataType:'json',
url: "insertabsent.php",
success: function(){
obj.addClass('hidden');
}
});
However, if for some reason you want to send a string like you did, then decode it using json_decode.
I am creating json object but can't access its value in php.I am trying to access json object in php and assign that object to php variable.My js code is
var arr= [];
var data={ "tab" : 'system' };
jObjArr = arr.push(data);
var JSONstr = JSON.stringify(jObjArr);
what i am missing ?
I try to get tab value on that page in php.
Try to pass simple object rather than sending an array:
function send_me() {
//var arr = [];
var data = { "tab": 'system' };
//jObjArr = arr.push(data);
//var JSONstr = JSON.stringify(data);
$.ajax({
url: "a_blank.php",
type:"post",
data: data,
success: function (response) {
alert(response);
}
});
}
On php page side simply get as:
if($_SERVER["REQUEST_METHOD"]=="POST")
{
print_r($_POST['tab']);
die();
}
acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}