Please how can I send a whole number like twelve to php using ajax. I have been able to send string variables using both GET and POST methods successfully, but when it comes to numerical values it becomes a problem , I don't know why.below is my jQuery
function user_ajax_call(){
var data = $(".people_names").length;
var more_loader = $("<img id='hiddenL' src='../ForePost/icons/spin.gif'/>");
$("#pple").append(more_loader);
$.ajax({
url: 'http://localhost/Forepost/mod/loadmore_data.php',
dataType: 'text',
type: 'POST',
data:{data:data},
processData: false,
contentType: false,
cache:false,
success: function(returndata){
$("#pple").append(returndata);
more_loader.hide();
},
error: function () {
}
});
}
And these are sample php lines
$limistart = $_POST['data'];
if(isset($limistart)){
echo $limistart;
}
You need to send them through: data.
You could do something like this in your data variable:
data = {
name_length : $(".people_names").length,
number : 12
};
And just pass it like this in your ajax:
function user_ajax_call(){
var data = {
name_length : $(".people_names").length,
number : 12
};
var more_loader = $("<img id='hiddenL' src='../ForePost/icons/spin.gif'/>");
$("#pple").append(more_loader);
$.ajax({
url: 'http://localhost/Forepost/mod/loadmore_data.php',
dataType: 'text',
type: 'POST',
data: data,
success: function(returndata){
$("#pple").append(returndata);
more_loader.hide();
},
error: function () {
}
});
}
And in your server side access it like :
$_POST['name_length']
$_POST['number']
If you change the value of contentType key it should work correctly.
So change this:
contentType: false
to:
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
EDIT:
and change the line:
processData: false
to:
processData: true
Related
I am trying to send a CKeditor value post with ajax but i cant response anyway! I cant find anything
function send_days(tourId){
var url = baseUrl + "tour/save_days/" + tourId;
var value = CKEDITOR.instances.tour_textarea_days.getData();
$.ajax({
url: url,
method: "POST",
data: dataString,
contentType: false,
processData: false,
cache:false,
success: function (data) {
$('.tour_popup_container').html(data);
}
});
}
but when i chance ajax method like this. It is succesfull
$.post(url, {data:value}, function (response) {
$('.tour_popup_container').html(response);
})
here is my codeigniter php file (it is not important actually)
public function save_days($tourId)
{
$value=$this->input->post("data");
print_r($value);
}
It looks like you used dataString instead of value.
var url = baseUrl + "tour/save_days/" + tourId;
var value = CKEDITOR.instances.tour_textarea_days.getData();
$.ajax({
url: url,
method: "POST",
data: value /*dataString*/,
contentType: false,
processData: false,
cache:false,
success: function (data) {
$('.tour_popup_container').html(data);
}
});
I believe I am making a very basic mistake somewhere.
I have a Form I want to transmit to a PHP page. I also want to send a parameter with that information so I have created a basic 2D array:
$fd['api'] -> contaning the parameter as a string
$fd['body'] -> containing the form data
I am struggling to transmit this array "$fd" as a json string and believe I am using the javascript syntax incorrectly somewhere as I do not often use Javascript.
Any Help would be appreciated.
function admin_statistics_form_send(){
var fd = []
fd['api'] = "refresh_all"
fd['body'] = new FormData(document.getElementById("admin_statistics_form"))
var jsonstring = fd
console.log(jsonstring)
$.ajax({
async: true,
beforeSend: function(){
},
url: "admin_statistics_api.php",
type: "POST",
data: jsonstring,
dataType: "json",
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data)
},
error: function(data) {
console.log(data)
}
})
}
You only want to send the FormData object. To add other key/value pairs you append to that object:
function admin_statistics_form_send(){
var fd = new FormData($("#admin_statistics_form")[0]);
fd.append('api',"refresh_all");
$.ajax({
//async: true, // redundant since it is default and should never use `false`
beforeSend: function(){
},
url: "admin_statistics_api.php",
type: "POST",
data: fd,
dataType: "json",
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data)
},
error: function(data) {
console.log(data)
}
})
}
I have a variable which contains data, i'm then using a ajax function to send this variable data to this php file. I'm slightly unsure I can store this variable into php and echo it out. This is the code that I currently have...
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: data,
success: function(data) {
alert ( data );
}
});
This is my php code
$noteone = $_POST['data'];
echo $noteone;
Any help would greatly be appreciated
data of your ajax call should be like below. Hope it will solve your problem.
data: { "data": data }
You also need to set the data type:
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: { "data": data },
dataType: "json", // <---- THIS ONE
success: function(data) {
alert ( data );
}
});
Try this :
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: JSON.stringify(data),
contentType: "application/json",
success: function(data) {
alert ( data );
}
});
PHP requires data to be submitted in key=value format when building $_POST/$_GET. You didn't do that. You only submitted value, so PHP has no key to populate $_POST with. You need to have:
data: { "whatever_you_want": data }
which becomes
$_POST['whatever_you_want']
I have a dropdown that has a list of ID's in it. The customer will select one and it will reflect a price total on the page. Im creating an ajax call that will update the total when a different ID is pulled from the Dropdown.
$("#BrandId").on('focus', function () {
// Store the current value on focus and on change
previous = this.value;
}).change(function () {
alert("Previous: " +previous);
sel = this.value;
alert("Selected: " +sel);
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetBrandCost", "Shocks")',
data: JSON.stringify({ idp: previous, id: sel }),
dataType: "json",
aysnc: false,
success: function (data1) {
alert(data1);
//ShockTotal = $("#ShockTotal").html();
//ShockTotal = ShockTotal / 1;
////ShockTotal = ShockTotal - data1;
//$("#ShockTotal").html(data1);
}
});
});
The alerts are working perfectly but the ajax isnt passing those ID's into the controller, the controller is just receiving nulls.
public decimal GetBrandCost(string idp, string id)
{
decimal costp = 0;
decimal cost = 0;
if (id == "" || id == null || idp == "" || idp == null)
{
return 0;
}
ShockBrand brandp = db.ShockBrands.Find(idp);
costp = brandp.Cost;
ShockBrand brand = db.ShockBrands.Find(id);
cost = brand.Cost;
cost = cost - costp;
return cost;
}
Since they are null I am hitting my if statement and just returning zero inside the success. Most of the things I read were to add the content type but that didnt seem to help in my case, Im sure it is something little.
From browser console, this
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: JSON.stringify({ idp: 1, id: 2 }),
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns request to http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799, which is incorrect
and without stringify
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: { idp: 1, id: 2 },
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns http://google.com/?idp=1&id=2&_=1440696381239 (see Network tab)
So don't use JSON.stringify
Why it's gonna work - your asp.net controller action receives simple typed parameters (string, numbers, etc) and jquery is fairly enought smart to determine what are going to send, if it was object inside object it will send it as POST data for POST, and string represenation of object for GET (you have GET request, but for purpose of knowledge, just stick with 2 types of data that can be send, params & data) So when jquery configures url, asp.net understands conventions, and matches request to approciated action
But Don't believe me, check it yourself
chrome dev console is your friend
By removing the
contentType: "application/json; charset=utf-8
and
dataType: "json"
it worked for me. Otherwise, I was always getting value = null in the controller action.
My code for calling ajax with data is now:
$(function () {
$.noConflict();
$.ajax({
type: "POST",
url: "../Case/AjaxMethodForUpdate",
data: {typ: $('#typeID').val()},
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
You can just put it like
var dataReq={ idp: previous, id: sel };
data: dataReq
And no need to use dataType and contentType.
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);