I built a vote system with ajax and php, and I send data to php page for saved data in db.
I tried to send data with ajax post and php.
My problem is the data is not send to the page.
My js code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajaxSetup({
url: 'vote.php',
type: 'POST',
cache: 'false'
});
$('.vote').click(function(){
var self = $(this);
var action = self.data('action');
var parent = self.parent().parent();
var imgid = <?=$array['id'];?>;
if (!parent.hasClass('.disabled')) {
if (action == 'up') {
parent.find('#image-like').addClass('disabled_up');
$.ajax({data: {'imgid' : imgid, 'action' : 'up'}});
}
else if (action == 'down'){
parent.find('#image-dislike').addClass('disabled_down');
$.ajax({data: {'imgid' : imgid, 'action' : 'down'}});
};
parent.addClass('.disabled');
};
});
});
</script>
and my html code:
Use post method. This is not the correct code, but it's an idea, always works for me.
$('.vote').click(function(){
//Your vars
var data='voteup';
//Your actions... ddClass/removeClass...
$.post('vote.php',data,function(data){
//On your vote.php use "if($data=='voteup') else ;"
//And show message here...
alert(data);
});
return false;
});
example of vote.php
<?php
$data=$_POST['data'];
if($data=='voteup')
echo "You voted up!";
else echo "You voted down!";
?>
It's just an idea (:
You can try changing this:
if (!parent.hasClass('.disabled')) {
to this:
if (!parent.hasClass('disabled')) {
Some Notes:
From the docs:
For $.ajaxSetup()
Description: Set default values for future Ajax requests. Its use is not recommended.
Try using .post() function, you can set a callback when your action is done
jQuery.post(URL_TO_REACH, {ID_VALUE1 : 'my value' , ID_VALUE2 : 'my second value' })
.done(function( data_ajax ) { // data_ajax : Your return value from your php script
alert( data_ajax );
})
});
Hope this will help you
Official documentation : http://api.jquery.com/jQuery.post/
Related
How do I refresh the page after ajax call success. The page doesn't refresh even thought I have put window.location.reload(true). It only displays the echo message but doesn't refresh it
$("#update-btn").click(function() {
var token = document.getElementById('tokenAmount').value;; //Place the token here
var master = currentUserID;
var lastUser = lastNode.info.id;
$.ajax({
type : "POST",
url : "update.php",
data : {'master': master,
'token' : token,
'user_id': lastUser
},
success : function(data) {
alert(data);
window.location.reload(true);
}
});
});
update.php
$master=$_POST['master'];
$user = $_POST['user_id'];
$token = $_POST['token'];
if(condition)
{
$result = $MySQLi_CON->query($secondToken);
if($result == false)
$response['msg'] = "Not Enough";
else
{
$response['msg'] = "Successful";
}
}
else
{
$response['msg'] = "Not enough";
}
echo json_encode($response['msg']);
Please try below code :-
location.reload();
Edited :-
success : function(data) {
alert(data);
location.reload();
}
Other ways :-
location.reload()
history.go(0)
location.href = location.href
location.href = location.pathname
location.replace(location.pathname)
location.reload(false)
Please have a look on below link :- There are 534 other ways to reload the page with JavaScript :-
http://www.phpied.com/files/location-location/location-location.html
.ajaxStop() callback executes when all AJAX call completed. This is a best place to put your handler.
$(document).ajaxStop(function(){
window.location.reload();
});
The source is from here
The next statement wont execute unless you click Ok on alert().
So use console.log(data) instead.
success : function(data) {
console.log(data);
window.location.href=window.location.href;
}
Try this:
location.reload(true);
In your ajax success callback do this:
success: function(response){
setTimeout(function(){
location.reload()
}, 5000);
}
As you want to reload the page after 5 seconds, then you need to have
a timeout as suggested in the answer.
I want to execute a JS function when a PHP form is submitted, and from that function, I want to return a value (which is based on user's input) to PHP, where I'd like to echo it.
This is an SSCCE. In the real code, there is more than just echoing the value, and the value is a JSON object.
Following is my code. The problem is that the $.ajax(); part is not working. Nothing happens in the browser after alert(name);.
Why isn't this working properly? How can I fix this?
From index.php:
<form id="form">
Name:
<input id="name" type="text" />
<input type="Submit" value="Go" />
</form>
From scripts.js:
$(document).ready(function() {
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
alert(name);
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
}
});
});
});
echo.php:
<?php
if ( isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"]) ) {
echo $_POST["nameEntered"];
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
EDIT:
Console:
Network:
EDIT 2:
Added the following to $.ajax():
,
success: function(){
alert("success");
},
error : function(){
alert("error");
}
I get an alert saying success but the browser NEVER directs to echo.php =s
EDIT 3:
After the alert saying success, a ? is added to the URL in the browser. Initially the URL was http://localhost/Test12/index.php and it changed to http://localhost/Test12/index.php?.
This way should show response.
JAVASCRIPT
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
//alert(name);
$.ajax({
type:'POST',
url:'http://localhost/Test12/echo.php',
data: {
nameEntered : name
},
success : function(data){
console.log(JSON.parse(data));
},
error : function(error){
console.log('erro', error);
}
});
});
PHP
<?php
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
$name = array("nome" => $_POST["nameEntered"]);
echo json_encode($name);
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
As a test, replace your echo.php with:
<?php
echo 'Incoming = ' .$_POST["nameEntered"]. "/r/n";
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
echo 'Here 01';
} else {
echo 'Here 02';
}
?>
Try removing the document.ready() or instead of .submit use .on('submit', function(e){}); or add absolute path '/page.php'
I think you need to add "event" as parameter in your submit function, in addition to the success call to show results
What does this give you:
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
},
success: function(recd){ // <-------
alert(recd); // <-------
},
error : function(){
alert("error");
}
});
You're calling event.preventDefault(), but you've failed to add the event to your callback's parameters... so you're not actually stopping the form from being submitted. That is why you see the question mark in the address bar.
Try:
function(e){
e.preventDefault();
};
I have web page that submits a form via AJAX in codeigniter, submission works great, and the php script works as well, but when php is done it return an HTML view as a response to Ajax so it repopulates a div but instead of repopulating it try's to download the file. Chrome console shows
Resource interpreted as Document but transferred with MIME type application/text/HTML
has me confused because I use the same code in another page and it works fine.
This is my Jquery script
$("#addpaymentform").submit(function (event) {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
data: formdata,
url: baseurl + 'sales/add_payment',
success: function (data, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
$('#paymets').html();
$('#payments').html(data);
$('#addpaymentform').each(function() { this.reset() });
}
if (ct.indexOf('json') > -1) {
$("#Mynavbar").notify(
data,
{position: "bottom center"}
);
$('#addpaymentform').each(function() { this.reset() });
}
}
});
event.preventDefault(); // this will prevent from submitting the form.
});
and this is my controller
function add_payment()
{
$this->form_validation->set_rules('fpay', 'Type of payment', 'trim|required|alpha');
$this->form_validation->set_rules('payment', 'Payment', 'trim|numeric');
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
header('Content-type: application/json');
echo json_encode(validation_errors());
} else {
$fpay = filter_var($this->input->post('fpay'), FILTER_SANITIZE_STRING);
$payment = filter_var($this->input->post('payment'), FILTER_SANITIZE_STRING);
if(isset($_SESSION['payments'][$fpay]))
{
$temp = $_SESSION['payments'][$fpay] + $payment;
$_SESSION['payments'][$fpay] = $temp;
header('Content-type: application/html');
echo $this->_loadpaymentcontent();
}
}
}
function _loadpaymentcontent() {
$this->load->view('payment_content');
}
Hope someone can point me in the right direction I've been stuck on this for 2 days.
Thanks everyone.
I had the same problem and i successfully solved it by putting an exit; after the value which is returned to the ajax call in the controller method.
In your case it will be:
echo $this->_loadpaymentcontent();
exit;
What exit does here is it limits the returned value to the value which should be returned to the ajax call and exits before the html is appended to the returned value.
This is what is obvious per the effect it produces.
Yo need to set up your AJAX.
$.ajax({
type : 'POST',
url : baseurl + 'sales/add_payment',
dataType : 'html', // Will set the return type of the response as AJAX.
... Keep rest of the code same.
Have an email input that I'm trying to send to a function using Ajax. I retrieve a success message indicating that it's sent however I don't receive a message back from the php function echoing out the value. Can't see where I'm going wrong.
Any help would be great!
Jquery code is:
jQuery(document).ready(function($) {
$("#submit").click(function(e) {
e.preventDefault();
var vipEmail = $("#email").val();
var ajaxurl = '<?php echo admin_url( "admin-ajax.php", "relative" ); ?>';
console.log(vipEmail);
// This does the ajax request
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'add_member',
member : email
},
success:function(data) {
// This outputs the result of the ajax request
$(".w-form-done").show();
$(".sign-up-form").css("display", "none");
},
error:function(errorThrown){
console.log(errorThrown);
//Show Error Message
$(".w-form-fail").show();
}
});
});
});
PHP Code inside functions.php is:
function add_member()
{
$member = sanitize_email( $_POST['email'] );
echo $member;
die();
}
add_action('wp_ajax_add_member', 'add_member');
add_action('wp_ajax_nopriv_add_member', 'add_member');
You declare a variable vipEmail, but you send member : email, email is not defined.
Then you look for $_POST['email'] instead of $_POST['member'].
So basically change member : email to email : vipEmail.
In addition to what Musa posted, to me it also looks like in success:function(data) you're not doing anything with data.
I'm trying to print a calendar using php but struggle figuring out how to change the month displayed with ajax
I have two buttons in tag whose value is "+1" and "-1" respectively with a class="selectMonth"
<button class="selectMonth" name="selectMonth" value="-1">previous</button>
<button class="selectMonth" name="selectMonth" value="+1">next</button>
This is my ajax code:
$(".selectMonth").on("click", function(){
$.ajax({
url : "index.php",
type : "POST",
data : {selectMonth : this.value},
success : function(){
alert("success!");
}
});
});
and in my index.php I have
<?php
if(!isset($_POST["selectMonth"]))
$_SESSION["date"] = time();
else
{
$selectMonth = $_POST["selectMonth"];
$_SESSION["date"] = strtotime($selectMonth . 'month');
}
var_dump($_POST["selectMonth"]);
$date = $_SESSION["date"];
print_calendar($date);
?>
After I click one of the buttons, I can get the alert message but not the $_POST variable and what is var_dump is always NULL
Could anybody find out the mistake for me?
I'm still learning ajax.
Thank you very much!
try below line of code :
data : {'selectMonth' : $(this).val()},
OR
data : {'selectMonth' : $(this).attr('value')},
Try
$(".selectMonth").on("click", function(){
var inputVal = $(this).attr('value');
$.ajax({
url : "index.php",
type : "POST",
data : {selectMonth : inputVal},
success : function(){
alert("success!");
}
});
});
Instead of
data : {selectMonth : this.value}
try
data : {selectMonth : this.val()}