newbie ajax and php get parameters - javascript

I need help to do something small but I don't know how to solve it.
I have a javascript file with ajax inside like this
$.ajax({
data: "mc_id="+someid,
url: "includes/getDataPrs.php",
type: "GET",
dataType: "json",
async: false,
success: function(msg){
//some function here
}
});
in getDataPrs.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
header('Content-Type: application/json');
$id = null;
$date = null;
$limit = 0;
if (isset($_GET['mc_id'])) {
$id = $_GET['mc_id'];
}
//some process here $data
echo json_encode($data);
I can get data from $_GET['mc_id'] but when I need more data and I change the parameters in javascript like this
$.ajax({
data: "{'mc_id':'"+someid+"','limit':'"+somelimit+"'}",
url: "includes/getDataPrs.php",
and then I got nothing in php $_GET['mc_id'] or $_GET['limit']
in my desperate to solve it, I put in url "includes/getDataPrs.php?mc_id=someid&limit=somelimit
any comment or suggestion I truly appreciated
thanks in advance

passing multiple variable in ajax should be like
$.ajax({
data: {mc_id: someid, limit: some_limit},
url: "includes/getDataPrs.php",
type: "GET",
dataType: "json",
async: false,
success: function(msg){
//some function here
}
});
It is always better to use data: {mc_id: someid, limit: some_limit} because it will treated like object itself.

Try using following syntax for sending data in ajax function:
...
data:{mc_id:someid,limit:somelimit},
...
Without using quotes.

Change from
data: "{'mc_id':'"+someid+"','limit':'"+somelimit+"'}",
To
data: "mc_id="+someid+"&limit="+somelimit,

Follow the below steps:
1) Replace `data: "mc_id="+someid,` with `data: { mc_id: someid},`. (required)
2) Now you can get your data in PHP file like `$_POST['mc_id']` (optional). It is better to use `type: 'POST'`in your jQuery code.
So below is your whole code:
$.ajax({
data: { mc_id: someid},
url: "includes/getDataPrs.php",
type: 'POST',
dataType: "json",
async: false,
success: function(msg){
//some function here
}});
in getDataPrs.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
header('Content-Type: application/json');
$id = null;
$date = null;
$limit = 0;
if (isset($_POST['mc_id'])) {
$id = $_POST['mc_id'];
}
//some process here $data
echo json_encode($data);
?>

You try this
$.ajax({
type: "POST",
url: "includes/getDataPrs.php",
data: {'mc_id': someid, 'limit': somelimit}.done(function (response) {
//
});
});

Related

How to send multiple data fields via Ajax to php page?

i have a problem, I want to send 2 posts to my author php page by using ajax
thats my code :
$.ajax({
type: "POST",
url: "includes/get_competitions.php",
data:'sport=<?php echo $_GET['sports']; ?>',
success: function(data){
$("#competitions-list").html(data);
}
and this what i want to do :
$.ajax({
type: "POST",
url: "includes/get_competitions.php",
data:'sport1=<?php echo $_GET['sports1']; ?>, sport2=<?php echo $_GET['sports2']; ?>',
success: function(data){
$("#competitions-list").html(data);
}
but it didn't work
Multiple parameters in a data string are separated by &, not , (it's just like the syntax of parameters in a URL).
However, if you're using jQuery it's best to use an object. $.ajax will automatically convert it to the properly encoded query string. And you can use json_encode() to convert a PHP value to the corresponding JavaScript literal.
$.ajax({
type: "POST",
url: "includes/get_competitions.php",
data: {
sport1: <?php echo json_encode($_GET['sports1']); ?>,
sport2: <?php echo json_encode($_GET['sports2']); ?>
},
success: function(data){
$("#competitions-list").html(data);
}
You could also make a single sports array, rather than numbering the parameters.
$.ajax({
type: "POST",
url: "includes/get_competitions.php",
data: {
sports: [<?php echo json_encode($_GET['sports1']); ?>,
<?php echo json_encode($_GET['sports2']); ?>]
},
success: function(data){
$("#competitions-list").html(data);
}
Then in get_competitions.php, $_POST['sports'] will be an array.
You can try this
data: $('#myForm').serialize() <---- your form name
This will send all the form data

Get data from a different php file using JQuery

I have an JQuery function which submits data from a php form to a different php file(submitForm.php). The submission works fine and there isn't any problem whatsoever, below is the handler:
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
success: function(data) {
}
});
}
Now, I want to be able get data from the submit form (submitForm.php), and load it into a different page.
This is my submitForm.php
<?php
$name="Amanda";
$age="23";
$data = array("name"=>"$name","age"=>"$age");
header("Content-Type: application/json");
echo json_encode($data);
?>
This is how my new submitHandler looks like
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
success: function(data) {
var name= html(name);
var age=html(age);
$("#message").load("newpage.php",{name:name,age:age});
}
});
}
I think I am doing it wrong, I would be grateful if somebody could correct me or give an idea as to how to do this. Thanks
It should be like this. If you want to take your returner data you should use formal parameter of success function.
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
dataType : 'json',
success: function(data) {
var name= data.name;
var age=data.age;
$("#message").load("newpage.php",{name:name,age:age});
}
});
}
Edit: Also you need dataType: 'json' line.

Ajax response undefined or strange

i'm trying to send an array to JS, but i can't have the answer i want.
this is my PHP code:
$output = array('total'=>(float)$BHoras[1]'gastas'=>(float)$BHoras[2]);
echo json_encode($output);
and this is my JS code:
function ProjectSelect()
{
var proj = document.getElementById('ProjetosSelect').value;
$.ajax({
url: 'CRM files/TSread.php',
type: "POST",
data: ({ProjetosSelect: proj}),
complete:function(data)
{
var Horas = data.responseText;
alert(Horas); // response -> {"total":146,"gastas":84.5}
alert(Horas[3]); // response -> o
}
});
}
i only want the "146" and "84.5".
i tried to do, alert(Horas['total']), alert(Horas.total), but give me undefined
Just specify dataType: "json" and jQuery will parse response for you:
function ProjectSelect()
{
var proj = $('#ProjetosSelect').val();
$.ajax({
url: 'CRM files/TSread.php',
type: "POST",
data: ({ProjetosSelect: proj}),
dataType: "json",
success: function(Horas)
{
alert(Horas.total);
}
});
}
On server side you could try TracKer note. And you can add a header too.
<?php
$output = array('total'=>(float)$BHoras[1], 'gastas'=>(float)$BHoras[2]);
header('Content-type: application/json');
echo json_encode($output);

JS array send to php is returning as empty [duplicate]

Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);

Issue with decoding json array in php

Okay now i am having a weird issue here, sometime back i learned how to encode and decode a json array properly here on stackoverflow but now i am having a weird issue on my godaddy server that i cannot comprehend, maybe i may have made i typo or something somewhere in code but i honestly cannot tell what is wrong here. The code works okay on my localhost but not when i upload it too my godaddy server.
The code here is basically supposed to pass an id as a json to the php server which is then supposed to execute a query using the id as a parameter.
Here is the jquery code:
<script text="text/javascript">
$(document).ready(function() {
$('#download').click(function(e) {
// e.preventDefault();
var tid = $('#id').val().trim();
var data = {
ID:tid
};
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(response) {
}
});
});
});
</script>
and this is the php code:
<?php
if (isset($_POST['data']))
{
$Data = $_POST["data"];
$arr = json_decode($Data);
$id = $arr->ID;
$sql = $pdo->prepare("update ********** set ******** = ******** + 1 where id=:id");
$sql->bindValue("id", $id, PDO::PARAM_INT);
$sql->execute();
unset($_POST['data']);
}
?>
Now i checked if the value was being sent to the server using my browser console and it was. I also checked if the $_POST['data'] on the server contained any data using var_dump and it did in fact have the data i wanted.
in the ajax set the content type to contentType: "application/json",
so:
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
contentType: "application/json",
success: function(response) {
}
});
and in the php use:
$json = file_get_contents('php://input');
$data = json_decode($json);

Categories

Resources