ajax post with PHP - php

why isn't this working?
jQuery AJAX Code:
$("header input").bind("keyup", function()
{
var searchString= $("header input").val();
var dataString = 'search=' + searchString;
alert(dataString);
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false
});
});
PHP Code(Just a test Code):
if($_POST["search"]) {
echo "TEST MESSAGE!";
}
It doesn't show The echo :/
thanks for ur help ;)

You need to display the data you receive from the ajax call.
Example, to put the result into a <div> called YourresultDiv:
Try with this
$("header input").on("keyup", function () {
var searchString = $("header input").val();
var dataString = 'search=' + searchString;
alert(dataString);
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (data) {
$('#YourresultDiv').html(data);
alert("Successful");
}
});
});

Hopes this will help you....
$("header input").bind("keyup", function()
{
var searchString= $("header input").val();
var dataString = 'search=' + searchString;
alert(dataString);
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
async: false
},success: function (data) {
$('div#posteddata').append(data);
}
);
});
<html>
<head>
</head>
<body>
<div id="posteddata"></div>
</body>
</html>

You need to specify an element you want to update.. for example
<div id="result"> </div>
and then append a success event handler to your ajax call
$("header input").bind("keyup", function () {
var searchString = $("header input").val();
var dataString = 'search=' + searchString;
alert(dataString);
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false
}).success(function (data) {
$("#result").html(data);
}).fail(function () {
alert("Ajax failed!");
});
});

Try with this
In js add
success: function (data) {
// success handler
}
as your response handler
if($_POST["data"]) {
// search = search string available here in $_POST['data']
echo "TEST MESSAGE!";
}

where is your call back function in $.ajax() function,with callback function only,you can display anything through an ajax request..
So try this.
$("header input").on("keyup", function () {
var searchString = $("header input").val();
var dataString = 'search=' + searchString;
alert(dataString);
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (data) {
$('#Yourdiv').html(data); // or $('#Yourdiv')text(data);
}
});
});
Without success function,you can see the echoed statement in your network segment in console.
for that, press F12,then you will get a link like
XHR finished loading: POST "http://localhost/yourproject/func_name.Click on that link and you will goto network segment and from there,click on the function name and then in response or preview tab,you canb see the echoed statement..
try it.

Related

How can I send a response in Ajax through php script

I need to send a response from the ajax to the php code. Alert msg as to be displayed when success.. I have to get entered date should be displayed in the url and response as to be sent..
<script>
$(document).ready(function() {
$('#txtdate').change(function(){
date = $(this).val();
$.ajax({
type: 'GET',
url: "http://localhost/data/check_date.php?date=" +date ,
success: function() {
alert(data);
}
});
});
});
</script>
Two error:
1:
date = $(this).val();
to
var date = $(this).val();
2:
url: "http://localhost/data/check_date.php?date=" +date ",
to
url: "http://localhost/data/check_date.php?date=" +date ,
3:
success: function() {
to
success: function(data) {
All script:
<script>
$(document).ready(function() {
$('#txtdate').change(function(){
var date = $(this).val();
$.ajax({
type: 'GET',
url: "http://localhost/data/check_date.php?date=" +date ,
success: function(data) {
alert(data);
}
});
});
});
</script>
Remove " mentioned at the end of the url because date is variable to be passed through url.
To overcome all mistakes change your whole code to
<script>
$(document).ready(function() {
$('#txtdate').change(function(){
var date = $(this).val();
$.ajax({
type: 'GET',
url: "http://localhost/data/check_date.php?date=" +date,
success: function(date) {
alert(date);
}
});
});
});
</script>
var date = $(this).val();
$.ajax({
type: 'GET',
url: "http://localhost/data/check_date.php?date=" +date ,
dataType: 'text',
success: function(data) { //add data in the function which is returned from the file
alert(data);
}
});
also try opening your network tab by clicking F12 in your browser before doing ajax request, if there's some error in your php file you can view it here in network tab, see if it helps

when I send data with ajax php wont get anything

post and get works fine but json returns wrong value , or something is wrong with my php code.
$(function () {
$('#username').on('keypress',function () {
var input = $('#username').val();
if(input.length>=4){
$.ajax({
url:'registration_php.php',
type: 'POST',
data:{username:input},
success:function () {
$.getJSON('registration_php.php',function (text) {
alert(text.user);
});
}
});
}
});
});
success:function(result) {
var items = JSON.parse(result);
alert(items['user']);
}
pass the result directly to your reponse as an argument like this
you should specify a dataType: "json" in your ajax call
var postData = JSON.stringify({
username: 'value'
});
var request = $.ajax({
url: "registration_php.php",
method: "POST",
dataType: "json",
data: postData,
});
request.success(function( results ) {
console.log(results)
});

How to utilize the Ajax call success return data to php code for running mysql query in same file

I am getting data from ajax call. But that data is coming in Jquery and I have saved it in a variable. Now I want that data to be utilized for running some php and mysql code. Can any one solve this?
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result) {
alert(result);
//$('.alert').show().html(result).delay(2000).fadeOut(3000);
setTimeout(function(){window.location.href = "index.php";},2000);
}
});
}
return result;
});
If what you want is to navigate to the index.php page on click of that button, then, do it this way:
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result) {
alert(result); //you may remove this. use console.log for debugging your js next time
setTimeout(function(){window.location.href = "index.php?result="+result;},2000); //why the timeout?
}
});
}
});
The easier and proper solution should be to re-use ajax to use this variable in another PHP file.
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result)
{
//AJAX code to execute your MySQL query
$.ajax({
type: "POST",
url: "read_data2.php",
data: result,
cache: false,
success: function (result)
{
//Manage your read_data2.php output
}
});
}
});
}

how to pass whole data using ajax in php using keypress event

I am passing empcode using key press event, but my whole empcode is not transfered and the last digit is cut.
Here is my code:
$(document).ready(function(){
$("#e_code").keypress(function(){
//var dataString=document.getElementById("e_code").value;
var dataString = 'e_code='+ $(this).val();
$.ajax({
type: "POST",
url: "getdata.php",
data: dataString,
cache: false,
success: function (html) {
$('#details').html(html);
$('#custTrnHistory').show()
}
});
});
});
on getdata file code is
write code in keyup instead of keypress
$("#e_code").keyup(function(){
You can bind your keypress on document --- try this
$(document).on('keypress',"#e_code",function(){
Try this
$(document).ready(function(){
var minlength = 5; //change as per the the length of empcode
$("#e_code").keyup(function () {
var inputvalue= $(this).val();
if (inputvalue.length >= minlength ) {
var dataString = 'e_code='+ $(this).val();
$.ajax({
type: "POST",
url: "getdata.php",
data: dataString,
cache: false,
success: function (html) {
$('#details').html(html);
$('#custTrnHistory').show()
}
});
}
});
});

refresh div after sending data to db

i have a div that shows the total sum of some products:
<div class="total-price"><?php echo (!empty($cart)) ? $cart['total'] : '0'; ?> $</div>
with ajax, i'm adding products to cart ... se the page is not reloading.
How to refresh the div after I add the product to cart?
The ajax that i'm using:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
$(".total-price").something...;
}
});
})
</script>
Thank you!
You can do something like this:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
var oldPrice = $('.total-price').text() * 1;
var itemPrice = "15"; //the price that should be added
$('.total-price').text(oldPrice + itemPrice);
}
});
})
</script>
You should be returning a total basket value from your /tdt/order path.
In the PHP script you should echo some JSON data with all the required information, for example
echo json_encode(array("totalPrice" => "£10.01"));
Then you need to parse this information into your Javascript and update the pages elements;
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
$(".success-message").slideDown().delay(5000).slideUp();
$('.total-price').val(data.totalPrice);
}
});
})
</script>
The above ajax request will expect the data returned to be JSON, you will then use this to update the total-price element.
You can use something like angularjs or knockoutjs - for angular you would update your model - for knockout you would use the self.object.push(value) i.e.,
function OrderViewModel() {
var self = this;
self.myOrder = ko.observableArray([]);
self.addOrderItem = function () {
$.ajax({
type: "post",
url: "yourURL",
data: $("#YOURFORMFIELDID").serialize(),
dataType: "json",
success: function (value) {
self.myOrder.push(value);
},
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
}
}
ko.applyBindings(new orderViewModel());
</script>
</pre>

Categories