This question already has answers here:
PHP trigger AJAX error code without using array
(4 answers)
Closed 6 years ago.
I am using jquery ajax to retrieve data from a php function.
My php function is as follows
<?php
if(isset($_GET['action'])) {
$data = array();
$data[0]["field"] = "data";
echo json_encode($data);
} else {
// error
return;
}
?>
and I am calling using the jquery ajax in my javascript
$.ajax({
url : '../functions/php/function.php',
type : 'GET',
dataType : 'json',
data : {'wrong','wrong'},
success : function(data) { console.log('all ok') },
error : function(log) { console.log('not ok') }
});
Instead of just returning from the php function with nothing is it possible to retrieve an error so that the jquery executes the error function?
You can set header with any http status code lets say 400 http_response_code(400). When jQuery Ajax function sees the status code other than 200 it will execute your error callback function.
Related
This question already has answers here:
Page redirect with successful Ajax request
(10 answers)
Redirect with PHP after ajax call
(5 answers)
Closed 2 years ago.
I have a button which I want to call a php script which does some stuff followed by a redirect to a new page based on that stuff. Relevant Code is:
HTML:
<button onclick="newTourney()">New Tournament</button><br>
and
<script>
function newTourney(){
var name = prompt("Tournament Name:");
$.ajax({
url: "new_tournament.php",
method: "POST",
data: {name: name}
});
}
</script>
new_tournament.php (including ob_...() and error reporting enabled to try to fix this):
<?php
use general\orm\UsbgfGenOrm;
use trn\interfaces\Usbgf\UsbgfUtil;
use trn\orm\DimEvent;
use trn\orm\DimTournament;
include_once __DIR__ . "\..\usbgf_bootstrap.php";
ob_start();
$club = UsbgfUtil::getOnlineCircuitClub();
$tournament = new DimTournament($club);
$event = new DimEvent($tournament);
error_reporting(E_ALL);
ini_set('display_errors', true);
if(isset($_POST["name"])){
$tournament->Name = $_POST["name"];
$event->Name = $_POST["name"];
}
$tourneyId = $tournament->getId();
ob_end_clean();
header("Location: edit_tourney.php?id=" . $tourneyId);
exit;
It simply isn't doing anything whatsoever when the button is pressed. I've tried printing the response from the ajax call like so:
$.ajax({
url: "new_tournament.php",
method: "POST",
data: {name: name},
complete: function(response){
console.log(response.responseText);
}
});
When I do this, it prints the entire html from the page I'm trying to redirect to (and any other echos) to the console, so its definitely accessing the correct files at least.
My best guess is that something about $.ajax doesn't allow for redirects or something like that? I'm not sure what to replace it with but I use a similar ajax call elsewhere to a script without a redirect and it works just fine.
This question already has answers here:
Ajax return value with return not work
(2 answers)
Closed 3 years ago.
I have two php files one is index.php and other is phpscriptname.php. i need to call differet functions by using ajax and case method. i found a solution in a website which i give below, but this is not working.
index.php as below
<script>
$.ajax({ url: 'phpscriptname.php',
data: {function2call: 'getEmployeesList'},
type: 'post',
success: function(output) {
alert(output);
}
});
</script>
phpscriptname.php as below
<?php?
if(isset($_POST['function2call']) && !empty($_POST['function2call'])) {
$function2call = $_POST['function2call'];
switch($function2call) {
case 'getEmployeesList' : getEmployeesList();break;
}
}
function getEmployeesList(){
return "hai";
}
?>
i was expected "hai" in a popup. but it is not working.
alert(output); will not return anything becuase you are using return for getting plain text response from PHP, you need to use echo instead return in your method.
Second solution is that, if you want to use return in your method then you can modify your switch case as:
if(isset($_POST['function2call']) && !empty($_POST['function2call'])) {
$data = ''; // initialize in default
$function2call = $_POST['function2call'];
switch($function2call) {
case 'getEmployeesList':
$data = getEmployeesList();
break;
}
echo $data;
}
Im creating a validation form in Ajax and PHP. But i don't have a clue how i should get the value from PHP??
For example:
The validation form is in index.php And the page with the function is checkUser.php.
In checkUser i have a global file included with my classes initialized. The checkUser.php look like this:
<?php
$requser = false;
require "core/rules/glb.php";
$user->checkUser($_GET['username']);
The get function comes from the Ajax call i do in the index file. But how do i know that PHP said that the username already exist så that i can make a if statement and paus the script?
Im a beginner, thanks.
And sorry for my english
$.ajax({
type: "GET",
url: "user_add.php",
data: 'username='+$("#jusername").val()+'&email='+$("#jemail").val()+'&password='+$("#jpassword").val()+'&secureSession=23265s"',
success: function()
{
location.href='register.php';
}
});
Jus print out the data, for better help also post the ajax script
<?php
$requser = false;
require "core/rules/glb.php";
print $user->checkUser($_GET['username']);
If you are trying to give a response to the ajax call from php, then you can do it via normal output. Just like
echo json_encode(array("status"=>"FAIL"));
exit();
will send a json response to the ajax call from the php script. like
{"status":"FAIL"}
which you can parse it at the ajax callback and check the status. like
var data = JSON.parse(response);
if(data.status == "FAIL") {
alert("Ajax call returned failed");
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am using AJAX to call a PHP file that does email validation and outputs simple text that gets returned to the AJAX Success. I am using the text returned to create variables to represent which error to display. I am having trouble using these variables, the form still submits. What could I be doing wrong?
My Code:
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
success: function(data) {
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
}
});
}
if (invalid == 1) {
alert('invalid email');
error= true;
}
if (taken == 1) {
alert('email taken');
error= true;
}
if (error == true) {
return false;
}
Is this AJAX call inside a click event? If so, you may want to use event.preventDefault() function to avoid triggering the form submission:
event.preventDefault();
Have a look to the example in the documentation
You should have two things in consideration:
1) if you're ajax call is triggered by a link or submit button , you MUST use preventDefault function
2) in your "checkmail.php" don't forget to call exit function in the end of call
This question already has answers here:
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
this is my first question at stackoverflow, speaking specifically ... i am using the result of my PHP file ("myphp.php") ...
<?php
echo "Hello"
?>
now the javascript code that was called :
function functionX()
{
var result;
$.post("myphp.php",function(data)
{
result=data; /// result should be Hello
});
alert(result); /// the msgbox shows "Undefined"
// i am enable to access the result i got from PHP file
}
So my problem is how to access the result , so that i can use it at other parts of my code ...
OR can you suggest some other ways .. THANXX
as i am a newbie to ajax .. i want to use this concept for checking username availability as shown
var result;
function functionX(username)
{
$.post("check_username.php",{usn:username},function(data)
{
if(data=="OK"){result="yes";}
if(data=="FAIL"){result="no";}
});
alert(result); // Now i want the result here .. its important
}
<?php
$usn=$_POST['usn'];
$flag=0;
$q=mysql_query("SELECT * FROM accounts");
while($row=mysql_fetch_assoc($q))
{
if($row['usn']==$usn)
{
$flag=1;break;
}
}
if($flag==1)
{
echo "OK";}
else
echo "FAIL";
?>
i know these methods for detecting username existence can be silly .. so that's what i did
try this
var result;
$.ajax({
type: "POST",
url: 'myphp.php',
success: function (data) {
result=data;
}
});
alert(result);
It's because if you just put the code below it doesn't mean after as raina77ow mentioned.
If you don't need the data later just use this:
function functionX(){
$.post("myphp.php",function(data) {
alert(data);
});
}