Store on PHP variables sent by Ajax - javascript

I am creating a DDBB Insert trough $.ajax:
$(document).on('click','.submitMessage', function(){
content=$('textarea').val();
img=$('#messageImg').val();
stdMsg=$('.ms_stdMsg').val();
prefix=$('.prefix').val();
phone=$('.cuadroTelefono').val();
$.ajax({
url: "../actions/newMessage.php",
type: "POST",
data:{ms_content:content, ms_img:img,ms_prefix:prefix,ms_phone:phone},
contentType: false,
cache: false,
processData:false,
success: function(data)
{
alert("Enviado");
}
});
});
And this is the way I receive code on newMessage.php:
$ms_content = $_POST['ms_content'];
$ms_img = $_POST['ms_img'];
$ms_prefix = $_POST['ms_prefix'];
$ms_phone = $_POST['ms_phone'];
Console gives an error
Notice: Undefined index: ms_content in C:...\newMessage.php on line 9
one for each variable passed (I have ommited entire URL)
As the posted information is an object, I guess I must decode it someway on PHP, but trying:
$ms_content = json_decode($_POST['ms_content']);
...has neither workd

You need to specify the data that you are sending with contentType parameter. For more references

$(document).on('click','.submitMessage', function(){
content=$('textarea').val();
img=$('#messageImg').val();
stdMsg=$('.ms_stdMsg').val();
prefix=$('.prefix').val();
phone=$('.cuadroTelefono').val();
$.ajax({
url: "../actions/newMessage.php",
type: "POST",
data:{ms_content:content, ms_img:img,ms_prefix:prefix,ms_phone:phone},
cache: false,
success: function(data)
{
alert("Enviado");
}
});
});
Please remove processData:false, contentType: false and then try.

You can use this $_REQUEST instead of $_POST in your php file.
$ms_content = $_REQUEST['ms_content'];
Instead of
$ms_content = $_POST['ms_content'];
Second Maybe due to url path
try giving full url path.
Third
Provide a contentType.

I think you have to access the $_GET parameters because jquery documentation says:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
http://api.jquery.com/jquery.ajax/
So you will get your data with
$ms_img = $_GET['ms_img'];

Related

Pass object value to controller using Ajax GET

$.ajax({
url: "/Course/GetChapters/",
type: "GET",
data:{id:2},
beforeSend: function () { },
success: function (result) {}
})
.done(function () {});
Can i pass a complex object via data?
JQuery Ajax - Documentation
Data -> Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So as long as you have simple name/value pairs it should work. Of course the length of the URL is limited to 2,083 characters.
try this:
var data = 'param1=' + value+ '&param2=' + value;
OR
var data = '{param1:'val1',param2:'val2',}'.

sending an ajax GET with a javascript response format

I am trying to do the following
$("select.languages").on("change", function(){
var lang = $(this).find("option:selected").text();
$.get(url: "/search",
data: {"lang": lang},
dataType: 'script');
});
so every time a language is selected I would call /search with the language and by other SO answers to make dataType be "script"
but this doesn't quite work. What does work is
$.get( "/search.js",{"lang": lang} )
yet this pollutes the url since the format is very explicit and doing using this method requires me to add extra pointless code
can I implicitly set the response format?
Try this instead:
$.ajax({
url: "/search",
data: {"lang": lang},
dataType: 'script'
});
The get shorthand method does not accept the parameters as an object like this.
Probably a syntax error - I would try this:
$("select.languages").on("change", function(){
var lang = $(this).find("option:selected").text();
$.ajax({
url: "/search",
data: {"lang": lang}
});
});
Since you're trying to send a JS request, you probably won't even need the dataType property, as Ajax expects it by default:
$.ajax - dataType

Serialize the data from 3rd party API in javascript/jQuery

I want to do a serialize the data that I got from 3rd Party API. The following Picture is what I got from the API
As you can see in the photo, I have received 2 sets of the Information which indicated by the number in the []. And when I do the POST request using jQuery, the multiple Parameters Posts to my Java method. What I would like to do is to encapsulate each set ot the Information into a Group and after that serialize them in one parameter and sent it back as one object that hold all the things inside.
How can I do it by Javascrip or jQuery???
anyway, this is my code
function getMediaInfo(InkBlob){
console.log(InkBlob);
jQuery.ajax({
type: 'POST',
url: '/webapp/filepicker/importAssets',
dataType: 'json',
data: {"inkBlob": InkBlob}
}); }
All I want to do is to set only one parameter call inkBlob that contains the Information as Show in the photo above.
How about -
For Serializing js object
var str = JSON.stringify(InkBlob);
jQuery.ajax({
type: 'POST',
url: '/webapp/filepicker/importAssets',
dataType: 'json',
data: {"inkBlob": str}
});
Note
JSON.stringify is not available for older browser, use JSON2.js for older browsers.

passing json array ajax

Trying to pass a array using ajax call.
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info: info, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
However when i try to catch it on the server side using :
request.getParameter("info"); //Displays null**
Also, if i wish to send an array of arrays ? is it possible?
I tried using serialize however my IE throws error that serialize : object doesnt support this property i Did include jquery lib.
You can use JSON.stringify(info) to create a JSON representation of the object/array (including an array of arrays). On the server side you should be able to get the string via getParameter and then unserialize it from JSON to create constructs JSP can use.
Yes,It is Possible to send arrays.
var info_to_send = ['hi','hello'];
$.ajax({
type: "POST",
data: {info: info_to_send, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
You can only provide strings in a request url.
You could encode the array like so:
info = JSON.stringify(info);
// results in "['hi', 'hello']"
Then send it to the server, also JSON parse on the server.
You will need to go to http://www.json.org/ to get a Java implementation of JSON parsing.

javascript object to php

i'm trying to send an js object to a php function using jquery.ajax.
This is what i have so far:
js side:
$.ajax({
type: "GET",
dataType: "json",
url: url,
data: {persoon : persoon2},
async: false,
success: function(){
alert(data);
return true;
}
});
php side:
$decode = json_decode($_GET["persoon"]);
$verzekering->setVoornaam($decode->persoon_voornaam);
in js this works: persoon2.persoon_voornaam
but i can't get to the value in php, what am i doing wrong?
few fixes
data: "persoon=persoon2", // check input format
success: function(data) { // missing data argument
EDIT your ajax code is working (check URL or php code)
http://jsfiddle.net/ish1301/KZndE/
Found the problem(s)
I was using this inside Drupal and the Jquery version was still 1.2.6. Upgrading it resolved a lot of the problems
The string i tried to catch with the $_GET["persoon"] was mall formated becaus i just send along a js object. Changing
data: {persoon : persoon2},
to
data: {persoon:JSON.stringify(persoon2)},
fixed the problem

Categories

Resources