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.
Related
Im trying to send an array to the PHP script:
usedAnswers = [1,2];
// funtion for displaying a question
displayQuestion = () => {
$.ajax({
url: "backend/retriveData.php",
data: {usedAnswers:usedAnswers} ,
type:"post",
success: function(response) {
console.log(response);
}
});
}
// inital display of question
displayQuestion();
Then when I want to access the array in the PHP script
<?php
echo print_r($_POST['usedAnswers']);
?>
I get the following problem on screen
Why is he adding an extra 1 ?
When I try to access the first element of the Array like this:
echo print_r($_POST['usedAnswers'][0]);
He console.logs me the number 11?
What am I doing wrong what is the correct way to send an Array via Ajax?
Is it also possible to send a set via Ajax?
so, based on your comments, it appears your question is really referring to how to send data through, rather than the odd output you're getting, which Jay has already answered for you.
as far as your code reads, what you're actually sending is this:
{[1, 2]:[1, 2]}
which is invalid JSON.
if you're trying to actually have a 'usedAnswers' key (which it looks like from your php), then you need to do this:
$.ajax({
url: "backend/retriveData.php",
data: {'usedAnswers':usedAnswers}, // <-- note the quotes around the key
type:"post",
success: function(response) {
console.log(response);
}
});
Because you are echoing the print_r() (which in and of itself is a type of echo) you're returning a value for the truthiness of the print_r(). Change the line to this
print_r($_POST['usedAnswers']);
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);}
})
}
Does anyone know how pass form values into PHP and still return the data to JavaScript? (For use in Google Charts if anyone is wondering.)
I have an HTML form with 4 radio boxes. I'd like to pass the value of the form so that my PHP request will be modified based on the user's selection.
The results from the PHP request need to be passed to JavaScript for processing.
In the radio button on click event place a javascript function that will perform an XMLHttpRequest to the php page and have the PHP page echo some JSON content that can be decoded in the return of the XHR in Javascript.
Example of such
May this can help you.
I think that you must do an Ajax request
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( data) {
alert( "Data Saved: " + data);
});
You send data to server form your form (here sent are name and location). You read this data with javascript with OnSelect and transfert it to your PHP code and,
You get back data from server into your JavaScript code and you can do what you want with it.
Sorry if my solution use JQuery, it is better for cross-browser with less code writing !
You could use this line to parse an array into json and use it later in javascript:
json_encode($rows); //format array named $rows into json data
More info: http://php.net/manual/en/function.json-encode.php
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'];
I don't understand how the success function works in a $.ajax call with jquery.
for instance
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
useReturnData(data /* ??? not sure how to use the data var */ );
}
};
ajax.php:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
?>
how do i use that data within the success function? No where seems to explain what the data parameter is, they just seem to use it ambiguously.
another side question, is the data: "function=1" related to the data as a parameter for the success function?
The data variable contains the output of your php file, so if in your php file you do:
echo "<p>success</p>";
data will contain <p>success</p>.
In your example you would change your php file to:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
// other stuff...
echo $string;
?>
The content of the data parameter depends on the type of the response. If the Content-Type is application/json, then it's parsed as JSON. If it's text/html or similar, the content is HTML. In your case, it looks like you're returning text. If you make your Content-Type header text/plain or similar, then data should just be a string.
To answer your second question, the data property for the Ajax request is something different; it specifies the request data that is sent. In other words, it's the query string if you have a GET request, and the post "form" variables if it's a POST request.
data is whatever is returned by the server side script, so in this case it would be
this is the data i want to return and use
Providing the if() condition is met.
Nobody really says what data contains because it can contain various different things, although it's always a string. Sometimes it's HTML, sometimes it's JSON and sometimes just a return message.
In your case, data will just be a string providing you echo the string out in your server side script.
The easiest way is to load the data into some placeholder element (div?)
E.G.
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
$('div.selector').load(data);
}
};