Passing JQuery var to PHP using AJAX [duplicate] - javascript

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
I'm trying to pass 3 variables that look like this
var location = document.location.pathname;
var search = document.location.search;
var referrer = document.referrer;
Into a PHP file that I can eventually use to send emails, I have never used AJAX before but know that you could use it to achieve this.
Can anyone help me out? Thanks in advance.

A simple Ajax POST method can help you here. Here's an example.
$.ajax({
type: "POST",
url: "ajax.php",
data: {location: location, search: search, referrer: referrer},
success: function(response){
//do something
}
})//ajax end
Now in ajax.php, you can receive the values via $_POST.
PHP Receiving(ajax.php).
var_dump($_POST['location']);

You could do like this:
$.ajax({
type: "POST",
data: {'location': location,
'search': search,
'referrer': referrer
},
url: "Here the path to your php-file",
success: function (data) {
Here you could react on any
}
});
In the php file you receive those data by Post and can handle them.

Related

Ajax post issue with smarty

I have script using smarty engine.
I just tried to use ajax post to get some data from page.
The javascript function as following:
function getTime(val,id) {
$.ajax({
type: "POST",
url: '{$GLOBALS.site_url}/check_time/',
data:'GetDate='+val + '&Jobid='+id,
success: function(data){
alert(data);
}
});
}
the alert show me (3 small squares) I don't know what dose mean !

Send Form Data containing inputs and files with JQuery & AJAX to PHP Web Service [duplicate]

This question already has answers here:
File Upload via AJAX within JQuery
(5 answers)
Closed 7 years ago.
I'm trying to send all data from my form with Jquery and Ajax to a PHP REST webservice.
JS
$("#idform").submit(function(event) {
/* Stop form from submitting normally */
event.preventDefault();
//Get Data
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method');
/* Send the data using post and put the results in a div */
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
dataType: "json",
//processData: false, // tell jQuery not to process the data
//contentType: false // tell jQuery not to set contentType
success: function(res){
if (res.result == '0') {
$("#idform").html('<div class="text-lg">Good Job!</div>');
} else {
//$("#respuesta").html('Error:');
$("#respuesta").html(res.message);
}
},
error:function(res){
$("#respuesta").html('Error comunicating webservice');
}
});
});
PHP
I'm doing something like this with files:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$fileuploaded = $_FILES['fileuploaded']['tmp_name'];
$destinationpath = $_SERVER['DOCUMENT_ROOT']."/path/".$_FILES['fileuploaded']['name'];
move_uploaded_file($fileuploaded, $destinationpath);}
Everythings go ok when I make POST from form directly to php file but not when I'm trying to send data with ajax. PHP web service recieves all inputs but no my two files :(
Sorry for bad written english!
I think you have to use the JS like this
JS
$.ajax({
url: "web_service.php",
data:'value1=1&value2='+$("#num").html()+'&value3=G',
cache: false,
async : true,
type: "POST",
....
In doc.php you have the code to connect to web service in PHP and the parameters send in the data line above. The data is an example

Pass a nested object to POST request [duplicate]

This question already has answers here:
Jquery Ajax Posting JSON to webservice
(5 answers)
Closed 8 years ago.
How can I send a nested object via POST request?
var name = "test",
path = "?diffCurr%5B%5D=FALSE&diffProv%5B%5D=FALSE",
data = {
datatype:"report",
"value":{
"name":name,
"query":path
}
};
$.ajax({
type:"POST",
url: "resources/savedata.html",
data: data,
success: function(data){
...
},
complete: function(){
...
}
})
When I check in the chrome, in the network tab under "form data", I see this:
datatype:report
value[name]:test
value[query]:?diffCurr%5B%5D=FALSE&diffProv%5B%5D=FALSE
Basically, I was expecting $_POST["value"] to contain an object with name and query.
Basically, I was expecting $_POST["value"] to contain an object with name and query.
It does.
You are just looking at the raw data which is encoded in application/x-www-form-urlencoded with PHP's square bracket syntax for complex objects.
When PHP deserializes it to populate $_POST, it will do so in the form you expect.
One of the easiest way is serializing in a Json string your nested object
$.ajax({
type:"POST",
url: "resources/savedata.html",
data: JSON.stringify(data),
success: function(data){
...
},
complete: function(){
...
}

Posting JSON string to PHP page

Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.

Trying to set variable as part of URL in jquery ajax post

So I am trying to do a post using jQuery.ajax instead of an html form. Here is my code:
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/$org_ID',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Here is my problem:
When this was in an html form, the $org_ID that was part of the URL would actually pull the variable and send it as part of the URL. Now that this is in jquery, its just sending $org_ID as text. How can I get this to figure out what the variable, $org_ID is? I tried declaring it in the javascript but I am brand new to jquery/javascript and don't really know what i'm doing.
Thanks!
Are you rendering this in PHP? In that case you need to do:
url: '/groups/dissolve/<?php print $org_ID; ?>'
Otherwise, you need to do something like
var org_id = 'foo';
// or
var org_id = '<?php print $org_id ?>';
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/'+org_ID,
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Unlike PHP, you can't interpolate variables in javascript, you have to concatenate them with the string.
If you're trying to POST a variable (org_id) then you should put it in data:
data['org_id'] = org_id;
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
While you can concatenate params onto your url to send them in an HTTP request, putting them in a data object not only lets jQuery do more work for you & escape HTML entities etc (and keep your code cleaner), but also allows you to easily debug and play around with ajax() settings.
It's not clear in the question where your data comes from, but you can use something like:
url: '/groups/dissolve/'+orgId,
or:
url: '/groups/dissolve/?orgId='+orgId,
Short answer, concatinate
url: '/groups/dissolve/' + $org_ID

Categories