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);
});
Related
im fairly new to ajax.. but I have this function which takes and order id and query sql from it in a php page. I can set the returned data to a div but what id like to do is set the return from the function to the returned data in html or text form so i can email it later. also any better ways to do this code would be greatly appreciated
<script>
function getInvoice(id){
var request = "driverInvoice.php"+"?oID="+id;
$.ajax({
url: request,
success: function(data){
$("#theDiv").html(data);
}
});
}
</script>
Use data: {oID: id} to send with POST.
function getInvoice(id){
$.ajax({
async: false,
type: "POST", //Method POST, you can edit and use GET
url: 'driverInvoice.php', //URL
data: {oID:id}, //Variables
success: function(data){
$('#theDiv').html(data);
},
error: function(data) {
}
});
}
If I undestend, you want transform data in text, like a strip_tags php function?
...
success: function(data){
$("#theDiv").html(data);
var text = $("#theDiv").text()
}
I want to pass values to a PHP script so i am using AJAX to pass those, and in the same function I am using another AJAX to retrieve those values.
The problem is that the second AJAX is not retrieving any value from the PHP file. Why is this? How can I store the variable passed on to the PHP script so that the second AJAX can retrieve it?
My code is as follows:
AJAX CODE:
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
PHP CODE:
<?php
$userAnswer = $_POST['name'];
echo json_encode($userAnswer);
?>
Use dataType:"json" for json data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.
SO, I recommend using one AJAX call and get the value with success.
example: in first ajax call
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
alert(data);
//or if the data is JSON
var jdata = jQuery.parseJSON(data);
}
});
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call
In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.
Try this: var_dump($_REQUEST); and check if you're receiving the values.
you have to pass values with the single quotes
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: '145'}), //variables should be pass like this
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
try it it may work.......
i am trying to submit a php form through ajax, my jquery code is
$("#editContraForm").submit(function editContra (e) {
e.preventDefault();
dataString = $("#editContraForm").serialize();
$.ajax({
type: "POST",
url: "./validations/contraAjax.php",
data: dataString,
action : "edit",
dataType: "text",
success: function(data) {
console.debug("success : "+data);
},
error : function(error){
console.debug("erro");
}
});
});
and php code is (contraAjax.php)
if(!isset($_SESSION))
session_start();
include_once '../connect/connectOpen.php';
$action=isset($_REQUEST['action'])?$_REQUEST['action']:'';
if($action=="edit"){
echo 'good';
}
and the call is successfule (as shown in firbug) but console prints 'success: ', means data is null. What is wrong with this code, Kindly help me
You should not serialize data, but pass an object.
See jQuery documentation: http://api.jquery.com/jQuery.ajax/
use action as a parameter and then access it using $_POST['action'].
also try to var_dump($_POST['action']);
To add an action parameter just concatenate it into the data string.
data: dataString + '&action=edit',
I am new to jquery and php, I have two input fields, zip and city, the city shall output a value based from the zip that the user input. The jquery script shall call a URL: http://domain.com/city?zip.php="zip; so that zip.php will return an echo value that will output to the city input field.
I tried using ajax getXMLHTTP. some times it works but sometimes not
Please Refer to the following code snippet below:
<input type="text" id="zip_code" name="zip_code" />
<input type="text" id="city" name="city" />
<script type="text/javascript">
// Some Jquery code here for ajax get request to http://domain.com/city?zip.php
</script>
if you are using jquery the use $.ajax option instead of getXMLHTTP
function passzipvalue(zip)
$.ajax({
type: "GET",
url : 'http://domain.com/city.php='
data:"zip="+zip,
success: function(msg){
$("#formsData").html(msg);
}
});
}
something like this or
$.get('http://domain.com/city.php?zip='+zip,function (msg){
$('#formsData').html(msg);
});
if you want to populate it in some input fields use .val instead of .html
Use jQuery.get, documented here. In the success handler, use the data argument to populate the city input.
Sample:
$.get('http://domain.com/city.php?zip='+$('#IdOfZipInput').val(), function (data){
$('#IdOfCityInput').val(data);
});
Use jQuery AJAX. For example:
var zip = $('#zip').val();
$.get('http://domain.com/city.php?zip='+zip,function (data){
$('#city').val(data);
});
$.ajax({
url: 'http://domain.com/city.php?zip='+zip,
type: get,
success: function(data){
$("div").html(data);
}
});
use this data will be displayed
If its a constantly updating element then use jquery.post as ie caches the "get" results.
jQuery.post('call.php',{ action: "get"}, function (data) {
jQuery('#content').append(data);
});
FInd the tutorial here http://vavumi.com/?p=257
try to use the jquery ajax
$.ajax({
type: "POST",
url: 'sample/test.php',//your url
data: data,//data to be post
cache: false,
success: function(html) {
alert(html);//response from the server
}
});
$.ajax({
url: 'url',
beforeSend: function (xhr) {
//show loading
}
}).done(function (data, xhr) {
//hide loading
//success
}).fail(function (xhr) {
//hide loading
//error
});
Ok so I know long hand ajax but trying to use the jQuery short cut. I have two documents
form.php
submit.php
In my "form" page I am calling the "submit" page to process the insert. I am currently using the jquery ajax:
<script type="text/javascript">
jQuery('form').submit(function() {
string = jQuery("form").serializeArray();
jQuery.ajax({
type: "POST",
url: "submit.php",
data: string,
dataType: "json",
})
return false;
});
</script>
When I view firebug it is processing the ajax fine. I am getting 200 and post parameters are set. What I am trying to do is have the ajax return the submit.php file. I know it has something to do with the "success" function but I don't know how to add this. I tried a few things like:
<script type="text/javascript">
jQuery('form').submit(function() {
string = jQuery("form").serializeArray();
jQuery.ajax({
type: "POST",
url: "submit.php",
data: string,
dataType: "json",
success: function(html){
alert(html);
}
})
return false;
});
</script>
and
<script type="text/javascript">
jQuery('form').submit(function() {
string = jQuery("form").serializeArray();
jQuery.ajax({
type: "POST",
url: "submit.php",
data: string,
dataType: "json",
success: function(html){
$('.result').html(data);
}
})
return false;
});
</script>
but neither of these are working. Again I am simply trying to send the ajax request and then return the contents of the submit.php page. Not only does the submit.php page hold the script to process the php/ajax insert but it also display success statements like "insert was successful" so that is why I need to not only run the script in the page but also return the contents of that page. Thank you for any help.
Chagne the dataType:'json' to dataType:'html' for the callback that you wish to display the contents of submit.php.
You were close in your second attempt, but you made a typo. Try:
success: function (data) {
$('.result').html(data);
}
Also, unless your server is returning JSON, you probably want to change the dataType:
dataType: "html"