Let's say I have this script for example:
<script type="text/javascript">
function getdata() {
var referenceNumber = $("#reference_number").val();
$.ajax({
url: 'getlistofsomething.php',
type: 'POST',
dataType: 'json',
data: 'referenceNumber=' + referenceNumber,
success: function (output_string) {
$("#name").val(output_string[0]);
$("#address").val(output_string[1]);
}
});
}
</script>
Is there a way I can pass the value in $("#address").val(output_string[1]); into the PHP file this script above is in?
Thanks.
The easiest way is just to send it to the server using GET. Only do this if the data isn't very sensitive...
<script type="text/javascript">
function getdata()
{
var referenceNumber = $("#reference_number").val();
$.ajax({
url: 'getlistofsomething.php?address=' + $("#address").val(output_string[1]),
type: 'POST',
dataType: 'json',
data: 'referenceNumber='+referenceNumber,
success: function(output_string)
{
$("#name").val(output_string[0]);
$("#address").val(output_string[1]);
}
});
}
</script>
This can then be accessed in your php script with:
$address = $_GET['address'];
Related
In the View File
<script type="text/javascript">
function fetch_comp(val){
$.ajax({
type:"POST",
url:"<?php echo base_url()?>admin/admin_main/fetchData",
data:{'c_name':val},
datatype: "JSON",
success: function(data){
var obj = JSON.parse(data);
$("#job_description").val(obj.job_description);
$("#ctc").val(obj.ctc);
$("#location").val(obj.location);
}
})
}
</script>
In the Controller File
public function fetchData(){
$val = $this->input->post('c_name');
echo "<script>alert('$val');</script>";
}
The value is not being passed from the view page to controller page.
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)
});
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.
I try to receive a PHP response in my JavaScript.
My PHP looks like this:
some code
if(...) echo "1";
else echo "2";
JavaScript:
function GetChoice() {
var returned="";
$.ajax({
async: false,
cache: false,
url: "http://mydomain.com/script.php",
type: "POST",
dataType:"text",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);
But GetChoice() returns nothing. What's wrong?
UPD: It works if javascript and php script are on the same server. My scripts in different domains.
Try this :
temp1.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function GetChoice() {
var returned = "";
$.ajax({
async: false,
cache: false,
type: "POST",
url: "http://localhost/temp2.php",
data: { name: "John"}
}).done(function( msg ) {
returned = msg;
});
return returned;
}
var r = GetChoice();
alert(r);
</script>
temp2.php
<?php
echo $_REQUEST["name"];
?>
its working....!
try this:
function GetChoice() {
var returned = "";
$.ajax({
async:false,
cache:false,
url:"http://mydomain.com/script.php",
type:"POST",
dataType:"text",
success:function (data) {
alert(data);
}
});
}
The problem is, in your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.
Here is explanation.
How do I return the response from an asynchronous call?
Luck,
GetChoice() will return nothing before the callback in success runs.
The callback, which is the function you define as the success paramater will not fire until the data have been requested from the server.
This is asyncronous (the A in AJAX) so the rest of the code with continue causing the GetChoice() function to return before the callback has been run
this is the script
<script type="text/javascript">
$.ajax({
async:false,
cache:false,
url:"http://path.com/to/file",
type:"POST",
dataType: "html",
data: 'data',
success: function(data){
alert(data);
}
});
and in your PHP file write this code
<?php
function test()
{
$str = 'This is php file';
return $str;
}
echo test();
?>
Make sure the path to the php file is correct AND add the script in another PHP file. Basically you need 2 files. Just tested this in my editor and works ..
function GetChoice() {
var returned="";
$.ajax({
url: "../script.php",
type: "POST",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);