trying to send POST request to script via ajax, not calling the script
<script>
function claimitem() {
var val=document.getElementById('itemid').value;
alert(val); //shows as 4 correct
$.ajax({
type: "POST",
url: "scripts/claim.php",
data: {id: val},
dataType: "json",
success: function(data) {
alert("success"); //does not show
}
});
window.location = "profile.php";
}
</script>
here i am calling the javascript function
<input type="submit" onclick="claimitem()" class="btn" value="claim - <?php echo $ebase;?> PP">
my claim.php looks like this what is wrong with my ajax call???
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id'])) {
...
}
When you call $.ajax, you're starting an asynchronous task. This task, involving a request, doesn't stop the script so the following line is immediately executed.
As the following line replaces the page, it ends the script, including the ajax request. You must call this line in the callback to let the time for the ajax request :
$.ajax({
type: "POST",
url: "scripts/claim.php",
data: {id: val},
dataType: "json",
success: function(data) {
alert("success"); //does not show
window.location = "profile.php";
}
});
code looks ok better add some alert to error as if some problem with your ajax helper.
something like.
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
Hope you have added this to your head tag
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
then try to change input type="button"
<input type="button" onclick="claimitem()" class="btn" value="claim - <?php echo $ebase;?> PP">
Related
I'm trying to return Data for Ajax, but I'm still not clear about something :
My Form :
<form id="checkitem" class="form-horizontal">
<input type="text" name="item1"><br><br>
<input type="submit" value="Submit">
</form>
Ajax call :
<script>
$(document).ready(function(){
$('#checkitem').submit(function(){
$.ajax({
type: 'POST',
url: 'operations.php?r=checkitem',
data: $(this).serialize()
});
});
});
</script>
My PHP code (For operations.php?r=checkitem) :
$item1 = mysql_real_escape_string($_POST['item1']);
include ("data.php");
$query = mysql_query("INSERT INTO Itemlist (item1, ins_date) VALUES ('$item1',now()");
if (!$query)
{
die('Invalid query: ' . mysql_error());
}
echo "Item1 has been added";
How to return echo value , or any other php variable from the page operations.php
EDIT :
As per your suggestion guys I should use success function :
success : function(response){
alert(response); //Do whatever you want to do with this
My question is , What is response ? is it all what has been echoed from other page ? or the HTML code of the other page ?
Thnx
You can do it like this.
AJAX has various callback functions, success is one of them. You can use others like error, complete.
success will be called when AJAX request successfully executed. This will provide use response text which we echo or print in our PHP page.
<script>
$(document).ready(function(){
$('#checkitem').submit(function(){
$.ajax({
type: 'POST',
url: 'operations.php?r=checkitem',
data: $(this).serialize(),
success : function(response){
alert(response); //Do whatever you want to do with this
}
})
});
});
</script>
the ajax function of jquery has a success callback function, you can retrieve the data from the ajax page you called :
$.ajax({
type: 'POST',
url: 'operations.php?r=checkitem',
data: $(this).serialize(),
success: function(result) {
console.log(result);
// do what you want with the result here
// if it's html you could do $('.elem').html(result);
}
})
The better is to specify which kind of data you're expecting with the type key : (type: 'json') or (type: 'text/html) for example.
And in your php script, send headers in consequence !
or use deferred way
$.ajax({
type: 'POST',
url: 'operations.php?r=checkitem',
data: $(this).serialize()})
.done(function(result){
console.log(result);
})
.fail(function(error){
console.log(error);
});
I would like to display newly inserted data from database. I found the below code from another question and it does what I want but it only shows the data when clicked. So can someone tell me how can I make the data auto load every 5 secs?
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<input type="button" id="display" value="Display All Data" />
<div id="responsecontainer" align="center">
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function (response) {
$("#responsecontainer").html(response);
setTimeout(load, 5000)
}
});
}
load(); //if you don't want the click
$("#display").click(load); //if you want to start the display on click
});
Try to add setTimeout:
success: function(response){
$("#responsecontainer").html(response);
setTimeout(success, 5000);
}
You can use function setTimeout as a timer to trigger. For detail, please look at below code:
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
setTimeout(loadData, 5000);
}
});
};
You may use jquery's setInterval() or setTimeout() inside onload();
refer to the following questions, its answer explains well what you need exactly.
Calling a function every 60 seconds
Hi i have ajax in my project, in other files, but for this one particular instance where I call scripts/claim.php and pass in an id parameter via GET it doesn't seem to work.
HTML
<input type="hidden" id="claimid" value =<?php echo $fetch_donate['id'];?>>
<input type="button" onclick="processclaim();" class="btn" value="claim - <?php if($donate_type=='generic'){ echo $ebase;} else { echo $fetch_donate['ebase'];}?> PP"></div>
PHP
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['id'])) {
....
}
Javascript
<script>
function processclaim() {
alert("hi");
var id=document.getElementById('claimid').value;
alert(id);
$.ajax({
type: "POST",
url: "scripts/claim.php",
data: {id: id},
dataType: "json",
success: function(data) {
window.location = "profile.php";
}
});
alert(id);
}
</script>
the alerts work, displays "hi" and the correct id that is passed.
You are probably getting an error back from your server, add that state to the Ajax call
$.ajax({
type: "POST",
url: "scripts/claim.php",
data: {id: id},
dataType: "json",
success: function(data) {
window.location = "profile.php";
},
error: function() {
console.error("ERROR!", arguments);
}
});
My guess is you are setting the dataType coming back as JSON and it is not being returned from the server as JSON.
I'm using an ajax script to post a value to a PHP file.
I'm not able to pass the variable.
My variable is declared in PHP and I would like to pass it with ajax.
Here is the variable and my button:
<?php $employee_id= '3'; ?>
<input class="btn btn-danger" type="submit" value="Delete" id="delete-btn">
This is the Javascript:
<script>
$(document).ready(function () {
$("input#delete-btn").click(function(){
$.ajax({
type: "POST",
url: "delete.php", //
data: {id: '$employee_id'},
success: function(msg){
$("#thanks").html(msg)
},
error: function(){
alert("failure");
}
});
});
});
</script>
Here is the PHP code where I want to receive the value:
if (isset($_POST['id'])) {
$emp_id = strip_tags($_POST['id']);
echo $emp_id;
$query = "DELETE FROM `employee` WHERE id='$emp_id'";
$result = mysql_query($query) OR die(mysql_error());
echo 'You successfully deleted the user.';}
I know I'm doing something wrong around the data...
That is because your variable is in php but you are not using php to attach your variable to your ajax, try wrapping your variable in php tags and then make sure you use 'echo' to print the value of your variable into javascript.
data: {id: <?php echo '$employee_id'?>},
Your javascript code, as far as the client will see, will end up looking like this for them:
data: {id: '3'},
They won't see the php code, they will just see the end result as their javascript.
You need PHP tags around your variables:
<script>
$(document).ready(function () {
$("input#delete-btn").click(function(){
$.ajax({
type: "POST",
url: "delete.php", //
data: {id: <?php echo '$employee_id'; ?> }, // <---
success: function(msg){
$("#thanks").html(msg)
},
error: function(){
alert("failure");
}
});
});
});
</script>
I have the following javascript that's using ajax with jquery to submit a form.
$(function() {
$("#signform").submit(function() {
alert();
$.ajax({
type: "POST",
url: "page/sign.php",
data: { mail: $("#inputEmail").val(),
pass: $("#inputPassword").val(),
nick: $("#inputNick").val(),
date: $.datepicker.formatDate('yy/mm/dd', new Date()) },
sucsess: handler,
error: function(err) { alert('error: ' + err.status) }
});
});
function handler(var){
$('#message').html(val);
}
});
and html code is here, using bootstrap !
<form class="form-horizontal" id="signform">
// ... something codes
<div class="form-group">
<div class="col-offset-2 col-lg-10" align="center">
**<button type="submit" class="btn btn-default">Sign in</button>**
<button type="button" class="btn">Cancel</button>
</div>
</div>
</form>
When I pressed the submit button, it went to the index page.
I don't know what is wrong.
js code is in the same page in sign.php
You are not preventing the default action of the submit button, you can either call event.preventDefault(), or return false from the submit handler to fix this
Also in the handler method the parameter was called var which is invalid
$(function() {
$(document).on('submit', "#signform", function(e) {
$.ajax({
type: "POST",
url: "page/sign.php",
data: {
mail: $("#inputEmail").val(),
pass: $("#inputPassword").val(),
nick: $("#inputNick").val(),
date: $.datepicker.formatDate('yy/mm/dd', new Date())
},
success: handler,
error: function(err) {
alert('error: ' + err.status)
}
});
return false; //this will prevent the default action and will stop the event propagation
//if you do not want to stop event propagation you can use
//e.preventDefault();
});
function handler(val){ //also invalid variable name var here
$('#message').html(val);
}
});
Try this, It will help you better, Here U=page URL, F=Page method,D=Data
U=sign.php,
F=page,
D="mail: '+$("#inputEmail").val()+',pass: '+$("#inputPassword").val()+',nick: '+$("#inputNick").val()+',date: '+$.datepicker.formatDate('yy/mm/dd', new Date())+'"
// function for call page method using ajax
function Operation(U, F, D) {
$.ajax({
type: "POST",
url: U + '/' + F,
data: D,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (r) {
var str = r.d;
});
}