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

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

Related

Get content with ampersand through javascript

I have an editable table cell
<td class="center" contenteditable="true" onblur="saveToDB(this, 'docTitle', '<?= $row->id; ?>')"><?= $row->docTitle ?></td>
and here the function
function saveToDB(editableObj,column,id) {
$(editableObj).css("background","#B2DDF2 url(../img/AjaxLoader.gif) no-repeat right");
$.ajax({
url: "<?php echo base_url();?>documents/inline_update",
type: "POST",
data:'column='+column+'&editval='+editableObj.textContent+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
Whenever user enter data with an ampersand (Eg. Forms & Format), only Forms will be inserted into database.
I have tried innerText but still get the same result.
What are the options to achieve this without escape / encode ampersand?
You can just provide an object as data and jQuery will take care of proper serialization and escaping for you (it will use utility $.param internally which will apply escaping to data values):
$.ajax({
url: "/",
type: "POST",
data: {
column: column,
editval: editableObj.textContent,
id: id,
},
success: function (data) { },
});

newbie ajax and php get parameters

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

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

Retrieve JSON from javascript to php (OpenCart controller)

There is a nice JSON object in console.log, but can't seem to retrieve it in controller.
function checkOut(data) {
$.ajax({
url: 'index.php?route=sale/customer/checkout&token=<?php echo $token; ?>&customer_id=<?php echo $customer_id; ?>&products=' + data,
type: 'post',
dataType: 'html',
data: 'products=' + encodeURIComponent(data),
cache: false,
beforeSend: function() {
$('.success, .warning').remove();
$('#button-checkout').attr('disabled', true);
$('#checkout').before('<div class="attention"><img src="view/image/loading.gif" alt="" /> <?php echo $text_wait; ?></div>');
},
complete: function() {
$('#button-checkout').attr('disabled', false);
$('.attention').remove();
},
success: function(html) {
console.log(data);
$('#checkout').html(html);
}
});
}
Sending data via get only seems to send a string, [object Object].
Change the dataType to json and all the html in result page disappears.
Experimented with $.parseJSON(data);, which returns null value in console.log.
What's the method to retrieve the data object so it can be json_decode($data, TRUE)d and available as a php array?
Try This
$.ajax({
url: 'index.php?route=sale/customer/checkout&token=<?php echo $token; ?>&customer_id=<?php echo $customer_id; ?>',
type: 'post',
dataType: 'json',
data: {
products: data
},
success: function (data) {
alert(data);
}
});

Sending Multidimentional array data, with ajax, to a php script

I have two simple scripts. One client-side jquery that has multidim array & a server-side php script. in php $data stays empty.
jquery
console.log("IN JQUERY");
console.log(inps);
$.ajax({
type: 'post',
cache: false,
url: './gen.php',
data: inps,
success: function(response){
console.log("RESPONSE");
console.log(response);
}
});
gen.php
<?php
$data = file_get_contents('php://input');
$data = json_decode($data, true);
print_r($data);
?>
firefox console output
>POST ..././gen.php [HTTP/1.1 200 OK 1ms]
>"IN JQUERY"
>{isbranch: "1", ismanager: "0", isdept: "1"}
>"RESPONSE"
>""
Is there a way to send Multi Dimensional array to the php with ajax without spliting array?
You should use JSON.stringify to encode your data before send it, also better to add correct contentType to it:
$.ajax({
type: 'post',
cache: false,
url: '/gen.php',
data: JSON.stringify(inps),
contentType: 'application/json',
success: function(response){
console.log("RESPONSE");
console.log(response);
}
});
The key-value pairs should already exist in your $_POST
$isbranch = $_POST['isbranch'];
$ismanager = $_POST['ismanager'];
$isdept = $_POST['isdept'];

Categories

Resources