$.ajax POST not receiving data - javascript

If you wish to visit my webpage
Login details that can be used are
(case sensitive):
Username: stack
Password: stack
Click on yourhours tab.
My overall goal is to send all data from input boxes to a database. However currently I am just trying to get the interaction from the javascript and the PHP working. In the console I can see that the data variable has the value of "". I cannot see why this is happening.
PHP
<?php
$startTime = $_POST["startTime"];
echo $startTime;
?>
HTML
http://pastebin.com/7p9NiV44

Your javascript is working and is sending the value of the startDate input element to your sendHours.php. Your PHP-script is also correct.
By some reason your $_POST array isn't populated and it's not possible to come up with a solution based on your question alone. I would start by checking my php.ini, especially the setting post_max_size.
Also, you could try replacing your PHP-code with a simple <?php echo "Hello world"; ?> to verify that your setup is working to that extent at least.

not a solution but add the error section to get a better idea of what is going on.
function d(){
var startTime = document.getElementById("startTime").value;
console.log(startTime);
$.ajax({
type: "POST",
url: "sendHours.php",
data: {startTime: startTime},
success: function(data){
console.log(data);
},
error: function(err, status) { console.log(err);}
})
}

Related

Pass javascript string variable to another page and get the variable in PHP with AJAX

I basically don't seem to understand sending a variable to another page.
I've tried PHP sessions, javascript cookies and ajax POST and GET.
I'm trying to send the innerHTML of a div, with the data created by a jQuery call,
a variable called savedartists. It displays correctly in the console.log on the sending page but the $_POST['savedArtists']
is undefined in the receiving page. I have spent hours looking at different posts on this site but I haven't been able to get it to work.
Any help is appreciated.
<input class="et_pb_button et_pb_button_0 et_pb_bg_layout_light" onClick="savequote();" type="button" id="savedchoices" value="Commander la prestation" >
<script>
function savequote() {
var savedartists = document.getElementById('selectedList').innerHTML;
console.log(savedartists);
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
}
});
}
</script>
On the receiving page (example.com/artiste/mise-en-relation/)
<?php
if(isset($_POST['savedArtists']))
{
$uid = $_POST['savedArtists'];
echo $uid;
} else {
echo 'zit!';
}
?>
Thanks for your time
Capturing as an answer for future readers...
Fundamentally what's happening here is that two requests are being made to the target page. The first one is the AJAX request:
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
//...
}
});
This is a POST request which contains the data you expect, and works just fine. However, the result of this request is being ignored. That result is available in the success callback, but the code doesn't do anything with it:
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
Instead, what the code is doing is performing a redirect. This creates a second request to that same page (though it's essentially irrelevant that it's the same page). This is a GET request and contains no data to send to the server.
At its simplest, you should either use AJAX or redirect the user. Currently you're mixing both.
I want to redirect to the other page.
In that case AJAX is the wrong tool for the job. You may not even need JavaScript at all, unless you want to modify the elements/values of a form before submitting that form. But if all you want is to POST data to another page while directing the user to that page, a plain old HTML form does exactly that. For example:
<form method="POST" action="example.com/artiste/mise-en-relation/">
<input type="text" name="savedArtists">
<button type="submit">Submit</button>
</form>
In this case whatever value the user enters into the <input> will be included in the POST request to example.com/artiste/mise-en-relation/ when the user submits the form.

Ajax post error with no futher information

I need help with this stuff. Chrome doesn't have this problem, only Firefox. When I submit form, ajax creates tasks. My mysql queries ain't got any problems, I added tons of
if not working write mysql error into file
But all are successful. So here is the error
http://i.stack.imgur.com/KYq4L.jpg how to find out what the hell is this? My code of ajax is pure empty here it is:
$.ajax({
type: "POST",
url: '/modules/projects/ajax/ajax_import.php',
data: {
data: array,
id: projectNow,
}
});
Thats it.
First check ajax_import.php is available at this location or not.
/modules/projects/ajax/ajax_import.php
If file is exist at this location then just clear all content from there and just write test content as below.
<?php
echo "testing";
?>

PHP JSON Encoded Object causes Ajax Error

This has been bugging me for the last few hours, and I've tried various searches but never found exactly this issue with an answer. Maybe asking and showing some code will help me get this figured out.
I am using ajax to do a post to PHP, which I want to just give a notification so that I may update a div on the page. In this case, I just need the PHP to say something like "Cfail" which the javascript would use to update page content.
Originally, I was going to try just text responses. So, my PHP for example would be like this:
<?php
session_start(); //Because have an encoded captcha answer.
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
echo 'Cfail';
}
?>
The Javascript would be:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'text',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned=='Cfail'){
alert("I read it right!");
}
}
});
});
});
It would run through the script just fine, but the result never would be what I was asking for. Alert showed the corrct text, however, research indicated that the issue with this was PHP apparently adding white space. The common answer was the encode a JSON response instead. So, I tried that.
Updated PHP:
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
$result = array('result' => 'Cfail');
echo json_encode($result);
exit;
}
?>
Updated Javascript:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'json',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
}
});
});
});
Which now no longer runs successfully. The alert doesn't come up, and the loader object remains visible(indicating the success never goes through). I tried putting an error section to the ajax, and it indeed fired that. However, I had no idea how to parse or even figure out what the error was exactly. The most I got in trying to get it was what PHP was outputting, which was {"result":"Cfail"} .... Which is what I would EXPECT PHP to give me.
I can work around this, I've done a similar set-up with just echoing a number instead of words and it used to work just fine as far as I knew. I'd just like to figure out what I am doing wrong here.
EDIT:
I managed to figure out what the issue was in my case. I had a require('config.php'); between the session start and the json_encode if statement. For some reason having the external file added, which was just me setting a couple variables for the code further down, some hidden character was added before the first { of the JSON object.
No idea why. As I said, it was just a $var='stuff'; situation in the require, but apparently it caused the issues. :/
Use this like
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
//$result = array('result' => 'Cfail');
$data['result'] = 'Cfail';
echo json_encode($data);
exit;
}
?>
This works for your javascript
use the below code, in your success call back, first parse the encoded json object that you are recieving from the back end and access the object property result to check it's value
success: function(returned){
returned = JSON.parse(returned);
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}

Passing Variable via AJax

Im on project to make an app with codeigniter but i got stuck, when i want to pass same variable outside field via ajax into controller i got error the variable is not defined.
this is a example.
$("#form_status_update").submit(function() {
var date = new Date().toString();`
$.ajax({
type: 'POST',
url: "<?php echo base_url()?>socialcontroller/setdate",
data:date,
success: function(data) {
window.location.href = "<?php echo base_url()?>socialcontroller/ssetdate";
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
});
after passing some var i want to insert into my database.
and my question is how to pass a variable not field into controller via ajax thanks, i already search on google but i didnt geting the right answer :)
`
The line data:date, is wrong. You are passing up a number on the querystring and not a key/value pair.
It needs to be
data: {date : date},
or
data: "date=" + encodeURIComponent(date),
From jQuery Docs:
data
Type: PlainObject or String or Array
Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing. Object must be Key/Value pairs. If
value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
Here is the code that help you with your problem
You can just adapt it with your code and it should work !
<script>
$(document).ready(function(){
$("button").click(function(){
var myDate = new Date();
$.ajax({
// Send with POST mean you must retrieve it in server side with POST
type: 'POST',
// change this to the url of your controller
url:"index.php",
// Set the data that you are submitting
data:({date:myDate}),
success:function(result){
// Change here with what you need to do with your data if you need of course
$("#div1").html(result);
}});
});
});
</script>
<body>
<div id="div1">
<p>Today date here</h2>
</div>
<button> Get Date< /button>
</body>
</html>
and your PHP code can be something like this !
<?php
// This line of code should get your data that you are sending
$data = $_POST['date'];
/// This code was just for checking purpose that it is returning the same value through ajax
$arr = array(
'receive_date'=>$data,
);
echo json_encode($arr);
I think this code can work with must of MVC framework if you are setting your controller URL as url parameter. Check also the Framework documentation about getting the data through POST !
your selector $("form_status_update") doesn't match a class or an id of the DOM.
and it doesn't match an html element either.
so this for sure gives you some (extra) problems.
couldnt you have tried running the date function at the php controller youre calling from the ajax function.
i dont see any specific reason as to why you have to send in date as the input parameter from the javascript function.
remove the date var and data field.
and in your php controller.
when you get the controller called.
run a date function in the php code and use the date from there.

unable to get the data value of ajax on another page

I'm trying to update the user votes into database. This below ajax codes returns correct rating datas. But, I'm unable to get the alert data on another page. In my car_user_rating.php page I have tried this echo $post_rating = $_POST['performance_rating'];. But it doesn't get the performance_rating data value.
I have checked my console. It returns the rating values (4). I'm confused why it doesn't get the data value?
ajax request
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: "<?=CAR_USER_RATINGS?>",
data: { performance_rating: performance_rating },
success : function(data){
alert(performance_rating)
},
});
});
});
you should alert the data which you pass in success: function()
like
success : function(response){
alert(response);
},
use 'var' in submit handler, may it's because of scope:
var performance_rating = $('input:radio[name=rating]:checked').val();
I am not sure of your context so cant say exactly. Also i dont know if you are using exact same code as above or you have written teh above code in a hurry since there are mistakes there!!!
However Firstly try these
data: { "performance_rating": performance_rating },
url: "<?php=CAR_USER_RATINGS?>" //you have forgotten php
success : function(data, testStatus, xhr){
},
and check each values of data, testStatus, xhr
Also what is the value of
performace_Rating before $.ajax
"<?php=CAR_USER_RATINGS?>" before $.ajax
Just to summarize. I could figure out from your comment that your php is as below:
no. I have this codes on my php page inside the body tag
<?php echo $post_rating = $_POST['performance_rating'];
/*var_dump($get_rating); echo $sql = "UPDATE ".TBL_CAR_USER_RATINGS." SET performance = '$get_rating' WHERE model_id = '2'"; die(); mysql_query($sql, $CN) or die(mysql_error()); */ ?>
This is present inside the body tag!!! Well if you are using body tag i presume you are using other html, header(optional) tags as well
For a ajax response page the reply to client should "ONLY" be the value you want to send back.
Having tags will result in the the ajax response containing these tags as well.
So if you want your ajax page to return performance rating do the below:
//car_return_Rating.php
<?php echo $_POST['performance_rating']; ?>
If you have below code your response is shown below
//car_Return_rating.php
<html>
<body>
<?php echo $_POST['performance_rating']; ?>
</body>
</html>
then response i.e. data in success(data){}
will be equal to
data = "<html><body>4</body></html>"; //assuming 4 to be equal to $_POST['performance_rating'];

Categories