I've a problem with my page, first code (let said is hompe.php)
<html>
<div id="trackingkp"></div>
</html>
then on my ajax I've code like these
$( document ).ready(function() {
var dataString = '';
$.ajax
({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'html',
success: function(html)
{
$('#trackingkp').html($(html).find('#trackingkp').html());
//$("#trackingkp").html($(data).find('#trackingkp').html());
}
});
});
and on my ajax controller, I do like these (I'm using framework laravel)
public function tracking($url)
{
//var_dump("AAA");
$this->view('ajax/tracking/'.$url,[]);
}
on my ajax/tracking view like this
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
When I try that is showing
Syntax error, unrecognized expression: "<input type='text'>
I have solved the problem, I'm using another option without using jQuery, so on same time, on controller when load view home.php, I try put load view too like these
public function index(){
is_header();
$this->view('home',[]);
$this->view('ajax/tracking/kp',[]); ---> I add these
is_footer();
}
and on ajax/tracking/kp (view) I put these code
<input type='text'></input>
and is working.
The problem would be in this one:
success: function(html) {
// Problem : $(html).find('#trackingkp').html();
$('#trackingkp').html($(html).find('#trackingkp').html());
}
From which this html response is expected to return a json value
in your given [controller]
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
Thus this is equivalent to:
$("<input type='text'></input>").find('#trackingkp').html();
In this case, I don't think you might need to call another *.html(). You can simplify / solve this by calling it once:
$.ajax({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'json', // Kindly replace [html] to [json] since you are returning a [json] value
success: function(html) {
$('#trackingkp').html(html);
}
});
Hope this helps for your case
Related
I use typeahead.js to put tags for my multiple input. The tags input function correctly except the fact that its autocomplete suggestion does not come out. Is there any way to correct this problem?
I've tried most solution related to my problem that are already on this site but currently still not be able to display the autocomplete suggestion. I am always stuck at the successful ajax response and that's it.
my jquery:
<script>
$("#s_to").tagsinput({
tagClass: 'uk-badge',
typeaheadjs: {
source: function(query) {
console.log(query);
url = "<?php echo base_url(); ?>index.php/<?php echo $loc_pts; ?>/ajax_email";
var s_to = extractLast(query);
ajax_status = "fail";
$.ajax({
url: url,
method: "POST",
data: {
s_to: s_to
},
async: false,
dataType: "json",
success: function(json){
return json.s_to;
}
});
}
}
});
</script>
my input :
<input required type="text" name="s_to" id="s_to" class="controls uk-autocomplete-results" value="<?php echo $s_client_email; ?>" autocomplete="on" data-provide="typeaheadjs" />
my related script:
<script src="<?php echo base_url(); ?>assets/bower_components/typeahead.js/typeahead.jquery.min.js"></script>
console log output screen shot
Supposedly the input able to receive multiple input and each input seleccted will be displayed inside a tag. What make it harder is that no error message displayed. Thus, I know that my ajax is done correctly.
The main issue is that you do not return the array in correct scope. Your return json.s_to; is inside the ajax success function, but you need to return the value in parent scope. So, the code should be like this:
$("#s_to").tagsinput({
tagClass: 'uk-badge',
typeaheadjs: {
source: function(query) {
console.log(query);
url = "<?php echo base_url(); ?>index.php/<?php echo $loc_pts; ?>/ajax_email";
var s_to = extractLast(query);
ajax_status = "fail";
var toReturn = [];
$.ajax({
url: url,
method: "POST",
data: {
s_to: s_to
},
async: false,
dataType: "json",
success: function(json) {
toReturn = json.s_to;
}
});
/* This is the correct scope to return the array */
return toReturn;
}
}
});
The AJAX request goes through correctly, I checked with chrome's developer tools, there is a request on quiz.php page, but when I check for $_POST['risultato'] it looks doesn't exist. I noticed though that in Chrome's dev tools there's 2 quiz.php elements (one xhr the other document)
I tried changing the code in several ways, but it seems like it doesn't work
<?php
if(isset($_POST['risultato'])){
print($_POST['risultato']);
}
?>
<script>
function inviaRisultati(ris){
$.ajax({
url: "quiz.php",
type: "POST",
cache: false,
data: {risultato: ris},
success: function(){
alert("INVIATI");
}
})
}
The program is expected to return the result on quiz.php page (the same page where ajax request is fired), and it's supposed to print it somewhere
EDIT: I fixed it
<?php
file_get_contents('php://input');
if(isset($_POST['risultato'])){
print($_POST['risultato']);
}
?>
function inviaRisultati(param) {
return $.ajax({
url:"quiz.php",
method:"POST",
data:{action: "SLC", risultato :param},
dataType:"text"
});
}
inviaRisultati(1).done(function(response){``
document.open();
document.write(response);
});
In Ajax, the data attribute is in JSON format.
your data attribute will be like this
data: {risultato: ris}
Hi you can do it this way:
your php script:
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case 'SLC':
if (isset($_POST["risultato"])) {
$response = $_POST["risultato"];
echo $response;
}
}
break;
}
Where action is a command you want to do SLC, UPD, DEL etc and risultato is a parameter
then in your ajax:
var param = $('#yourinputid').val();
function getInfo(param) {
return $.ajax({
url:"quiz.php",
method:"POST",
data:{action: "SLC", risultato :param},
dataType:"text"
});
}
call it like this:
getInfo(param).done(function(response){
alert(response);
//do something with your response here
})
Hope it helps
HTML CODE
<script>
jQuery(document).ready(function(){
ris = 'abcd';
jQuery.ajax({
url: "quiz.php",
type: "POST",
cache: false,
data: {risultato: ris},
success: function(){
}
})
});
</script>
PHP CODE
<?php
file_get_contents('php://input');
print($_POST['risultato']);
Console Output
After hours of trying to get this to work, i want to ask you :)
So i have a php Page that can display files from a server. Now I can edit
the files with a editor plugin.
Textarea is the tag where the editor gets rendered.
To save the changed text from the editor, I have a button that gets the innerHTML from the surrounding pre tag of the text with javascript.
I now want to pass that variable via ajax to a php variable on the site get.php,
so I can save it locally and send it to the server.
The problem is, that there is no reaction at all, if i click the "Save" button. I tested a lot of answers from similar ajax functions here, but none of them gave me a single reaction :/
php main
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
...
echo "<textarea><pre id='textbox'> ";
echo $ssh->exec($display);
echo "</textarea></pre>";
echo '<input type="button" value="Save File" id="butt">';
echo "<script>
var show = document.getElementById('textbox').innerHTML;
$(document).ready(function() {
$('#butt').click(function() {
$.ajax({
type: 'POST',
url: 'get.php',
data: {'variable': show},
success: function(data){
alert(data);
}
});
});
});
</script>";
...
get.php
if (isset($_POST["variable"])){
$show =$_POST["variable"];
echo $show;
}
Edit:
This is the actual working state:
echo "<textarea id='textbox'><pre> ";
echo $ssh->exec($display);
echo "</pre></textarea>";
echo '<input type="button" value="Save File" id="butt">';
echo "<script>
$(document).ready(function() {
$('#butt').click(function() {
var show = document.getElementById('textbox').value;
$.ajax({
type: 'POST',
url: 'get.php',
data: {'variable': show},
success: function(data){
alert(data);
},
});
});
});
</script>";
You have an error in the data: {'variable': show)} part. It should be: data: {variable: show}. Also you should use Firebug or Firefox developer tools for these kind of problems. A lot easier to see whats wrong.
I would suggest small changes to see if everything is running as it should.
I can see that pre tag is behind textarea closing tag - try to change it
Try putting var show = document.getElementById('textbox').innerHTML; inside of the ,,butt" function
Then I can see your problem here data: {'variable': 'show')}, - you are sending 'show' as a string - remove quotes to send it as a variable which will appear as a POST value in PHP site.
with this should work:
$.ajax({
type: 'POST',
url: 'get.php',
data: {variable: show)},
success: function (data){
alert(data);
I have this button
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
And this button related to this
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
I'm using this script to send value of button to my php controller
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable,
success: function (data){
}
});
}
When I use alert, the result of javascriptVariable is correct and I want it in my controller so I'm trying in my controller to do this:
if(isset($_POST['activation']))
{
$name = $this->input->post('myname');
var_dump($name);
}
But I get null value, what is the wrong?
When you pass data from the browser via AJAX only the data you pass in the data: parameter is sent to the PHP script.
So if you want to test for activation in the PHP script you must actually send that parameter
Also see the amendment to the data: parameter creation below. Its easier to read and a lot easier to code correctly when passing more than one parameter as you dont have to remember &'s and + concatenation.
function handleButton(obj) {
obj.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {activation: 1, myname: obj.id}, // add parameter
success: function (data){
alert(data);
}
});
}
Now the PHP will see 2 parameters in the $_POST array activation and myname
if(isset($_POST['activation']))
{
$name = $_POST['myname'];
var_dumb($name);
}
Or if you are using a framework which I assume you are
if(isset($this->input->post('activation')) {
$name = $this->input->post('myname');
var_dumb($name);
}
EDIT:
Spotted another issue your button has an attribute type="submit" this will cause the javascript to run AS WELL AS the form being submitted in the normal way.
Remove the type="submit" attribute and to be doubly sure that the form will not be submitted as well as the AJAX add a call to preventDefault(); as well before the AJAX call
Since the php script is conditioned by a second POST variable [if(isset($_POST['activation']))], you should post that as well.
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable+'&activation=1',// <-- RIGHT HERE
success: function (data){
alert(data);
}
});
}
SIDE NOTE: you could also echo instead of dump the variable:
if(isset($_POST['activation']))
{
echo $this->input->post('myname');
}
Try this in your ajax function :
function handleButton(obj) {
var javascriptVariable = obj.id;
//alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {myname: javascriptVariable},
success: function (data) {}
});
}
And in your PHP script, you can do $_POST['myname'] to get it (maybe $this->input->post('myname') can work, you can test it)
Look two id
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
AND
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
For both html elements id is same.It can not be used with in the same page.This may cause a problem for you...
I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});