I have ext js panel component that when submited it throws js error in firebug console.
I says
'You're trying to decode an invalid JSON String: <html>
... index.php html code here
</html><!-- use login javascript file --> <!--<script type="text/javascript" src="http://localhost:9808/recorder/js/login.js"></script>-->
<script type="text/javascript">
login = true;
</script>
<div id="login_window"> </div>' when calling method:
[nsIDOMEventListener::handleEvent]
Intersting is that the html code get concatenated with some additinal html after the "html" tag. and I get index.php html code instead of json. As far as I knwo check() function I call ecoes only json data.
My component code is like this
login_group_combo = Ext.create('Ext.form.ComboBox',
{
name: 'combo_name',
id: 'combo_id',
fieldLabel: text_label,
editable: false,
//possible view options
store: [
],
listeners:
{
focus: function(elem, e)
{
function1();
}
}
});
function1() look like this
function function1(){
form1.submit({
url: './index.php/mypage/check',
success: function(f,a){
// some code here
echo json_encode($result_array);
},
failure: function(form, action){
switch (action.failureType) {
case Ext.form.action.Action.CLIENT_INVALID:
Ext.Msg.alert('Failure', 'Invalid data entered!');
break;
case Ext.form.action.Action.CONNECT_FAILURE:
Ext.Msg.alert('Failure', 'Ajax communication failed');
break;
case Ext.form.action.Action.SERVER_INVALID:
Ext.Msg.alert('Failure', action.result.msg);
}
}
});
}
The intersting thing is that the execution enters function1(); but doesnt enter form1, success or neither faulire blocks. What could be the problem?
If you load ./index.php/mypage/check in your browser and view source, do you see json or html? Often something in the server framework is putting in the html via header and footer layout code or similiar and some config needs to be set so you can return raw json strings.
Related
I have a jQuery validation script that is working perfectly with the except of the event handler. I have simplified this post for troubleshooting purposes.
jQuery
submitHandler: function (form) {
$.ajax({
type: $(form).attr("method"),
url: $(form).attr("action"),
data: $(form).serialize(),
dataType : "json"
})
.done(function (data) {
if (data.resp > 0 ) {
alert(data.message);
}
});
return false; // required to block normal submit since you used ajax
},
// rest of the validation below, truncated for clarity
The submitHandler successfully posts to my PHP script that adds a user to a database and then echoes back a json_encode() result.
PHP
<?php
// All processing code above this line has been truncated for brevity
if($rows == "1"){
$resp = array("resp"=>1, "message"=>"Account created successfully. Waiting for user activation.");
}else{
$resp = array("resp"=>2, "message"=>"User account already exists.");
}
echo json_encode($resp);
?>
As you can see the idea is simple. Alert the user with the proper response message. When I run my script the user account is added successfully to the database but no alert is displayed to the user. The Console in Chrome shows no errors, what am I missing?
The data variable in the done() is a string. You have to transform it to an object like this
var response = $.parseJSON(data);
in order to access the attributes
I am sorry I missed dataType : "json" in your code in my previous answer.
Any way I tried your code and it is working. The alert shows the message. I think you have an error somewhere else. I think it has some thing to do with the array you are encoding to json(PHP part). The response you get is not complete. Try to debug your PHP and test the page separately from AJAX and see what is the result
After some tinkering I was able to get things working the way I wanted. Here's the updated code.
jQuery
.done(function (data) {
$("#user_add_dialog").dialog({
autoOpen: false,
modal: true,
close: function (event, ui) {
},
title: "Add User",
resizable: false,
width: 500,
height: "auto"
});
$("#user_add_dialog").html(data.message);
$("#user_add_dialog").dialog("open");
});
return false; // required to block normal submit since you used ajax
PHP
<?php
// All processing code above this line has been truncated for brevity
if($rows == "1"){
$resp = array("message"=>"Account created successfully. Waiting for user activation.");
}else{
$resp = array("message"=>"User account already exists.");
}
echo json_encode($resp);
?>
I am very new to PHP and Javascript.
Now I am running a PHP Script by using but it redirect to another page.
the code is
<a name='update_status' target='_top'
href='updateRCstatus.php?rxdtime=".$time."&txid=".$txid."&balance=".$balance."&ref=".$ref."'>Update</a>
How do I execute this code without redirecting to another page and get a popup of success and fail alert message.
My script code is -
<?PHP
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
-------- SQL Query --------
?>
Thanks in advance.
You will need to use AJAX to do this. Here is a simple example:
HTML
Just a simple link, like you have in the question. However I'm going to modify the structure a bit to keep it a bit cleaner:
<a id='update_status' href='updateRCstatus.php' data-rxdtime='$time' data-txid='$txid' data-balance='$balance' data-ref='$ref'>Update</a>
I'm assuming here that this code is a double-quoted string with interpolated variables.
JavaScript
Since you tagged jQuery... I'll use jQuery :)
The browser will listen for a click event on the link and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.
As you can see, I'm using .data() to get the GET parameters.
$(document).ready(function() {
$('#update_status').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
rxdtime: $(this).data('rxdtime'),
txid: $(this).data('txid'),
balance: $(this).data('balance'),
ref: $(this).data('ref')
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});
PHP
Looks like you know what you're doing here. The important thing is to output the appropriate data type.
<?php
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
header('Content-Type: text/plain; charset=utf-8');
// -------- SQL Query -------
// your logic here will vary
try {
// ...
echo 'success';
} catch(PDOException $e) {
echo $e->getMessage();
}
Instead of <a href>, use ajax to pass the values to your php and get the result back-
$.post('updateRCstatus/test.html', { 'rxdtime': <?php ecdho $time ?>, OTHER_PARAMS },
function(data) {
alert(data);
});
I'm dealing with how to send successful response to jquery's iframe post form plugin.
With the help of the source code of the plugin's demonstration, I can see that there is the following code below: (Click here for source)
complete : function (response)
{
var style,
width,
html = '';
if (!response.success)
// I've always came to this block! And that is exactly the problem that I have
{
$('.message').slideUp(function ()
{
$(this)
.html('There was a problem with the image you uploaded')
.css({
color : '#9c0006',
background : '#ffc7ce',
borderColor : '#9c0006'
})
.slideDown();
});
}
else /***** When is the response successful and when will code come here? *****/
{
/*
following code goes here...
*/
}
}
The exact question is that when do the response.success will be TRUE? And how should I set it to TRUE with PHP? (Please answer both with and without JSON style)
when you run ajax and communicate with php. youre going to grab whatever php echoes out and use that. in this case its probably wisest to use json encode. heres a very basic example to give you an idea.
a php file:
echo json_encode(array('success' => true));
now a basic ajax request
$.ajax({url:"ajax.php",success:function(result){
result = $.parseJSON(result); // we do this to convert the php into javascript format
if(result.success){
alert('this is true');
}
}});
This ajax code posts the variables and displays $('#data').html(data); which is been eco-ed in php.-which works
$.post('login.php',{username:username,password:password},
function(data)
{
$('#data').html(data);
if (data=='login'){
alert("sucess");
}
});
However the problem lies on the next line which does not work:
if (data == 'login') {
alert("sucess");
}
This code is supposed to show a dialog box if the data == login
I have looked through different tutorials and this code is supposed to be working but its doesn't for some reason.
Thanks!
You can simply put JSON data Type and use json array as response..
$.post('login.php',{username:username,password:password},
function(data)
{
if (data.status=='login'){
$('#data').html(data.status);
alert("sucess");
} else{
alert('not login');
}
}, 'json');
And in your PHP
<?php
#.. put any code before that response because after it you must put exit.
# No other data except it must be sent! Else you will break it..
echo json_encode(array('status'=>'login'));
exit();
data holds the return result of the response of login.php.
In your case it probaly returns html, like <h1> welcome user x</h1> (I don't know what your code returns so it is an exampe).
If that is the case, you code should check if that is valid. I suggest using JSON. Your login.php checks the login data. If the login attempt is valid you return login: true; And redirect the user.
When in valid just return the data errors and show them with jquery.
Use this code, if your response fails you will get proper alert.
var jqxhr = $.post("login.php", {username : username, password : password}, function(data) {
alert("success" + data);
console.log(data);
},'text')
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
else you will get alerted by "succes" and your data.
More information how to use this function you can find on http://api.jquery.com/jQuery.post/
To be sure it works. Put in login.php
<?php
echo 'ajax works';
exit;
?>
You use old functions that will be removed. Use PDO or other engine.
Your code is not secure. SQL Injections are possible.
I am doing a simple ajax request to another domain like this:
<script type="text/javascript">
$(function() {
$('.clik').click(function() {
$.ajax({
type: "POST",
url: "http://sub.mydomain.com/test.php",
crossDomain: true,
dataType:"jsonp",
success: function(data) {
$('p.txt').html(data['no']);
}
});
});
});
</script>
</head>
<body>
<p class="clik">Halleluja</p>
<p class="txt"></p>
this is the test.php page on sub.mydomain.com
<?
header('Access-Control-Allow-Origin: http://mydomain.com');
// Begin Session
require_once('cl.session.php');
$session = new Session();
$session->start_session('test', false);
// Access Database
require_once('cl.database.php');
$login_db = new Database('user', 'pass', 'accounts', 'test');
$login_pdo = $login_db->PDO;
include "fn.check_login.php";
if(checkLogin($login_pdo) == true) {
// We start out by checking if the request has been made using AJAX
if (is_ajax()) {
echo "this is working";
} else {
echo "this is not working!";
}
} else {
echo 'You are not authorized to access this page, please login. <br/>';
}
// Function to check if the request is an AJAX request
function is_ajax() {
// BOOLEAN return if AJAX
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?>
It returns a semantic issue.
Also if I simply echo some basic text:
<?
echo "Hello World!";
?>
it still returns a semantic issue.
could somebody tell me what went wrong?
Well, for a start, JSONP requests can't be POST (only GET). But I tend to assume jQuery is ignoring the invalid type. JSONP is intrinsically a GET.
Your response to it is invalid. You've told jQuery you're expecting the server to provide a JSONP response. but your responses aren't JSONP.
A JSONP response would look something like this:
callback({
"property": "value",
"anotherProperty": 42
})
...where the name of the callback (callback in the above) is taken from the query string of the request. So for instance, if the request were http://sub.mydomain.com/test.php?callback=foo, the response would use foo for the name of the callback:
foo({
"property": "value",
"anotherProperty": 42
})
jQuery will add the callback= query string parameter to the request for you automatically, and generate the corresponding function for you, which in turn calls the ajax success handler with the data passed into it.
I think you may need to use the jquery postMessage plugin (or similar if there is one). Long time since I tried it but check if you load the script from the server you wish to call (think I tried that and failed in the past but hey - its worth a bash - report back if it does).