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)
});
Related
I have a simple code but is not working. I want to create a more complex function but I just need the basic structure.
HTML
<span class="cleanreport">Delete Record</span>
Javascript:
$( ".cleanreport" ).click(function() {
var token = "test";
$.ajax({
data: {"data": token},
type: "post",
url: "clean.php",
success: function (data) {
console.log(data);
$('.test').html(data);
}
});
});
PHP clean.php
$data = $_POST['data'];
echo $data;
What I am doing wrong?
This should work for you:
var token = "test";
$.ajax({
type: 'POST',
url: "clean.php",
data: {id: token},
dataType: "json",
success: function(response) {
// some debug could be here
},
error: function(a,b,c) {
// some debug could be here
}
});
If not, please debug success and error parameters using console.log().
Based on jquery documentation setting type is an alias for method so this could not be a problem in you case for sure.
$( ".cleanreport" ).click(function() {
var token = "test";
$.post('clean.php",
{
data: token
},
function (data,status) {
//console.log(data);
$('.test').html(data);
});
});
I have this code:
var name= "theName";
var surname= $('#surname').val();
$.ajax({
url: 'SaveEdit.php',
type: 'post',
data: { "callFunc1": whichOne},
success: function(response) {
alert(response);
}
});
It's working, but i need to do something like this:
var name= "theName";
var surname= $('#surname').val();
$.ajax({
url: 'SaveEdit.php',
type: 'post',
data: { "callFunc1": whichOne, name},
success: function(response) {
alert(response);
}
});
It gives me errors like:
Warning: missing argument 2 for func1()
I am using this code too:
function func1($data, $name){
//some code here
}
if (isset($_POST['callFunc1'])) {
echo func1($_POST['callFunc1']);
}
How to do it right?
Either create an array and pass as much as variable you want. otherwise try this:-
var name= "theName";
var surname= $('#surname').val();
$.ajax({
url: 'SaveEdit.php',
type: 'post',
data: { "callFunc1": whichOne,"callFunc2": name},
success: function(response) {
alert(response);
}
});
You should add a name to your secund parameter in the AJAX call. Don't forgot to pass it ot your function "func1".
Example:
if (isset($_POST['callFunc1'])) {
echo func1($_POST['callFunc1'], $_POST['callFunc2']);
}
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>
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.
What is wrong:
$('#click01').click(function(){
$a = 14;
$.ajax({
url : 'msg.php',
type : 'post',
data : {a:$a}
});
window.location = 'msg.php';
});
msg.php contains:
var_dump($_POST['a']); // NULL, but expected: 14
$('#click01').click(function(){
var a = 14;//not $a since this is javascript
$.ajax({
url : 'msg.php',
type : 'post',
data : {'a':a}
});
window.location = 'msg.php';
});
$('#click01').click(function(){
var a = 14
$.ajax({
type: "POST",
url: "msg.php",
data: {a:a},
beforeSend: function () {
// do action
},
success: function(html){
window.location = 'msg.php';
}
});
});
Rather than set the window.location you want to set a 'success' function on the ajax call so that when it finishes it takes the response and puts it into your page.
E.g. something like:
$('#click01').click(function(){
$a = 14;
$.ajax({
url : 'msg.php',
type : 'post',
data : {a:$a},
success: function(data, textStatus, jqXHR) {
$('#placeToPutTheResponse').append( data );
}
});
});
The above assumes that you have added an HTML node with the id="placeToPutTheResponse"
It is worth reading this other post on SO for a decent overview: jQuery Ajax POST example with PHP
It uses done rather than success, and slightly different syntax, but it's a great overview.
$(document).on('click','#click01',function () {
var a = 14;
$.ajax({
url: 'msg.php',
type: 'post',
data: {a: a},
success: function(e){
console.log(e);
},
error: function(e) {
console.log(e);
}
});
});
Try this
$('#click01').click(function(){
var a = 14;
$.ajax({
url : 'msg.php',
type : 'POST',
data : {a:a},
complete: function (data) {
console.log( data ); // this will tell you the output of var_dump.
window.location.href = 'msg.php';
}
});
// window.location = 'msg.php';
});
also this line window.location.href = 'msg.php'; in function complete will actually redirect you to the msg.php, so if you dont want any redirects remove those lines..