For some reason IE is asking us to download a file instead of running it as ajax. This works in all browsers except IE. I tried messing with the headers that it returns with no luck.
The function grabs form data then post's it the response is a can be an array of any number of items to be updated on the page.
Its not suppose to be file its suppose to be just a json response.
PHP
header('Content-type: application/json');
$error = "The Email and Password you entered could not be resolved.";
$elements[0]['target'] = '.error_report';
$elements[0]['action'] = 'inside';
$elements[0]['data'] = '<p>'.$error.'</p>';
$this->output->set_output(
json_encode(array("elements" => $elements))
);
Javascript
$(document).ready(function () {
jQuery.ajaxSetup({
cache: false,
dataType: 'json',
error: function () {
alert("Request was not successful. Please try again shortly.");
}
});
$(document).ajaxSuccess(function (e, xhr, settings) {
var response = xhr.responseText;
if (settings.dataType != 'json') {
return;
};
try {
response = jQuery.parseJSON(response);
} catch (e) {
alert(e);
return;
}
if (response.elements instanceof Array) {
var reqs = ['target', 'action'];
var valid = true;
for (var i=0;i<response.elements.length;i++) {
var cur = response.elements[i];
var sel;
for (var j=0;j<reqs.length;j++) {
if (typeof cur[reqs[j]] !== "string") {
valid = false;
break;
};
};
if (!valid) {
continue;
};
sel = $(cur.target);
switch (cur.action) {
case "inside":
sel.html(cur.data);
break;
case "instead":
sel.replaceWith(cur.data);
break;
case "remove":
sel.remove();
break;
case "refreshPage":
window.location.reload();
default:
if (typeof sel[cur.action] === "function") {
sel[cur.action](cur.data);
}; // else continue
break;
};
};
};
// Dispatch the AJAX request, and save it to the data object so that
// is can be referenced and cancelled if need be.
self.data('ajaxify.xhr', jQuery.ajax({
url: this.action,
type: 'post',
dataType: options.dataType,
data: (beforeSubmitIsJquery ? beforeSubmitResult.serialize()
: self.serialize()),
success: function (/**/) {
cleanup();
options.onSuccess.apply(that, arguments);
},
error: function (/**/) {
cleanup();
options.onError.apply(that, arguments);
},
complete: function (/**/) {
options.onComplete.apply(that, arguments);
}
}));
Related
Say I have a function as following. alert_danger returns the error message in red box. check_empty checks if a value posted from form is empty or not.
function alert_danger($msg){
$alert = "<div class='alert alert-danger' id='responseBox'>".$msg."</div>";
return $alert;
}
function checkEmpty($postValue, $msg){
if($postValue == null){
echo alert_danger($msg);
exit();
}
}
Now when I want to return the function value using jSON it's not returning the same. The following error is occuring:
// It returns this
$msg = alert_danger("Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
// But it does not returns this
$msg = checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
What seems to be the problem here?
Here is my jQuery if needed!
$(".action").click(function() {
var form = $(this).closest("form");
var type = form.find(".type").val();
var dataString = form.serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = form.attr("action");
$.ajax({
type: "POST",
dataType : "json",
url: url,
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json){
$('.message').html(json.status).fadeIn();
// $('#content').html(json.result).fadeIn();
$(".overlay").hide();
$("html, body").animate({ scrollTop: $(".message").offset().top }, "slow");
btnElement.html(btnValue);
if(type == 'admin'){
if($('.message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
$(".overlay").hide();
window.location.replace("dashboard.php");
}, 1000);
}
}
}
});
return false;
});
Consider the following.
PHP
<?php
function checkEmpty($postValue, $msg){
return $postValue == null ? array("status" => "error", "message" => "Empty Value") : array("status" => $postValue, "message" => $message);
}
header('Content-Type: application/json');
echo json_encode(checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!"););
?>
JavaScript
function redirectTo(url, time) {
if (!url) {
return false;
}
time = time != undefined ? time : 0;
setTimeout(function() {
window.location.href = url;
}, time);
}
$(".action").click(function() {
$(this).closest("form").submit();
});
$("form").submit(function(event) {
event.preventDefault();
var type = $(this).find(".type").val();
var dataString = $(this).serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = $(this).attr("action");
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: dataString,
cache: true,
beforeSend: function() {
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json) {
if (json.status == "error") {
$(".message").html("<div class='alert alert-danger error'>" + json.message + "</div>").fadeIn();
} else {
$('.message').html("<div class='alert alert-danger'>" + json.message + "</div>").fadeIn();
$("html, body").animate({
scrollTop: $(".message").offset().top
}, "slow");
btnElement.html(btnValue);
if (type == 'admin') {
if ($('.message').find('#responseBox').hasClass('alert-success')) {
redirectTo("dashboard.php", 1000);
}
}
}
}
});
return false;
});
Typically, it is bad practice to use language X to generate code in language Y. Try decoupling the two languages by making data their only interface -- don't mingle the code.
https://softwareengineering.stackexchange.com/questions/126671/is-it-considered-bad-practice-to-have-php-in-your-javascript
You have to be careful to not confuse echo and return, they do very different things.
https://www.php.net/manual/en/function.echo.php
https://www.php.net/manual/en/function.return.php
Since you're passing back JSON data to the AJAX Call, I would advise wrapping your HTML inside the callback versus sending it back inside the JSON.
I think you should take a look at your success function. I think it normally runs before the page loads. So, its possible none of the html your referencing in there exists yet. So move it out to a function like this:
success: function(json) {
doSomething();
}
function doSomething(json){
$( document ).ready(function() {
console.log('page has loaded now modify your html with jquery'+json);
}
}
I'm very new with Ajax and I need help to store the data from an Ajax request into an array. I looked at answers here at the forum, but I'm not able to solve my problem.The Ajax response is going into $('#responseField').val(format(output.response)) and I'm want store "output.response" into an array that can be used outside of the Ajax. I tried to declare a variable outside of the Ajax and call it later, but without success. I'm using $json_arr that should get the data. How do I do to get the data from the Ajax and store it in a variable to be used outside of the Ajax? This variable will an array that I can access the indexes.
function sendRequest(postData, hasFile) {
function format(resp) {
try {
var json = JSON.parse(resp);
return JSON.stringify(json, null, '\t');
} catch(e) {
return resp;
}
}
var value; // grade item
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
$json_arr=$('#responseField').val(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
window.alert($json_arr);
let promise = new Promise(function(resolve, reject) {
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
resolve(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
});
promise.then(
function(result) { /* you can alert a successful result here */ },
function(error) { /* handle an error */ }
);
The issue is you are calling asynchronously.
You call the alert synchronously, but it should be called asynchronously.
A little snippet to help you see the difference:
// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';
function sendRequest() {
$.ajax({
// dummy REST API endpoint
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "Alert from AJAX success",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response);
$json_arr = response.name;
// this window.alert will appear second
window.alert($json_arr);
}
});
}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I used this system.. sendind a json with success = 0 or 1 depending on success or error, is this correct or there is a better more correct method to pass true or false to the ajax call?
if (empty($item)) {
// add to the DB
$return['success'] = 0;
return Response()->json($return);
} else {
$return['success'] = 0;
$return['message'] = "Already in Collection";
return Response()->json($return);
}
then in Ajax:
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", ".dynamic-form", function (e) {
var form = $(this);
var span = $(form).find('input[name="span_id"]').val();
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
if (data.success == 1) {
alert("success");
}
else if (data.success == 0) {
alert("error");
}
}
});
e.preventDefault();
});
});
});
I use true or false and then compare like that if (data.success).
If you want a boolean send a boolean, but it's just my opinion.
This depends only on you, you can save your success as you do or to status...
<?php
if (empty($item)) {
// add to the DB
$return['success'] = true;
} else {
$return['success'] = false;
$return['message'] = "Already in Collection";
}
return Response()->json($return);
i am new to cakephp and trying to send data from ajax to my controller action..
i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh
here is my code ..
<a class="button anthracite-gradient" onclick="openPrompt()">submit </a>
my javascript
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
url:"/cakephp/controller/action/",
success : function(data) {
alert(value); //value right now is in this variable ... i want to send this variable value to the controller
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
myController
public function action(){
if( $this->request->is('ajax') ) {
$new = $this->request->data;
echo "ok"
return;
}
}
i want to first get the value here and then send the response to may ajax request
Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
data:{value_to_send:value},
url:"/cakephp/controller/action/",
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
public function action(){
if( $this->request->is('ajax') ) {
// echo $_POST['value_to_send'];
echo $value = $this->request->data('value_to_send');
//or debug($this->request->data);
echo "ok"
die();
}
}
For more see accessing-post-data
I will give you some example. In my case, list out book list as a smart search while typing on text box.
$( ".selectBook" ).each(function(){
$(this).keyup(function( event ) {
var tri = $(this).val();
var oPrnt = $(this).parents('.smartsearch');
var str = '';
if(tri.length > 2){
$.ajax({
type: "POST",
url: "/utility/getbooks/",
data: JSON.stringify({string: tri, activeonly:false}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function(key, val) {
str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
});
oPrnt.find("ul.result").html(str);
},
error: function (errormessage) {
oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
}
});
oPrnt.find("ul.result").slideDown(100);
}
});
});
And in the controller, action (getbooks Action in UtilityController in my case)
public function getbooks($string = '', $activeonly = true){
$this->autoRender = false;
if( $this->request->is('ajax') ) {
$data = $this->request->input('json_decode');
$string = $data->string;
$activeonly = $data->activeonly;
}
$aReturn = array();
// ... fetch books data from DB goes here...
$aResult = $this->Book->fetch('list');
foreach($aResult as $r){
if(isset($r['bookname'])){
$aReturn[$r['id']] = $r['bookname'];
}
}
return json_encode($aReturn);
}
I was wondering if I can return an error callback back to my jquery from my php page that I created, which will then display an alert based upon the actions that happen in my php page. I tried creating a header with a 404 error but that didn't seem to work.
Sample JQuery Code:
$(document).ready(function()
{
var messageid= '12233122abdbc';
var url = 'https://mail.google.com/mail/u/0/#all/' + messageid;
var encodedurl = encodeURIComponent(url);
var emailSubject = 'Testing123';
var fromName = 'email#emailtest.com';
var dataValues = "subject=" + emailSubject + "&url=" + encodedurl + "&from=" + fromName + "&messageID=" + messageid;
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function() {
alert('ERROR - MessageID Duplicate')
}
});
return false;
});
});
Sample PHP Code aka somepage.php:
<?php
include_once('test1.php');
include_once('test2.php');
if(isset($_GET['subject']))
{
$subject=$_GET['subject'];
}
else
{
$subject="";
}
if(isset($_GET['url']))
{
$url=$_GET['url'];
}
else
{
$url="";
}
if(isset($_GET['from']))
{
$from=$_GET['from'];
}
else
{
$from="";
}
if(isset($_GET['messageID']))
{
$messageID = $_GET['messageID'];
}
else
{
$messageID="";
}
$stoqbq = new test2($from, $messageID);
$msgID = new stoqbq->getMessageID();
if($msgID = $messageID)
{
header("HTTP/1.0 404 Not Found");
exit;
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
}
?>
-EDIT-
If you get the invalid label message when using json this is what I did to fix this problem:
Server Side PHP Code Part-
if($msgID == $messageID)
{
$response["success"] = "Error: Message Already In Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new SendToQuickbase($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
$response["success"] = "Success: Sent To Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
Client Side JQuery Part-
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
cache: false,
contentType: "application/json",
dataType: "json",
url: "http://somepage.php?&callback=?",
success: function(response){
alert(response.success);
}
});
return false;
});
You can a return a JSON response from your PHP with a success boolean.
if($msgID = $messageID)
{
echo json_encode(array('success' => false));
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
echo json_encode(array('success' => true));
}
and in your Javascript:
$.ajax({
type: 'GET',
dataType: 'json',
data: dataValues,
url: 'http://somepage.php',
success: function(response){
if(response.success) {
alert('Success');
}
else {
alert('Failure');
}
}
});
There is an accepted q/a with the same thing: How to get the jQuery $.ajax error response text?
Basically you need to grab the response message from the error callback function:
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});