I'm trying to make an async call to the same page but for some reason, the async call is not being made and hence getting "userinfo" undefined error! could someone please tell me what I'm doing wrong in this thank you!
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$( document ).ready(function() {
//getting location of the user and assigning it to the variable
$.get("http://ipinfo.io", function (response) {
var usercity=response.city;
console.log(usercity);
$.ajax({
//no need to provide url since we are making async call on the same page
type: "post",
data: {cityinfo:usercity},
});
}, "jsonp");
});
</script>
<?php
session_start();
$usercity=$_POST['cityinfo'];
echo $usercity;
?>
First, you make a regular request to the PHP page. $_POST['cityinfo'] is undefined at this stage because you don't set it. The page includes an error message telling you that.
Second, you make a JSONP request to ipinfo.io, and call a callback function when you get a response.
Third, you make a second HTTP request to the PHP page. This time you do define $_POST['cityinfo']. You have no success handler to do anything at all with the response so, although $_POST['cityinfo']; is set, you don't see any effect of that (unless you were to use the developer tools Network tab to examine the response itself).
It is important to note that this is a second, distinct request to the same URL. The JavaScript does not travel back through time and set the $_POST['cityinfo']; variable in the previous request (and it is the response to the previous request that is still displayed in the browser window).
Related
I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing
I am doing a program in PHP (MVC) in which I need to delete a row from the database when I click on a link on the View side. So, when I click on the link, the following ajax function it is called.
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
}
});
}
but I do not want to send any data so it is the reason why I put it as above.
Then, in the Controller side I have the following method:
public function deleteCar($id)
{
//Here I call the function to delete the Car that I send by id. It works fine.
header('Location: http://localhost/project/car');
}
If I call directly the method deleteCar on the link without Ajax the header works properly but in the same moment I use Ajax to call it, I have to refresh the page to see the content that I have modified, I mean, that the Car have been deleted.
The code works fine, just I do not want to refresh the page after AJAX function had finished.
Thanks in advance!
I am guessing the use case is to allow the app to work when the user does not have JS enabled - so they just click the links and get a non-AJAX experience. In this case you probably want to redirect ONLY if the page was requested via GET, not POST. something like
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
header('Location: http://localhost/project/car');
}
is likely what you are looking for.
You will then have to actually remove the element representing the car from the DOM in your success handler, with something like:
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
$('#car-row-' + id).remove();
}
});
}
(that won't be it exactly, it depends how the HTML of your page is setup how exactly you will do this).
I believe the key thing to understand here is - when your PHP function has completed it has removed the car from the database, but the browser still has the same HTML it got from the page originally. Just sending an AJAX request won't change that. If you want the HTML in the browser to change to reflect the new state of the database, you will NEED to do one of two things:
Refresh the page, so the entire thing is rebuilt by PHP based on the current database state
Use javascript to change the HTML in the browser, to reflect the changes you have made to the database state.
It is wrong on so many levels but it's difficult to put in words. It's subtle.
Long story short - think about jquery.ajax as of another virtual tab of you browser.
When you make ajax-request to the server - you create new virtual tab.
You php header could affect this virtual tab and redirect it where that header defined.
But it will redirect that virtual tab, not your current tab - if that makes sense.
What are your options? On success - make redirect with pure javascript.
success: function(response){
location.href = "http://localhost/project/car";
}
This would be the basic way to solve your problem.
For some reason my jQuery AJAX request submits the first POST successfully, but then it causes a second GET which does not submit the post data, causing a Index Undefined error. When viewing the logs with Firebug, I see it does the first POST successfully posting the data I want to submit, but then it does a second GET request pulling the entire "SecondPage.php" file without posting any data, overriding the DIV it was set to display in.
Here's the code:
$(document).on('change', '.SubmitRadioButton', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'SecondPage.php',
cache: false,
data: $(this.form).serialize(),
success: function(html) {
window.alert('Successfully submitted AJAX request!');
$("#DIVinFirstPage").load("SecondPage.php");
}
});
return false;
});
What am I doing wrong?
Also - I have noticed that on this second PHP page I have to make a reference to my "Header.php" file that performs all the functions. Why is it that with this ajax request, it doesn't inherit all the rules from the page as a PHP include("File.php") does? Is there any way around this so I don't have to re-initialize and re-download all the PHP and JavaScript files? I tried include_once("File.php") in the PHP and that didn't correct it either.
jQuery load is the same thing as doing a $.get request. Is only a wrapper.
.load()
So you are basically doing a post request with some data on this part of the code
$.ajax({
type: 'post',
url: 'SecondPage.php',
cache: false,
data: $(this.form).serialize(),
success: function(html) {
window.alert('Successfully submitted AJAX request!');
And then inside the success making a get request to the same page on this line.
$("#DIVinFirstPage").load("SecondPage.php");
Then the page SecondPage.php is giving you an Index Undefined Error because SecondPage.php is expecting POST data which is not being sent in the .load call.
Since the Index Undefined is a php error, that sends the 500 error code to the browser.
So you need to either check if the variables are set using isset on SecondPage.php or make the load call another page that is not expecting any data.
Another alternative would be to have the script that handles the POST on a separate php file and then do the .load to the second page of your form.
In the success callback of the first POST request, you perform a JQuery load(). According to documentation http://api.jquery.com/load/, "It is roughly equivalent to $.get(url, data, success)".
You see your success callback function has a parameter named "html". That is the response served to your from SecondPage.php after the POST request. I imagine that contains the content you want to populate your div with.
Perhaps try:
success: function(html) {
window.alert('Successfully submitted AJAX request!');
$("#DIVinFirstPage").html(html);
}
i am sending ajax request from html page using jquery to send the bulk emails and fetch the data from the server.
here is the code to send request for bulk mail
var sendReq = $.ajax({
type: 'post',
data: "leftID="+JSON.stringify(leftID)+"&rightID="+JSON.stringify(rightID)+"&mode="+mode,
dataType: 'json',
url:"bulk.php"
});
sendReq.done(function( data ) {
$("#bms-ack").html(data.status);
$("#bms-ack").fadeIn('slow');
$("#bms-ack").fadeOut(6000);
console.log(data);
console.log("success");
});
sendReq.fail(function(jqXHR, data){
$("#bms-ack").html(data.status);
$("#bms-ack").fadeIn('slow');
$("#bms-ack").fadeOut(6000);
console.log("fail");
});
now the issue is when i send a request to php page it will send mails and respond with success message.
as the php is returning the response back to the client so will this ajax request going to get blocked ? because when i send another request from jqtable to fetch new data it takes time until the previous request of ajax to send bulk mail hans't finished. and eventually my jqtable keeps loading.
how do i get rid of blocking request , should i remove returning success message from php and if i do so then how the user will know that the request has been submitted ?
If I understand you correctly your issue is that you can't fire another javascript call while the first one is running? That's because Javascript is single-threaded in most browser implementations.
Some light reading:Is JavaScript guaranteed to be single-threaded?
As far as I know, if you send an AJAX petition, is exactly the same as requiring a new page in a non-asynchronous way: As long as the page is not sent to the browser, you keep waiting for the result, and any other request is just a refresh.
So, if you want to achieve a "non-blocking" AJAX way, send the AJAX petition to "differents" URLs. I mean:
url:"bulk.php" => Change to url: "bulk.php?v=3"
the query string is just a foo, and it's only to change the URL you're calling.
When you'll make your AJAX petitions, just add a query string for every petition you're doing (with a ?v=X is more than enough, where X could be even one of the data you're retrieving, the id of the row, whatever...), and it'll work like a charm, as the browser think is a different petition and don't prevent you (block you) to retrieve the values the PHP file is generating (although you know the values are different because you're sending different data, :D)
Update
Uhm... It should allow you keep working. Just for checking, could you try the next piece of code and tell me what happens?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
for(var $i=0; $i<5; $i++) {
$.ajax({
type: 'post',
url:"ajax.php?v="+$i,
success: function(data) {
console.log(data)
}
});
console.log('Browser: ' + $i);
}
});
</script>
</head>
<body>
AJAX TEST
</body>
</html>
AJAX File: (ajax.php)
<?php
sleep(5);
echo 'WAAAAAAAA';
To me, it sends 5 AJAX calls to the server at the same time (not blocking behaviour) almost immediately. I think that this is exactly what you want to achieve, could you test your browser and tell me if you're receiving the same? And by the way, could you post an image of the browser behaviour with the AJAX posts?
I'm trying to send an AJAX request to a page to interpret some data, and if it complies with what i'm looking for, send another AJAX request back. Right now I can see the first request is being made, but I'm not getting one back
//message.php
<head>
<script>
function org_name(str){
alert(str); //this alert appears, so I know the data is being received by this function
$.get("common_functions.php", { group_name: str} );
}
</script>
</head>
Then, on common_functions.php I have a similar request back, however, I'm not sure exactly what the issue is. The alert box doesn't even appear so I'm confused as to why the console would say the request was sent
//common_functions.php
if(isset($_GET['group_name'])){
?>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
alert('common_functions'); //this does not appear
$.get("message.php", { name: "test"} );
</script>
<?
}
When I open up the javascript console in chrome I see the request sent form message to common_functions, but apparently the request on common_functions isn't sending one back
//text from javascript console
Request URL:http://localhost/message/common_functions.php?group_name=test
Request Method:GET
Status Code:200 OK
Does anyone see something obvious that I'm doing wrong or missing? If it makes a difference, common_functions is included in message.php because I do use some other functions from that page for my php.
You have to do something with your data. Right now, you're making an AJAX call, and doing nothing with your data.
So something like the following would work:
$.ajax({
url: "common_functions.php",
data: { group_name: str },
type: "GET",
success: function (data) {
$(data).appendTo("head");
}
});
Use $.ajax if you want control over execution states:
$.ajax({
type: "POST",
url: "common_functions.php",
data: { name: "test"},
success: function(r)
{
// user r as output
},
error: function(xhr, ajaxOptions, thrownError)
{
// error report
alert(xhr.responseText);
}
});
In this case you can see if execution was successful or if error occurred.
Also you can use firebug add-on for firefox or chrome to detect if response was sent. There is also an excellent tool called Fidler, which can give you much better overview over request/response states.
Here is an excellent tutorial for ajax debugging.
$.get will strip out <script> tags. You can use another jQuery AJAX method load() that won't, or use $.getScript. If you need content and script you can do both by making an ajax request for the content, and in the success callback of that ajax, call for the script with $.getScript
load() replaces all the content in the specified selector
$('#myDiv').load('common_functions.php', { name: "test"})
Will take all the content of the php output and replace all the contents of #myDiv but will also run the scripts
you may use a library that does that for you automatically, using http://phery-php-ajax.net
in your case, it would be
function messages($data){
$r = new PheryResponse;
// return your messages
return $r->json($messages);
}
function common($data){
$r = new PheryResponse;
switch ($data['group_name']){
case 'messages':
$r
->include_script(array(
'jquery' => 'http://code.jquery.com/jquery-1.8.2.js'
))
->phery_remote('messages'); // load your messages
break;
}
return $r;
}
Phery::instance()->set(array(
'common' => 'common',
'messages' => 'messages'
))->process();
on your page load
$(function(){
phery.remote('common', {'group_name': 'messages'});
});
you don't have to do anything else. btw, if you are including jQuery AFTER you are using $.get(), it won't work, obviously