Trying to pass js variables to php with ajax - javascript

As the title says, I'm trying to pass a couple js variables to a php file. Here is my code so far.
JS:
$.ajax({
method: "POST",
url: "sendDataToDB.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
sendDataToDB.PHP:
<?php
$temp = $_POST["mainVideoData"];
echo $temp;
?>
I saw this code on different websites, but for some reason it's not working for me. It says that 'mainVideoData' is undefined which basically means that it doesn't exist.
Does anyone know what I did wrong?
Thanks!
EDIT:
I've read some suggestions, and decided to make a whole new file with just the code someone gave me that worked for him. Here is my whole php file and whole js file.
php.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery-2.1.3.js" type="text/javascript"></script>
<script src="getApiData.js" type="text/javascript"></script>
<meta charset="utf-8"/>
<link rel="stylesheet" href=""/>
</head>
<body>
</body>
</html>
<?php
if(isset($_POST['mainVideoData'])){
$temp = $_POST["mainVideoData"];
echo $temp;
}
?>
And here is my whole js file:
$(document).ready ( function(){
var mainVideoTitle = "Hello";
$.ajax({
method: "POST",
url: "php.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
});
It only gives me an alert saying 'data sent', but it doesn't echo 'hello'.
Does anyone know what's wrong?
EDIT 2:
So I've added some code in my php file that should put my $temp in a database. Sadly that doesn't work. When I replace $temp by a normal value like 'hello' it places it in my database. When I use $temp it gives me this error:
Error: INSERT INTO youtubevideos (category)
VALUES (Wiz Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack)You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack)' at line 2
As you can see, it does give me the right value, and it also places that right value in VALUES. But for some reason it still gives me this error. Any reason why?

jQuery library is definitely included
check the path of your php file is valid
check mainVideoTitle defined or not
After just try this.
script:
$(document).ready ( function(){
var mainVideoTitle = "Hello";
$.ajax({
method: "POST",
url: "sendDataToDB.PHP",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
});
sendDataToDB.PHP:
<?php
if(isset($_POST['mainVideoData'])){
$temp = $_POST["mainVideoData"];
echo $temp;
}
?>
I hope this is help to achieve your result!!!

Try this it will work.Data will be captured in success.
$.ajax({
method: "POST",
url: "sendDataToDB.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
console.log(data);
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});

Related

jQuery Ajax not sending Post data to PHP file

I'm trying to send variables from my JavaScript to a PHP file using AJAX but it's not working. I've looked through all the similar asked questions (there are a bunch) but have yet to find a solution.
This is my first php file (one with the form, sends data to JavaScript):
<option value="imageOne" data-cuteform-image='assets/SketchThumbnails/imageOne.png></option>
<input id="inputURLID" type="text" name="inputURL">
<button type="submit" onclick="handleInputs(document.getElementById('sketch').value, document.getElementById('inputURLID').value); return false;">Submit</button>
JavaScript (where AJAX call is):
var content = {
'sketch': pickedSketch,
'songUrl': enteredURL
};
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
PHP (loadSketch.php):
if(isset($_POST['songUrl']))
{
$temp = $_POST['songUrl'];
echo $temp;
echo "received AJAX data";
} else {
echo "nothing in post variable";
}
When I get redirected to loadSketch.php (from the successful ajax call), "nothing in post variable" gets echoed out. Any ideas what I'm doing wrong?
Any insight is much appreciated! :)
Nothing is in songURL because when your Ajax function returns it is redirecting to the same page you just posted to. It is creating a new HTTP request to that PHP file with no data sending to it. Remove the comments on the console messages and you'll see the correct echo messages.
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
alert("success");
console.log(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
You should not use a submit button because it makes the whole page reload; instead use normal buttons and handle the click events calling your AJAX function.
HTML:
<button onclick="doAjaxFunction(param1, param2);">Calling Ajax Function<button>
JavaScript:
function doAjaxFunction(val1,val2){
$.ajax({
type: "POST",
url: "loadSketch.php",
dataType: "json",
data: {"'value1':'"+ val1+"', 'value2':'"+ val2+"'"},
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Then just pick your POST parameters in loadSketch.php and use them.
PHP:
$x = $_POST['value1'];
$y = $_POST['value2'];

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>";
}

AJAX not sending data

I am using the following code to get data from an input field and send it to PHP by POST but its not working
<script type="text/javascript">
$(document).ready(function () {
$("#id_1").change(function () {
var rat1 = $(this).val();
$.ajax({
url: "upload.php",
type: "post",
data: rat1,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
this is the input form
<input type="number" name="your_awesome_parameter" id="id_1" class="rating" data-clearable="remove"
data-icon-lib="fa" data-active-icon="fa-heart" data-inactive-icon="fa-heart-o"
data-clearable-icon="fa-trash-o"/>
You need to provide a name for the parameter. It should be:
data: { param_name: rat1 }
Then in upload.php you access it with $_POST['param_name']
Just in case, did you imported Jquery into your project?
I tested your code and I with the minor change that Barmar specified and it is working for me.
Try to use this code in your php file and see if you get any response in the developer tools console.
$data = $_POST["param_name"];
echo json_encode([$data]);
Try in this way men
function realizaProceso(valorCaja1, valorCaja2){
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2
};
$.ajax({
data: parametros,
url: 'ejemplo_ajax_proceso.php',
type: 'post',
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (response) {
$("#resultado").html(response);
}
});
}
change on input type number is not working in older versions of browsers, I think not sure. But try this below solution as you are using input type number.
$("#id_1").on("mouseup keyup",function () {
//your logic here
});
and passing data as already mentioned by others:
data: { param_name: rat1 }

Ajax not sending info to php

I'm trying to get some information from my php code when clicking on a button, but it doesn't connect to php.
front page is displayed in index.php
index.php:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="functions.js"></script>
<title>Account Panel</title>
</head>
<div "getInfos">
<h2>In this section you can get your inforrmation</h2>
<button id="getNameBtn">Get Your Name!</button>
<span id="getNameSpan"> something must come here</span>
</div>
</body>
</html>
javascript codes and ajax are in
functions.js:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
and php in serverside is some simple thing like this:
handler.php:
<?php
echo('Ajax successful!');
?>
You have not close the document ready function:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
data:JSON.stringify({taskid = 1}),
shoulde be
data:JSON.stringify({taskid: 1}),
First of all, you should better use a newer jquery version.
There is at least one error in your Code:
data:JSON.stringify({taskid = 1})
The json should read
{taskid : 1}
Use a colon, not an equal sign. Not sure that it is true for your jQuery version, but usually data can be attached as json object already, so the whole line should work so:
data: {taskid : 1},
And the data is then visible as POST data in the PHP page. Note that the live() function is deprecated since 1.7. You can use
$("#getNameBtn").click(function(){...});
instead. Moreover, I don't think you need the headers in your request.
First important change you need to do, use $.on instead of $.live, since the latter is deprecated. Another thing you should check, if the handler.php file is at the same level as your JS/HTML file. It could be that the file is not reachable from your code. Here is what you can try:
$(document).ready(function(){
$("#getNameBtn").on('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data: { call: 'myAjax', taskid : 1 },
headers: {
'content-type': 'application/json'
},
success: function(response) {
$('#getNameSpan').html(response);
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
And in the PHP file, you can check for the call key:
<?php
if(isset($_POST) && $_POST['call'] == 'myAjax') {
echo $_POST['taskid'];
exit;
}
?>
That exit is really important.
In your PHP file that returns JSON you should also set the header to JSON.
header("Content-Type: application/json"); //Above all HTML and returns
And the true answer to your problem has already been answered.

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