Set a mysql table to Javascript variable using AJAX - javascript

I have a mysql table with 'user_name' and 'user_round'. I want the 'user_round' to be set to whatever the value of 'Level' (this is a javascript variable). My code brings up errors like POST 404 not found. Here is what I have:
<script type="text/javascript" src="jQuery.js"></script>
var <?php echo $_SESSION['user_name']; ?>; //Without this I get username not defined error?
var Level = 1;
function Fail() {
$.ajax({
type: "POST",
url: "phpfiles/savestage.php",
data: {
name: '<?php echo $_SESSION['user_name']; ?>',
stage: Level
},
success: function() {
console.log("Finished uploading stage");
}
});
Here is my php page:
<?php
include 'connect.php';
$sql="INSERT INTO DB NAME (user_round, user_name) VALUES ('$stage', '$name')";
$result = mysql_query($sql, $cn) or
die(mysql_error($cn));
?>

I've made a test here and the inspector says the ajax posted variable Level with value of 1
<script>
var Level = 1;
function Fail() {
$.ajax({
type: "POST",
url: "phpfiles/savestage.php",
data: {
name: 'test_name',
stage: Level
},
success: function() {
console.log("Finished uploading stage");
}
});
}
Fail();
</script>

Related

PHP not receiving AJAX POST from js File

I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
url: '../game.php',
data: { 'Name': name },
success: function(response) {
console.log("sent");
}
});
}
This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['Name'];
console_log($data);
}
When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works
Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
dataType:'JSON', //added this it to expect data response in JSON format
url: '../game.php',
data: { 'Name': name },
success: function(response) {
//logging the name from response
console.log(response.Name);
}
});
}
and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array();
$response['Name'] = $_POST['Name'];
//sending the response in JSON format
echo json_encode($response);
}
I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)
<p style = "color: white;" id="response"></p>
Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {
$gameID = $_POST['gameID'];
$coord = $_POST['coord'];
$player = $_POST['player'];
echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;
}
AND in my custom.js I updated
function sendMovement(cel) {
var handle = document.getElementById('response');
var info = [gameID, cel.id, current_player];
$.ajax({
type: 'POST',
url: '../game.php',
data: {
gameID: info[0],
coord: info[1],
player: info[2]
},
success: function(data) {
handle.innerHTML = data;
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}

Update javascript variables after ajax call

I'm attempting to dynamically update a notice after the cart is updated via ajax. I can't seem to figure out how to re-update all variables so the calculation loop could run again. I tried wrapping the if statement into a function and calling that again inside of updated_wc_div but that didn't work.
Any suggestions?
( function($) {
var membership_price = membership.price;
//grab cart total from html
var total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
compared_price = parseInt(membership_price) - total;
//everything runs fine on load.
if ( total < membership_price ) {
message = 'For <strong>$'+ compared_price +'</strong> more, gain access to unlimited downloads. Become a member!';
notice = '<div class="woocommerce-info">' + message + '</div>';
$('.woocommerce-notices-wrapper').html(notice);
}
//running this to know when ajax is called
$(document.body).on('updated_wc_div',function( event ){
$('.woocommerce-notices-wrapper').empty();
total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
//I believe problem is here, it doesn't update variable so it could loop again.
});
} )(jQuery);
this is how I dynamically update an object after ajax call is being called:
function getCart(user_id) {
$.ajax({
type: "POST",
url: "get_total_cart.php",
data: {
'user_id': <?php echo $user_id; ?>
},
beforeSend: function() {},
success: function(response) {
var user = JSON.parse(response);
var total_cart = parseInt(user.total_cart);
$("#total_cart").html(total_cart);
}
});
}
function addCart(product_id, user_id) {
$.ajax({
type: "POST",
url: "add_cart.php",
data: {
'product_id': product_id,
'user_id': user_id
},
beforeSend: function() {},
success: function(response) {
getCart(user_id);
}
});
}
$(document).ready(function() {
$(".se-pre-con").fadeOut("slow");
getCart(<?php echo $user_id; ?>);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="total_cart">Total Cart</div>
<input type="button" name="add_cart" id="add_cart" value="Add to Cart" onclick="addCart('<?php echo $product[id]; ?>', '<?php echo $user_id; ?>')" class="btn btn-info">
I hope this helps.
Cheers.
Simply you have to put your function inside the ajax function or make the ajax function "async:false"
$.ajax({
type: "POST",
url: "",
async:false, // <======== remove asynchronous property
data: {},
success: function(result) {
}
});
////////////////////////////////////////////////
$.ajax({
type: "POST",
url: "",
data: {},
success: function(result) {
// Or put your function here
}
});

Passed the variable through javascript but not getting it in php?

i am passing my variable throught an AJAX request in javascript but not getting it in my php file. NOt sure where i am going wrong.?
JS code
var build = {
m_count : (document.getElementById('count').value),
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",});
PHP code
<?php
$module_c = $_POST['data'];
echo $module_c;
?>
You have to get the data by the name of the variable you want to get, which is m_count.
<?php
$module_c = $_POST['m_count'];
echo $module_c;
?>
EDIT:
Like suggested in the comments, change your JavaScript code to:
var build = {
m_count : (document.getElementById('count').value)
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",
success: function(data) {
alert(data);
}
});
PHP:
<?php
$module_c = $_POST['m_count'];
echo $module_c;
?>
JS:
var build = {
m_count : (document.getElementById('count').value),
}
$.ajax({
url: 'php/server.php',
type: 'POST',
data: build,
})
.done(function(msg) {
// JSON.parse turns a string of JSON text into a Javascript object.
var message = JSON.parse(msg);
alert(message);
}
})
.fail(function(err) {
console.log("Error: "+err);
})
.always(function() {
console.log("Complete");
})
;

unable to get value in controller from jquery, ajax in php code igniter

AJAX:
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
//alert(BASE_URL);
$.ajax({
type: "POST",
ContentType: 'application/json',
data: data,
url: BASE_URL + 'index.php?deo/dashboard',
error: function () {
alert("An error occoured!");
},
success: function (msg) {
alert('result from controller');
}
});
alert(data);
});
});
CONTROLLER:
public function dashboard() {
$data = $this->input->post('data');
$data = json_decode($data);
echo "<script>alert('count ".$data."');</script>";
}
Am trying to send value from my jquery, ajax to controller, am able to get value from my view page to jquery page and able to print that. But unable to send the value from ajax page to controller page, after sending the data i got the success data. but unable to get and print the data in my controller page. Thanks in advance
If your using firefox a good thing to use is firebug add on and then you can use the console to check for errors on there. To see if the ajax has any errors while sending.
Remove question mark after index.php? and I think your base url is not working correct try just.
Url
// With index.php
url: 'index.php/deo/dashboard',
// Or without index.php
url: 'deo/dashboard',
Or
// With index.php
url: <?php echo site_url('index.php/deo/dashboard');?>,
// Or without index.php
url: <?php echo site_url('deo/dashboard');?>,
Script
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
$.ajax({
type: "POST",
data: data,
url: 'index.php/deo/dashboard',
// url: <?php echo site_url('index.php/deo/dashboard');?>,
success: function (msg) {
alert('result from controller');
},
error: function () {
alert("An error occoured!");
}
});
alert(data);
});
});
Controller
public function dashboard() {
$data = $this->input->post('data');
echo "<script>alert('count ".$data."');</script>";
}

Jquery AJAX with codeigniter, always returns error

I am trying to write a script that will add the video currently being viewed to a database of favourites. However every time it runs, an error is returned, and nothing is stored in the database.
Here is the JQuery
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"localhost/stumble/site/add_to_fav.php",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
The add_to_fav.php is this...
public function add_to_fav(){
$this->load->model('model_users');
$this->model_users->add_favs();
}
And the add_favs function is below
public function add_favs(){
if($this->session->userdata('username')){
$data = array(
'username' => $this->session->userdata('username'),
'title' => $this->input->post('heading'),
'embed' => $this->input->post('embed')
);
$query = $this->db->insert('fav_videos',$data);
if($query){
$response_array['status'] = 'success';
echo json_encode($response_array);
}}else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
}
Thank you for the input, this has me stuck but I am aware it may be something relatively simple, my hunch is that it is something to do with returning success or error.
Try
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"http://localhost/stumble/Site/add_to_fav",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
Also to use base_url in javascript. In your template view :-
<script>
window.base_url = "<?php echo base_url(); ?>";
</script>
Now you can use base_url in all your ajax scripts.

Categories