Failed saving data from js to php - javascript

I run the following js:
$(".save_post").on("click", function() {
var saveId = $(".my_post_id").attr("data-id");
console.log(saveId);
$.ajax({
url: "save.php",
data: saveId,
dataType: 'json',
type: 'POST',
success: function(json_object) {
console.log(json_object);
$(".save_post").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$(".save_post").text("Failed to save data !");
}
});
});
console.log(saveId); gives 248 which is what I would like to save.
PHP page
$post_data = $_POST['data'];
if (!empty($post_data)) {
$file = fopen('data_save.json', 'w+');
fwrite($file, json_encode($post_data));
fclose($file);
echo json_encode('success');
}
var_dump($post_data);
I get if I go to save.php i get the following and the button text after I click says Failed to save data !
Null

Made it work by removing dataType: 'json',

Try this
$(".save_post").on("click", function() {
var saveId = $(".my_post_id").attr("data-id");
console.log(saveId);
$.ajax({
url: "save.php",
data: {saveId:saveId},
dataType: 'json',
type: 'POST',
success: function(json_object) {
console.log(json_object);
$(".save_post").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$(".save_post").text("Failed to save data !");
}
});
});
Data should be passed in ajax like {data:data}

Related

Getting array data from PHP to jQuery for outputting

Here is the partial code from the remove PHP file:
if($action == 'trackings_get') {
$result = $trackings->get(getCourierSlugByID($GLOBALS['tracking_id']), $GLOBALS['tracking_id']);
$result_history = $result['data']['tracking']['checkpoints'];
echo json_encode($result_history);
// debugging
//pretty_print($result_history);
}
Here is the JS from the remote site i am trying to call the data for:
$.ajax({
url: '/login/tracking.php',
type: 'POST',
dataType: "json",
data: {
action: action,
tracking_id: tracking_id
},
success: function(json){
//debug
alert(JSON.stringify(json));
}
});
try this
function test(){
$.ajax({
url: 'url',
type: 'POST',
dataType: "json",
data: {
action: action,
tracking_id: tracking_id
},
success: function(json){
}
});
}
i try this code in inspect element in this page https://tracking.ambientlounge.com/
function test(){
$.ajax({
url: 'your url',
type: 'POST',
dataType: "json",
data: {
action: "action",
tracking_id: "tracking_id"
},
success: function(json){
//debug
console.log(json);
}
});
}
result is array . dont need JSON.stringify .

Ajax, failed to load PHP from server

I'm trying to make a PHP connection, but I keep getting this error. I am hoping someone can help.
My code gives the following error:
{
"readyState": 0,
"status": 0,
"statusText": "NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost/php/busca.php'."
}
My code is:
SendSQL.onclick = function() {
var dataString='a=hello&b=world';
$.ajax({
type: "POST",
url:"http://localhost/php/busca.php",
data: dataString,
async: false,
dataType:'html',
success: function(data){
alert(data);
},
error: function(data){
alert(JSON.stringify(data)); //Better diagnostics
}
});
};
And the file busca.php is:
<?php
$a = $_POST['a'];
$b = $_POST['b'];
echo "$a, $b";
?>
Try this approach...
SendSQL.onclick = function() {
var dataString='a=hello&b=world';
$.ajax({
type: "POST",
url:"http://localhost/php/busca.php",
data: {
"a":"hello",
"b":"world"
},
async: false,
dataType:'text',
success: function(data){
alert(data);
},
error: function(data){
console.log(data);
}
});
};
Your dataString is the way for sending parameter of GET request.
Let's change to JSON like
var dataString = { "a":"hello", "b":"world" };
$.ajax({
type: "POST",
url:"http://localhost/php/busca.php",
data: {data: JSON.stringify(dataString)},
async: false,
dataType:'json',
success: function(data){
alert(data);
},
error: function(data){
alert(JSON.stringify(data)); //Better diagnostics
}
});
And in php code, use json_decode($_POST['data'])

jQuery AJAX POST not passing data to a PHP script

So i have this jQuery:
$("#dropbin").droppable(
{
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
data: noteid,
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
and that includes this url: url: 'deleteNote.php',
in deleteNote.php:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid']))
{
// $noteid2 = $_POST['noteid1'];
echo "You finally hit this bit, congratulations...";
// $stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
// $params = $noteid2;
// $stmt = sqlsrv_query($conn, $stmt, $params);
// if ($stmt === false)
// {
// die( print_r(sqlsrv_errors(), true));
// }
}
else
{
echo "No Data";
}
?>
Now even in the URL if i run /deleteNote.php?noteid=25 it hits the "No Data" part of my PHP.
When i run in debugger it populates the variable noteid with a NoteID so that bit is working but the PHP file is saying its not set?
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");
}
});

why ajax post method return empty alert box when i tried to return data from controller file in codeigniter

This is my ajax function
$(function(){
$("#myform").submit(function(){ //i want to get data from my form after submittingit
dataString = $("#myform").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
success: function(data){
alert(data);
}
});
return false;
});
});
this is my controller class function
function viewCustomerData(){
if($_POST){
$name = $_POST['name'];
return 'name';
}
else {
return false;
}
}
other thing is i tried to alert data string taken from form serialize, but it also empty. I want to return data set from database after sending key word from javascript file. i tried if the javascript file connect correctly with my controller function. so i tried to return some value and display it using alert box. but it gives empty result.
This is better way to submit a form with ajax
$(document).on("submit", "#myform", function(event)
{
event.preventDefault();
$.ajax({
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData"
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
alert(data);
},
error: function (xhr, desc, err)
{
}
});
});
try this
$(function(){
$("#myform").submit(function(){
dataString = $("#myform").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
cache: false,
datatype: 'json',
success: function(data){
alert(data.result);
}
});
});
});
in controller
function viewCustomerData(){
if($this->input->post('name'){
$result = $this->input->post('name');
} else {
$result = false;
}
header('Content-Type: application/json');
echo json_encode(array('result' => $result));
}
you cant alert $("#myform").serialize(); because this is an object instead of alert it try console.log($("#myform").serialize();)
then open browser console and see what is printed
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data);
}
});

How can i redirect page JavaScript/PHP?

I want to redirect page to URL that return from PHP script.
That when user created a post i want to return value of mysql_insert_id() for post_id.
$('input#submitButton').click( function() {
$.ajax({
url: 'newpost.php',
type: 'post',
dataType: 'json',
data: $('form#myForm').serialize(),
success: function(data) {
window.location.replace("http://localhost/?post_id=...");
}
});
});
I looked here but not found what i want.
Link
In your php script do :
echo json_encode(array(
'id' => $THE_ID
));
then here do:
$('input#submitButton').click( function() {
$.ajax({
url: 'newpost.php',
type: 'post',
dataType: 'json',
data: $('form#myForm').serialize(),
success: function(data) {
window.location = "http://localhost/?post_id=" + data.id;
}
});
});
});

Categories

Resources