jquery, json and success function - php

I have written this code, but I am not able to make it works as it should..:
<script>
$(document).ready(function(){
$(document).on('click','.a_mod', function(e){
e.preventDefault();
var id = $(this).attr('rel');
var var_id = '<?php echo $id ?>';
var data_3 = 'id=' + id + '&var_id=' + var_id;
$.ajax({
type: "POST",
data: data_3,
cache: false,
dataType: 'json',
url: "php/show_tariffa.php",
success: function(html){
var obj = jQuery.parseJSON(html);
$.each(obj,function(index, element){
var id = element.id;
var prestazione = element.prestazione;
var prezzo = element.prezzo;
var check = element.prezzo_mult;
$('#id_tariffa').val(id);
$('#nome_2').val(prestazione);
$('#prezzo_2').val(prezzo);
}); // fine .each
$('#box_2').slideUp();
$('#box_3').slideDown().css({"border-color": "#F31041"},'fast');
} // fine success
}); // fine ajax
});
});
</script>
Using Firefox and firebug I can see that the event starts and that the php script is executed but, I don't know why, the "success:" part of the ajax doesn't start at all..
Here there is the php script:
<?php
include("connect.php");
$id = $_POST['id']; // id
$var_id = $_POST['var_id']; // id_dentista
$html = array();
$query = mysql_query("SELECT
tariffe.id,
tariffe.prestazione,
tariffe.prezzo,
tariffe.prezzo_mult
FROM tariffe
WHERE tariffe.id_dentista = '$var_id' AND tariffe.id = '$id'")
or die(mysql_error());
while( $row = mysql_fetch_array($query)){
$html[] = $row;
}
echo json_encode($html);
?>
What's wrong? what am I missing?
Thanks Davide,

Update
After hours of troubleshooting in chatroom, I finally just installed this code on my server and set up the database. It works fine, the only issue was a BOM signature at the beginning of every file.
You need to set the encoding of your files to UTF8, not UTF8 BOM and you should be good. My guess is there is a BOM signature at the beginning of the returned data which is making $.parseJSON() mad.
Let me know if that fixes it, if not, it's back to the old drawing board.
If you are sure your query is successful, then add an error callback to your script (or use the delegate script below and its already added).
This should give you the reason why your script is erroring out.
error: function(xhr, status, error) {
console.log(status);
console.log(error);
console.dir(xhr);
}
Also, I'm not sure about FF, but in Chrome, you can go to the Network tab and click on your ajax script. You can then view the data being sent, and the response. You are probably having an issue with datatype/contenttype.
Sidenote:
You should be delegating your AJAX calls to properly handle event bubbling.
You should also be validating your input and not accessing superglobal $_POST directly.
You should also not use PHP inside of JS. Instead create an element in your HTML and replace this ...
var var_id = '<?php echo $id ?>';
with this ...
HTML
<input id="hiddenId" type="hidden" value="<?php echo $id; ?>">
jQuery
var var_id = $("#hiddenId").val();
Delegate Ajax
(function($){
$(function(){
//Usage Example
var inputString = $("#myInput").val();
var inputNumber = $("#myInteger").val();
var data = {inputString: inputString, inputNumber : inputNumber};
$('parent').on('click', 'button', delegateAjax('js/myAjax.php', data, 'POST');
});
function delegateAjax(url, data, responseType, dataType, callback) {
function successHandler() {
console.log("Ajax Success");
};
function failureHandler(xhr, status, error) {
console.log("Ajax Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler404(xhr, status, error) {
console.log("404 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler500(xhr, status, error) {
console.log("500 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
url = typeof url !== 'undefined' ? url : 'js/ajaxDefault.php';
data = typeof data !== 'undefined' ? data : new Object();
responseType = typeof responseType !== 'undefined' ? responseType : 'GET';
dataType = typeof dataType !== 'undefined' ? dataType : 'json';
callback = typeof callback !== 'undefined' ? callback : 'callback';
var jqxhr = $.ajax({url: url, type: responseType, cache: true, data: data, dataType: dataType, jsonp: callback,
statusCode: { 404: handler404, 500: handler500 }});
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
};
})(jQuery);
Correctly Validate/Sanitize Input
$args = array(
'inputString' => array(
'filter' => FILTER_SANITIZE_STRING,
'flags' => FILTER_REQUIRE_SCALAR
),
'inputNumber' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_REQUIRE_SCALAR
),
'inputNumber2' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_REQUIRE_SCALAR
)
);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
$response = array('status' => 'success');
echo json_encode($response); exit;
}

Related

How to pass JSON object from Controller to view

There are many threads on the subject, but I cannot find any that use PHP. I want to pass the json object to the view, where I will later update an element with the returned json object.
Here is my code:
View:
<input type="submit" class="button" name="insert" value="load"/>
<script>
jQuery(document).ready(function() {
var $ = jQuery;
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = baseUrl+"?action=load";
data = {'action': clickBtnValue};
$.post(ajaxurl, {}, function (result) {
alert(result);
});
});
});
</script>
And Controller is:
<?php
set_include_path(get_include_path().':../');
require_once('_inc/common.php');
$action = req('action');
if ($action == 'load') {
$result = parse_ini_file('test.ini');
$json = json_encode($result);
}
[UPDATE]
After the code to the answers provided, I now get an Json.parse error. So I edited my code again but the error still persists, I checked online to see if my Json is a valid json and no error on the validator.
$result = parse_ini_file($config_file);
$json = json_encode(array($result),JSON_HEX_QUOT);
var_dump($json);
header('Content-Type: application/json');
View
var request = $.ajax({
url: ajaxurl,
method: "POST",
data: {},
dataType: "json"
});
request.done(function( msg ) {console.log("d");});
request.fail(function( jqXHR, textStatus ) {console.log( "Request failed: " + textStatus );});
});
Like said above, you aren't outputting the JSON, and also you are not setting the content type. But I noticed something else, you did not assign the return type of the post request (JSON).
$.post(url, {}, function (data) {
alert(data);
}, 'JSON');
Be also sure that you encode an array and not a false value, parse_ini_file returns false when it fails.
Try this
<script>
jQuery(document).ready(function() {
var $ = jQuery;
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = baseUrl+"?action=load";
data = {'action': clickBtnValue};
$.post(ajaxurl, {}, function (result) {
var json =JSON.parse(result);
console.log(json); //see in browser console
});
});
});
</script>
And Controller is:
<?php
set_include_path(get_include_path().':../');
require_once('_inc/common.php');
$action = req('action');
if ($action == 'load') {
$result = parse_ini_file('test.ini');
echo json_encode($result);
}

PHP doesn't get JQuery serialize() POST parameters

I want to send a form with JQuery $.ajax, but I have a problem. It's seems that PHP cannot get serialized $_POST. It's weird because the variable elementiPost is not empty, indeed if I do console.log(parametriPost) the console show me the right content.
The weirdest thing is that PHP get parameters that I append manually to parametriPost ($_POST['data_r']) but not those of $(this).serialize()!
If I put manually a number in $ore it works fine, so the problem is not the query.
Thank you.
Here's the code:
JQuery
$('form').submit(function(e) {
e.preventDefault();
var formId = $(this).attr('id');
var data = area_get_row_date(formId);
var parametriPost = $(this).serialize() + '&data_r=' + data;
$.ajax({
url: 'insert_db.php',
method: 'POST',
async: false,
data: parametriPost,
success: function() {
// Success code
},
error: function(xhr, status, error) {
alert("Errore!");
}
});
});
PHP (insert_db.php)
$data = str_replace('_', '.', $_POST['data_r']);
$ore = $_POST['orelavorateore_2_07_2015'];
$sql = "INSERT INTO ore_lav
VALUES (NULL, 134, 4,STR_TO_DATE('" . $data . "', '%d.%m.%Y'), " . $ore . ", 1, 1)";
$results = api_store_result(api_mysql_query($sql));
This is what parametriPost contains:
lavorati_prenotati=L&periodointegrazione_3_07_2015=on&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=a&extra_field1_orelavoratechf_3_07_2015=&extra_field1_orelavorateore_3_07_2015=&extra_field2_orelavoratechf_3_07_2015=&extra_field2_orelavorateore_3_07_2015=&orenonlavoratechf_3_07_2015=&orenonlavorateore_3_07_2015=&orenonlavoratetipologia_3_07_2015=L&extra_field1_orenonlavoratechf_3_07_2015=&extra_field1_orenonlavorateore_3_07_2015=&extra_field1_orenonlavoratetipologia_3_07_2015=L&extra_field2_orenonlavoratechf_3_07_2015=&extra_field2_orenonlavorateore_3_07_2015=&extra_field2_orenonlavoratetipologia_3_07_2015=L&orenonpagateore_3_07_2015=&orenonpagatetipologia_3_07_2015=L&extra_field1_orenonpagateore_3_07_2015=&extra_field1_orenonpagatetipologia_3_07_2015=L&extra_field2_orenonpagateore_3_07_2015=&extra_field2_orenonpagatetipologia_3_07_2015=L&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=&data_r=3_07_2015
You can use this snippet to convert your form data into JSON format :
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("form").submit(function( event ) {
event.preventDefault();
//convert form data to JSON
var params = $(this).serializeObject();
//add a 'data_r' field with some data to our JSON
params.data_r = 'sample data';
$.ajax({
url: 'app.php',
type: 'POST',
data: JSON.stringify(params),
})
.done(function(data) {
console.log(data);
});
});
and on the PHP side :
<?php
$data = json_decode(file_get_contents('php://input'), false);
print_r($data->data_r);
?>
Now $data is an object and you can access to a specific field :
$data->data_r

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

jquery passing variables to php file

acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}

jquery: calling invisible php-mailer? ajax?

hey guys,
i know how to create a simple php file that mails some information to me.
However what I don't know is how to call that php-file with jquery and hand over a variable.
Handing over a variable might work with isset()...
How can I call this PHP mailer from jquery and do that HIDDEN from the user. So there should not pop up a new window and shouldn't be a page refresh or anything like that.
$('a.report').click(function(e) {
e.preventDefault();
var id = $(this).attr('href');
//call mail script and pass along the "id" variable
//change text (maybe in a callback function IF THE MAILING WAS A SUCCESS.
$(this).parent().text('Thank you for reporting.');
})
So I have this a.report Link which should trigger the email script. In my email script I need to access the "id" variable set in jquery. And it would even be nice to have a callback function if the php script did it's thing so I could output "Thank you for reporting".
How to do that?
Thank you guys.
I would use $.post():
<script type='text/javascript'>
$(function(){
function onReportPosted(data) {
// data.status - either 'error' or 'success', from mailer.php
// data.message - some text, from mailer.php
$('.result').text(data.message);
}
$('a.report').click(function(e) {
$('.result').text('sending report...');
var data = {
text: $('textarea[name=text]').val()
};
$.post(
'mailer.php',
data,
onReportPosted,
'json'
);
return false;
});
});
</script>
And in mailer.php:
<?php
if ( isset($_POST['text']) ) {
// mail()...
$result = array(
'status' => 'success',
'message' => 'thank you for reporting',
);
} else {
$result = array(
'status' => 'error',
'message' => 'some error occurred',
);
}
header('Content-Type: application/json');
echo json_encode($result);
exit;
Update: here's a way how to "tie" callback to a specific element:
<script type='text/javascript'>
$(function(){
$('a.report').click(function(){
var htmlElement = $(this).parent();
var data = {
// ...
};
$.post(
document.location.toString(),
data,
function(data) {
htmlElement.html(data.message);
},
'json'
);
return false;
});
});
</script>
see $.post to know how to call and pass the id to the php script (http://api.jquery.com/jQuery.post/)
It will be somthing like
$.ajax({
context: $(this),
type: 'POST',
url: 'script.php',
data: {id: id },
success: function() {
$(this).parent().text('Thank you for reporting.');
}
});
And in the php script, $id = $_POST['id'];
try:
$.post('script.php', {variableName: value, variable2Name: value2});
in php: $value = $_REQUEST['variableName']; $value2 = $_REQUEST['variable2Name'];
jQuery provides some great AJAX methods for us under the AJAX API catagory. I think $.post would be what you're looking for. This is how I send JSON data to a simple PHP script in my Grooveshark userscript:
$.ajax({
type: 'POST',
url: 'http://path/to/script.php',
data: JSON.stringify({key: 'value', array: ['one', 'two', 'three']),
dataType: 'json',
success: function(data){
console.log('Mailer returned with object ', JSON.parse(data) );
}
});
And here's how I parse it in PHP:
$incoming = json_decode(file_get_contents("php://input"), true);
This returns nested associative arrays for the JSON content, very easy to parse! I highly recommend using JSON as your data interchange format. Much better than XML.

Categories