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
Related
If I have one ajax call with a long foreach loop where I update a text file, and at the same time I want to read that file and display changed content from the first call by another second call, how can I achieve that?
When the first runs, the second waits until the first one has finished.
I want to run the first and second at the same time. In the second call, every second I want to check the state inside the file created by the first call - something like a progress bar.
function startTimer(){
timer = window.setInterval(refreshProgress, 1000);
}
function refreshProgress(){
$.ajax({
type: "POST",
url: '/index.php?/system/run_progress_checker',
dataType:"json",
success: function(data)
{
console.log(data);
if (data.percent == 100) {
window.clearInterval(timer);
timer = window.setInterval(completed, 1000);
}
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
function completed() {
//$("#message").html("Completed");
window.clearInterval(timer);
}
$(".systemform").submit(function(e) { //run system
$.when(startTimer(),run_system()).then(function(){});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
function run_system(){
$("#leftcontainer").html("");
$("#leftcontainer").show();
$("#chartContainer").hide();
$(".loading").show();
var sysid = $(".sysid:checked").val();
var oddstype = $(".odds_pref").val();
var bettypeodds = $(".bet_type_odds").val();
var bookie = $(".bookie_pref").val();
if (typeof oddstype === "undefined") {
var oddstype = $(".odds_pref_run").val();
var bettypeodds = $(".bet_type_odds_run").val();
var bookie = $(".bookie_pref_run").val();
}
$.ajax({
type: "POST",
url: '/index.php?/system/system_options/left/'+'1X2/'+oddstype+'/'+bettypeodds+'/'+bookie,
data: {
system : sysid,
showpublicbet : showpublicbet }, // serializes the form's elements.
dataType:"json",
success: function(data)
{
console.log(data);
$("#systemlist").load('/index.php?/system/refresh_system/'+sysid,function(e){
systemradiotocheck();
});
$("#resultcontainer").load('/index.php?/system/showresults/'+sysid+'/false');
$("#resultcontainer").show();
$("#leftcontainer").html(data.historic_table);
$("#rightcontainer").html(data.upcoming_table);
var count = 0;
var arr = [];
$("#rightrows > table > tbody > tr").each(function(){
var row = $(this).data('row');
if(typeof row !== 'undefined'){
var rowarr = JSON.parse(JSON.stringify(row));
arr[count] = rowarr;
$(this).find('td').each(function(){
var cell = $(this).data('cell');
if(typeof cell !== 'undefined'){
var cellarr = JSON.parse(JSON.stringify(cell));
arr[count][6] = cellarr[0];
}
});
count ++;
}
});
if(oddstype == "EU" && bookie == "Bet365"){
$('.bet365').show();
$('.pinnacle').hide();
$('.ukodds').hide();
}
if(oddstype == "EU" && bookie == "Pinnacle"){
$('.pinnacle').show();
$('.bet365').hide();
$('.ukodds').hide();
}
if(oddstype == "UK"){
$('.bet365').hide();
$('.pinnacle').hide();
$('.ukodds').show();
}
if(bookie == "Pinnacle"){
$(".pref-uk").hide();
}
else{
$(".pref-uk").show();
}
$(".loading").hide();
runned = true;
var options = {
animationEnabled: true,
toolTip:{
content: "#{x} {b} {a} {c} {y}"
},
axisX:{
title: "Number of Games"
},
axisY:{
title: "Cumulative Profit"
},
data: [
{
name: [],
type: "splineArea", //change it to line, area, column, pie, etc
color: "rgba(54,158,173,.7)",
dataPoints: []
}
]
};
//console.log(data);
var profitstr = 0;
var parsed = $.parseJSON(JSON.stringify(data.export_array.sort(custom_sort)));
var counter = 0;
for (var i in parsed)
{
profitstr = profitstr + parsed[i]['Profit'];
//console.log(profitstr);
var profit = parseFloat(profitstr.toString().replace(',','.'));
//console.log(profit);
var event = parsed[i]['Event'].toString();
var hgoals = parsed[i]['Home Goals'].toString();
var agoals = parsed[i]['Away Goals'].toString();
var result = hgoals + ":" + agoals;
var date = parsed[i]['Date'].toString();
var bettype = parsed[i]['Bet Type'];
var beton = parsed[i]['Bet On'];
var handicap = parsed[i]['Handicap'];
//alert(profitstr);
//alert(profit);
//options.data[0].name.push({event});
counter++;
options.data[0].dataPoints.push({x: counter,y: profit,a:event,b:date,c:result});
}
$("#chartContainer").show();
$("#chartContainer").CanvasJSChart(options);
$(".hidden_data").val(JSON.stringify(data.export_array));
$(".exportsys").removeAttr("disabled");
$(".exportsys").removeAttr("title");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Backend part is not so important because it works.
Sounds like a great case for jQuery's $.when $.then. In the first part, the $.when, you'll have the first ajax call, and when that is finished... you can port the data from the first part to the $.then part. For example:
$.when(
//perform first ajax call and pass this data to the 'then'.
$.ajax(
{
type: "POST",
url: "<<insert url>>",
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
).then(function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data); // take data from above and use it to perform second ajax call.
var params = '{ "CustomerID": "' + obj[0].CustomerID + '" }';
$.ajax(
{
type: "POST",
url: "<<insert url>>",
data: params,
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
});
}
});
Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }
I want to pass username and password to a php script and check in the database. On the client side I use the following script to make a json object and post it to the php file.
var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();
var myjson = JSON.stringify(myobj);
$.ajax({
method: "POST",
url: "checkpass.php",
data: myjson
})
.done(function( msg ) {
alert( msg );
});
On the server side, when I see in firebug, the post is passed as
Parametersapplication/x-www-form-urlencodedDo not sort
{"usrname":"XXXXXXX...
JSON
usrname
"XX"
usrpass
"justdoit"
Source
{"usrname":"XXX","usrpass":"justdoit"}
however when i run the php script to check the query the it returns an error
$usrname = $_POST['usrname'];
$usrpass = $_POST['usrpass'];
$sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
$result = $conn->query($sql);
if($result >0){
$output = 'Success';
} else
{
$output = 'fail';
}
I have tried through all the posts but cannot get this to work.
Thanks in advance.
Regards,
Echo and die the statement in order for ajax to have a success event
Js File
var myobj = {};
myobj["usrname"] = 'myUsername';
myobj["usrpass"] = 'myPassword';
$.ajax({
type: "post",
url: "url",
dataType: "json",
data: {post_data: myobj},
contentType: "application/x-www-form-urlencoded",
success: function (responseData) {
console.log(responseData);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
PHP action File
/** if we print post we will get the following array * */
//print_r($_Post);
//die()
//Array
//(
// [post_data] => Array
// (
// [usrname] => myUsername
// [usrpass] => myPassword
// )
//
//)
if (isset($_Post['post_data'])) {
$myPost = $_Post['post_data'];
$usrname = $myPost['usrname'];
$usrpass = $myPost['usrpass'];
$sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
$result = $conn->query($sql);
$num_row = $result->num_rows;
if ($num_row > 0) {
$output = 'Success';
} else {
$output = 'fail';
}
echo json_encode($output);
die();
}
Try This :
in js file :
$(document).on("ready", function(){
// Create an object using an object literal.
var ourObj = {};
// Create a string member called "data" and give it a string.
// Also create an array of simple object literals for our object.
ourObj.data = "Some Data Points";
ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];
var savedata = JSON.stringify(ourObj)
$.ajax({
type:"POST",
url:"Users.php",
data: {"points" : JSON.stringify(ourObj)},
success: function(data) {
// Do something with data that came back.
alert(data);
}
})
});
In PHP File :
if (isset($_POST["points"])) {
$points = json_decode($_POST["points"]);
echo "Data is: " . $points->data . "<br>";
echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
}
Try this:
var myobj = '{
usrname:'+$( "#customer option:selected" ).text()+',
usrpass:'+$("#psw").val()+'
}';
or
var myobj = {};
myobj.usrname= $( "#customer option:selected" ).text();
myobj.usrpass= $("#psw").val();
Use Json2 library as follows,
var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();
var myjson = JSON2.stringify(myobj);
$.ajax({
method: "POST",
url: "checkpass.php",
data: myjson
})
.done(function( msg ) {
alert( msg );
});
Well actually you php code is invalid because you pass json day not name value pair so you cant get it from $_POST['username']. You need to get the whole post data and decode it like this.
$data = json_decode(file_get_contents('php://input'), true);
Now $data is dictionary array of username and password. Also sanitize your data before passing to query to avoid sql injection.
I am trying to make an ajax call on click on anchor tag dynmically generated from $.each loop for a JSON response.
For Information : #records is my table and .update is the class of anchor tag in that table.
Please be informed that the table is generated dynamically.
Now the problem is that my ajax call is returning nothing even i have checked it error: but no response received. I have tried alerting my var data just before the ajax call and it worked.So the problem starts from the ajax call. Moreover, my server side code is running fine.
// Update existing customers
$("#records").on('click', ".update", function() {
var data = '?'+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data: data,
success: function(response) {
console.log(response);
}
});
});
Thanks in advance.
For reference below is the code that generates the table.
// Function to make datagrid
function getRecords() {
$.getJSON("viewcustomers.php", function(data) {
var items = [];
var xTd = '';
var xTr = '';
$.each(data, function(key, val) {
var c = 0;
var id = 0;
$.each(val, function(key1, val1) {
if (c == 0)
{
id = val1;
}
c++;
xTd += '<td>' + val1 + '</td>';
});
xTd += '<td>Edit</td>';
xTd += '<td>Delete</td>';
xTr = '<tr>' + xTd + '</tr>';
items.push(xTr);
xTd = '';
xTr = '';
});
$("#records").append(items);
});
}
Updated the server side code:
page url : localhost/hotel/viewcustomers.php
/**
* Fetch single row for the purpose of update / delete.
*/
if(isset($_GET['update'])){
$customer = new Customers;
$Id = $_GET['update'];
$customer_single = $customer->View_Single_Customer($Id);
echo json_encode($customer_single);
unset($customer);
}
This line is not used the right way var data = '?'+ $(this).attr('id');
Change it like this: var my_id = $(this).attr('id');
Then update the line data: data with data : {id:my_id}
Complete code :
$("#records").on('click', ".update", function() {
var my_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data : {id : my_id},
success: function(response) {
console.log(response);
}
});
});
Or do it like this:
$("#records").on('click', ".update", function() {
var param = '?id='+ $(this).attr('id'); /*notice that I have added "id=" */
$.ajax({
type: "GET",
url: "viewcustomers.php" + param,
/* remove the data attribute */
success: function(response) {
console.log(response);
}
});
});
Modify it as
$("#records").on('click', ".update", function() {
var request = '?id='+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php" + request,
success: function(response) {
console.log(response);
}
});
});
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);
}