Jquery Using Ajax to Send Data and Save in PHP

jquery using ajax to send data and save in php

you can use following code :

var form = new FormData($('#form_step4')[0]);
form.append('view_type','addtemplate');
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});

where savedata.php is the file name in which you can do the the DB things

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

checkbox jquery using ajax to send data and save in php not inserting

You are sending all checkbox value but , i think you need to only send checkbox which is checked so use :checked then you have use $( ".get_value" ).serialize() this is targetting all class that's why you are seeing mutliple insert instead change that to $(this).serialize() . I have added other way as well instead of sending checkbox ony by one you can use $(this).closest("form").serialize() to send whole form datas at onces.

Demo Code :

$('#chk1').click(function(e) {
e.preventDefault()

//send only input which is checked
$('input[type=checkbox]:checked').each(function() {
console.log($(this).serialize())
//use `this` here,,
$.post('fee_checked_save.php', $(this).serialize(), function(data) {
if (data == 1) {
$('#result').html(data);
}
});
});
});

//prefer way :
$('#chk1').click(function(e) {
e.preventDefault()
console.log("from second way.." + $(this).closest("form").serialize())
$.post('fee_checked_save.php', $(this).closest("form").serialize(), function(data) {
//some codes
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="chkl" id="chkl" method="post">

<input type="checkbox" class="get_value" name="chk1[]" value="1">  Soemthings..
<input type="checkbox" class="get_value" name="chk1[]" value="2">  Soemthings..

<input type="submit" name="Submit" id="chk1" value="Submit">
</form>

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.

Save Current DOM to file on server using PHP, Ajax, jQuery?

Solved it! Here was the solution for me to click a save button, return the html code of a particular element and prevent the page from refreshing:

AJAX

var url = '/savefile.php';
function chk() {
var elHtml = document.getElementById('outer-content').innerHTML;
console.log("inside chk");
$.ajax({
type: "POST",
url: url,
data: {myCode: elHtml },
success: function (obj) {
console.log("success outer");
$('#msg').html(obj);
console.log("success");
}
});
console.log(url);
return false;
}

PHP

          $html_val = $_POST[ 'myCode' ];

var_dump($html_val);

It was actually a lot simpler than I thought.

Save Data to File via Ajax POST and PHP

Few things could be going wrong here. Check the permissions on the directory your are trying to write to. Also make sure that your ajax call is using the POST method.

$.ajax({
url: "page.php",
type : 'POST',
...
});

As sated in the jQuery documentation, the type parameter sets the request type, POST or GET.

The type of request to make ("POST" or "GET"), default is "GET".


Another thing to consider is that you are not actually writing JSON data. The data is send in that format but when it gets to the $_POST variable it has been converted into an array. What you should try doing is writing a PHP array to the file -

$fh = fopen($myFile, 'w');
fwrite($fh,'<?php $arr='.var_export($_POST['data'],true).' ?>');
fclose($fh);

That should give a file similar to this -

<?php
$arr = array(
'foo'=>'bar'
)
?>

As you can see, the var_export() function returns a parsable version of the variable.

  • var_export()

var_export — Outputs or returns a parsable string representation of a variable

Upload and save to database with php and jquery ajax

<input type="file" class="file">

$(".file").on("change",function(){
var file = new FormData();
file.append('file',$('.file')[0].files[0]);
$.ajax({
url: "upload.php",
type: "POST",
data: file,
processData: false,
contentType: false,
beforeSend:function(){
$(".result").text("Loading ...");
},
success:function(data){
$(".result").html(data);
}
});

<div class="result"></div>

in upload.php

<?php
include("database.php");
$name = $_FILES["file"]["name"];
if(move_uploaded_file($_FILES["file"]["tmp_name"], "DESTINATION/".$name)){
// insert to data base
echo '<img src="DESTINATION/'.$name.'">';
}
?>


Related Topics



Leave a reply



Submit