I've been struggling with this for a while, I checked everything I could think of and I'm sure this should work.. but it doesn't.
The idea is simple - you have a form input of type "text". When you type a number in the input and click "Click me!", it should POST the data in JSON format to a Route (handled via Closure), which would then check if the input is in JSON format and if yes, make a database request, then return the data.
Here is my view (table.blade.php)
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<title>json test</title>
</head>
<body>
<form action="#">
<input type="text" name="articleID" id="articleid" placeholder="Enter article id" value=""/>
</form>
Click me!
<script>
$(document).ready(function(){
var a_id = $("#articleid").val();
var article = { id: a_id };
$("#trigger").click(function(){
console.log(article);
$.ajax({
type: "POST",
url: "/json",
data: article,
dataType: 'json',
success: function(data){
alert(data.title);
}
});
return false;
});
});
</script>
</body>
</html>
And my routes.php
Route::get('json',function(){
return View::make('table');
});
Route::post('json',function(){
if (Input::isJson())
{
$request = Input::all();
$article = Article::find($request['id']);
if (!is_null($article))
{
return Response::json($article);
}
else return Response::json(['error' => "Object not found"],404);
}
else return "not json";
});
I've got two problems with this:
console.log(article); prints Object { id=""} so JS doesn't seem
to pick up the value of the input
No matter what, I always receive the response "not json", even if I replace data: article with something like data: {id: 123} in the ajax call
UPDATE
Thanks to milz, the first issue is now fixed, I refactored the $(document).ready() function like so:
$("#trigger").click(function(){
var a_id = $("#articleid").val();
var article = { id: a_id };
console.log(article);
$.ajax({
type: "POST",
url: "/json",
data: article,
dataType: 'json',
success: function(data){
alert(data.title);
}
});
return false;
});
Now the object is properly set, however the backend still returns only "not json"...
I have no idea what I'm doing wrong here, I will appreciate any help! Thanks in advance!
Input::isJson() actually checks for the Content-Type header of the request. The only thing dataType does is telling jQuery what response to expect.
Try setting contentType
$.ajax({
type: "POST",
url: "/json",
data: article,
dataType: 'json',
contentType: 'application/json',
success: function(data){
alert(data.title);
}
});
Related
I cannot get the data to show up in the page, though it appears in console.log.
Here is my query on api.php, the pages are in the same folder.
$Sub = $_GET['id'];
$stmt = $conn->prepare("SELECT id, name FROM variables WHERE id=:id");
$stmt->bindParam(':id', $Sub, PDO::PARAM_STR);
try {$stmt->execute();} catch(PDOException $e){ echo errorHandle($e);}
$rs2 = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($rs2);
It is working fine and produces
{"id":"1","name":"James"} on api.php
Here is the .js and body
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js">
</script>
</head>
<body>
<p><div id="shoot">shoot</div>
<div id="output"></div>
< script >
$(document).ready(function() {
$("#shoot").click(function()
{
$.ajax({
type: "GET",
url: 'api.php?id=1',
data: "?id=1",
dataType: 'json',
success: function(data)
{
var id = data[0];
var vname = data[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
console.log(data);
}
});
});
});
</script>
</body>
</html>
I'm getting back
id: undefined name: undefined
I've tried $ajax and any number of other changes but nothing is showing up in the page.
Help would be appreciated
A couple of things to note
You're statically setting the ID when you set the URL-parameter, yet passing it as an argument in data as well. You should reference the file in the url parameter, and pass all relevant values in the data parameter.
The data-parameter has an invalid ? in front.
Actual issue: You get an associative JSON object returned, not an array, so you'll need to access it as such, with data.id instead of data[0].
The AJAX-call should look something like this.
$.ajax({
type: "GET",
url: 'api.php',
data: {id:1},
dataType: 'json',
success: function(data) {
var id = data.id;
var vname = data.name;
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
console.log(data);
}
});
This assumes that you have set the PHP header to return it as JSON, with
header("Content-Type: application/json");
when you use echo json_encode(..).
The values passed in the data parameter can be formatted in several ways, I've chosen a {id:1} in this example, but "id=1" would be valid as well.
On your $.ajax call do not pass the data: "?id=1". By doing that, you are hard-coding the response. So remove that line. That should fix the response coming back to AJAX.
Also, on success: function(data), the data you get back needs to be accessed in this manner:
data.id and data.vname.
$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
dataType: 'json',
}).done(function(){
console.log('done');
});
Above is my AJAX post, below is my PHP:
var_dump($_POST['test']);
die();
The problem is, this fails to work (I get a NULL value) - why?
I know my call is getting to the PHP code as I can dump any old string:
var_dump('hello');
die();
Where am I going wrong?
Just remove this dataType: 'json'. Your $_POST['test'] is a string value, not a JSON string.
The POST value that you are testing with is not JSON, it's a string.
Remove the
dataType: 'json',
and it should work.
When you set dataType: "json" within the AJAX request it means the expected response should be parsed as json, (not the outgoing POST, as others have said).
Heres is a stripped down copy&paste example, for you to build upon. Hope it helps
<?php
//is it POST
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// set var
$test = isset($_POST['test']) ? $_POST['test'] : null;
//do some logic - skip that bit ;p
//was the request from AJAX, ok send back json
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//always a good idea
header('Content-Type: application/json');
//json encode, notice the ABC, then look at the jQuery below
die(json_encode(
array('ABC' => 'From Response: '.$test)
));
}
}
?>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function(){
var ajax = $.ajax({
url: "./",
type: "POST",
data: {test : 'test'},
dataType: "json"
});
ajax.done(function(data) {
$("#result").html(data.ABC); /* << See data is an object */
});
ajax.fail(function(xhr, status, error) {
$("#result").html(xhr.responseText);
});
});
</script>
<span id="result"></span>
I'm not totally sure if this is the issue, but .done is deprecated. Additionally, as others mentioned, you are asking for json from the server and not receiving json.
Your code should look like this
$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
success: function () {console.log('done');}
});
I would like to recommend you my code. and please do check the following points.
check the location of the url you are giving. If it is in parent directory then you can access it using ../ and the most important thing give the extension of the file. like 'gateway.php'
and write success and failure function. It gives a better insight of what's going on.
$.ajax({
type:'POST',
url:'gateway',
data:{test:'test'},
success: function(data){
if(data)
{
alert(data);
}
},
failure: function(){
alert(failed);
}
}) ;
comment if there are any errors
hope it helps :). If it does then don't forget to green it :P
Or change PHP code
header('Content-Type: application/json');
exit(json_encode(array('data' => 'Bla bla bla')));
edit - the info appears to be posting, but on form_data.php it doesn't seem to be retrieving the posted values
Here's the AJAX
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#submit_boxes").submit(function() { return false; });
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: function(data) {
$('#view_inputs').html(data); //view_inputs contains a PHP generated table with data that is processed from the post. Is this doable or does it have to be javascript?
});
return false;
});
};
</script>
</head>
Here is the form I'm trying to submit
<form action="#" id = "submit_boxes">
<input type= "submit" name="submit_value"/>
<input type="textbox" name="new_input">
</form>
Here is the form_data page that gets the info posted to
<?php
if($_POST['new_input']){
echo "submitted";
$value = $_POST['new_input'];
$add_to_box = new dynamic_box();
array_push($add_to_box->box_values,$value);
print_r($add_to_box->box_values);
}
?>
Your form is submitting because you have errors which prevents the code that stops the form from submiting from running. Specifically dataType: dataType and this.html(data) . Firstly dataType is undefined, if you don't know what to set the data type to then leave it out. Secondly this refers to the form element which has no html method, you probably meant $(this).html(data) although this is unlikely what you wanted, most likely its $(this).serialize() you want. So your code should look like
$('form#submit_boxes').submit(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: success
})
return false;
});
Additionally if you have to debug ajax in a form submit handler the first thing you do is prevent the form from submitting(returning false can only be done at the end) so you can see what errors occurred.
$('form#submit_boxes').submit(function(event) {
event.preventDefault();
...
});
You can use jQuery's .serialize() method to send form data
Some nice links below for you to understand that
jquery form.serialize and other parameters
http://www.tutorialspoint.com/jquery/ajax-serialize.htm
http://api.jquery.com/serialize/
One way to handle it...
Cancel the usual form submit:
$("#submit_boxes").submit(function() { return false; });
Then assign a click handler to your button:
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: this.html(data),
success: success,
dataType: dataType
})
return false;
});
I have an ajax function in jquery calling a php file to perform some operation on my database, but the result may vary. I want to output a different message whether it succeeded or not
i have this :
echo '<button id="remove_dir" onclick="removed('.$dir_id.')">remove directory</button>';
<script type="text/javascript">
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
if(rmd==0)
alert("deleted");
else
alert("not empty");
window.location.reload(true);
}
});
}
</script>
and this
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if(isset($_POST['dir_id'])){
$rmd=remove_dir($_POST['dir_id'],$bdd);
}
?>
my question is, how to return $rmd so in the $.ajax, i can alert the correct message ?
thank you for your answers
PHP
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if (isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
?>
JS
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did}
}).done(function(rmd) {
if (rmd===0) {
alert("deleted");
}else{
alert("not empty");
window.location.reload(true);
}
});
}
i advice to use json or :
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
You need your php file to send something back, then you need the ajax call on the original page to behave based on the response.
php:
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo "{'rmd':$rmd}";
}
which will output one of two things: {"rmd": 0} or {"rmd": 1}
We can simulate this return on jsBin
Then use jquery to get the value and do something based on the response in our callback:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://jsbin.com/iwokag/3",
success: function(data){
alert('rmd = ' + data.rmd)
}
});
View the code, then watch it run.
Only I didn't send any data here, my example page always returns the same response.
Just try echoing $rmd in your ajax file, and then watching the console (try console.log(rmd) in your ajax response block)
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
console.log(rmd);
}
});
You can then act accordingly based on the response
Try echo the $rmd out in the php code, as an return to the ajax.
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
//if $rmd = 1 alert('directory not empty');
//if $rmd = 0 alert('directory deleted');
echo $rmd;
}
Your "rmd" in success: function(rmd) should receive the callabck.
Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.