Pass Data from Jquery to PHP for an Ajax Post

Pass data from jQuery to PHP for an ajax post

With jQuery post you can define a callback function which is executed when the data is returned:

$.post('/callcenter/admin/postContacts', data, function(returnedData) {
// do something here with the returnedData
console.log(returnedData);
});

The data should be in the form:

{name: 'value', anotherName: 'another value'}

which equates to the post names on the PHP end accessible in plain PHP like this:

echo $_POST['name'];           # prints "value"
echo $_POST['anotherName']; # print "another value"

How do I pass data to a php file using jquery AJAX

Here is the AJAX that I suggest using

$(document).ready(function(){
$('#save').click(function() {
$.ajax({
url: '../php/preparesave.php',
type: 'POST',
data: { user : 'Tommy' },

success: function(output){
alert(output);
}
});
});
});

And below is the PHP (I tried it on my machine and it works)

$user = $_POST['user'];

if(!file_exists('../users/' . $user . '/Platoons/')){
if(mkdir('../users/' . $user . '/Platoons/', 0777, true)){
die('Success');
}else{
die("Folder `../users/{$user}/Platoons/` failed to be created");
}
}

The way you have it, it will only try to create "/Platoon" in a folder $user (Tommy in your example) but that folder doesn't exist and so the script is failing. You need to set the recursive parameter to true so it would first create the folder that doesn't exist and then everything else inside it and then them.

Allows the creation of nested directories specified in the pathname. (Straight from the docs)

How correctly pass data to php using ajax?

When sending data using a FormData object all information has to be in that object. Therefore you need to append() the value from .code to it, as you do with the file information. Try this:

$(".code_form").on("submit", function(e) {
var formData = new FormData();
formData.append('dota', $(".code").val());

if ($(".upload_img").val() != '') {
formData.append("my_file", $(".upload_img").prop('files')[0]);
}

$.ajax({
type: "POST",
url: "img_proc.php",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function(data) {
$(".user-success-code").html(data);
}
})

e.preventDefault();
});

Pass data from jQuery Ajax to PHP and saving those values in Database

JSON is javascrip object notation you cannot JSON.stringify a variable, it has to be an object. Try this.

var data = {}; //defines that data is a javascript object
//assign your values to there respective indexes
data['a'] = payment;
data['b'] = count_days;
data['c'] = <?php echo $teahcer_id; ?>
//since data is now a object you can json.stringify it
var jsonData = JSON.stringify(data);

//make ajax request with json data
$.ajax({
type: "POST",
url: "student_searching_availibility.php",
data: { data:jsonData },
cache: false,

success: function()
{
alert('success');
}
});

On your PHP, remember that json_decode() expects second parameter the $assoc parameter as a boolean, its default is false which means that if you only specity the json string to be decoded then it will return you data in an object form, for associative array pass true as second parameter.

$data = json_decode($_POST['data']); //$data is now an object
$data->a; //your payment
$data->b; //your count_days

$data = json_decode($_POST['data'],true); //$data is now an associative array
$data[a]; //your payment
$data[c]; //your count_days

when you were inserting into sql $data1, $data2 you were actually trying to store objects into your table, here mysqli_query should have returned false and your code died thus you are not getting any error.

So your sql insert values depending upon your json_decode($_POST['data'], true or false) use either $data->a or $data[a] i.e,

"INSERT INTO availibility_status_date(student_id,teacher_id,status) VALUES  ('$data[a]','$data[b]','$data[c]')";

OR

"INSERT INTO availibility_status_date(student_id,teacher_id,status) VALUES ('$data->a','$data->b','$data->c')";

jQuery AJAX POST not passing data to a PHP script

Let's look in your Ajax call:

$.ajax({
type: 'POST',
data: noteid,
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});

Looks nice, but you are sending post data with no id, you're just sending a value. Try this instead.

  $.ajax({
type: 'POST',
data: {
noteid: noteid
},
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});

Ajax jquery(post) doesn't pass data to php

Updated answer after some live testing with Network tab in firefox web dev tools

The problem is that the current ajax code is not sending any of the elements because of wrong content-type. Let it detect content-type automatically. For jq ajax, default seems to be contentType: application/x-www-form-urlencoded even if you don't provide it specifically.

So, this worked:

<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
// let amount = $("#amount").val();
// let goal = $("#goal_name").val();

var formData = {
amount: $("#amount").val(),
goal_name: $("#goal_name").val(),
};

$.ajax({
method: "post",
url: "target-modal-code.php",
// datatype:"json",
//data:JSON.stringify(formData),
data: formData,
//contentType:"application/json",
//encode: true,
success: function (response){
$("#response").text(response);
// console.log(amount);
// console.log(goal);
console.log(formData);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});

</script>

After little bit of fiddling, I noticed that it works if you DON'T provide it contentType at all. Otherwise, AJAX won't send GET or POST params to the server.... dont know why. I know it's weird but that's how it is in jquery ajax.

I have intentionally kept the comments for you to see what all I have tried.

So to summarize,

  • Don't stringify the form data,
  • Don't provide contentType to ajax
    request.

Cheers.!

jQuery Ajax POST example with PHP

Basic usage of .ajax would look something like this:

HTML:

<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />

<input type="submit" value="Send" />
</form>

jQuery:

// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

// Prevent default posting of form - put here to work in case of errors
event.preventDefault();

// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);

// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");

// Serialize the data in the form
var serializedData = $form.serialize();

// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);

// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});

// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});

// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});

// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});

});

Note: Since jQuery 1.8, .success(), .error() and .complete() are deprecated in favor of .done(), .fail() and .always().

Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a $(document).ready() handler (or use the $() shorthand).

Tip: You can chain the callback handlers like this: $.ajax().done().fail().always();

PHP (that is, form.php):

// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;

Note: Always sanitize posted data, to prevent injections and other malicious code.

You could also use the shorthand .post in place of .ajax in the above JavaScript code:

$.post('/form.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});

Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.

How to pass Data From JQuery AJAX to PHP Without submit

Your data format is wrong ,must be {data-name:data-value}

data: {name: 'ccenter', value: 'Sales Department' } 

So you should call by data-name

$ccenter = $_POST['name'];


Related Topics



Leave a reply



Submit