I try searching about this but I just can't find any that can solve my problem. I want to produce a url like to this to send request to my webservice:
http://localhost/jQueryStudy/RamagalHTML/processjson3.php?
path=update%2FtallyHdr&json=
{"SessionID":"hHuCG3Jt1um5gV7kE320Bw7EjG97I4qZ","operation":"add",
"transaction_date":"2011-7-29","supplier_id":"10000000108","wood_specie_id":"1",
"lines":[{"plank_number":"7","thickness":"5","width":"8","length_t":"8","quantity":"1","board_foot":"26.67","wood_classification_id":"1","price":"15"}],"scaled_by":"WER","tallied_by":"WE","checked_by":"WE","total_bdft":"580.00","final":"N"}
Here's my current javascript code i have right now:
var dataJSON = {
"SessionID": $.cookie("SessionID"),
"operation": "add",
"transaction_date":$('#tallyDate').val(),
"supplier_id":$('#supplierInput').attr("name"),
"wood_specie_id":$('#woodSpecie').attr("name"),
"lines":plank_data,
"scaled_by":$('#tallyScaled').val().toUpperCase(),
"tallied_by":$('#tallyTallied').val().toUpperCase(),
"checked_by":$('#tallyChecked').val().toUpperCase(),
"total_bdft":$('#tallyTotal').val(),
"final":"N"
};
alert('this is the datajson from add : ' + JSON.stringify(dataJSON));
$.ajax({
type: 'POST',
data: dataJSON,
url: 'processjson2.php?path=update/tallyHdr',
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblTallyHdr').trigger('reloadGrid');
}
}
});
My .php code is this:
<?php
$data_url = http_build_query (array('json' => $_REQUEST["json"]));
$data_len = strlen ($data_url);
echo file_get_contents("http://localhost:8001/" . $_REQUEST["path"], false, stream_context_create(
array (
'http' => array(
'method'=>'POST',
'header' => "Connection: close\r\nContent-Length: $data_len\r\n",
'content'=>$data_url
)
)
));
Evrytime I run my program, the url is only this http://localhost/jQueryStudy/RamagalHTML/processjson2.php?path=update/tallyHdr, the data was not posted which makes my request not executed. Please help me on this. I don't know how to fix my php.
If you're wanting all your data to be sent as part of the URL then you should use GET, not POST.
It's therefore possible to do away with the data property and append everything to the request URL:
$.ajax({
type: 'GET',
url: 'processjson2.php?path=update/tallyHdr&json='+dataJSON,
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblTallyHdr').trigger('reloadGrid');
}
}
});
If you must use POST, then you just need to provide a variable name to go with your json:
$.ajax({
type: 'POST',
data: "json="+dataJSON,
url: 'processjson2.php?path=update/tallyHdr',
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblTallyHdr').trigger('reloadGrid');
}
}
});
For more info, see the examples towards the end of the page: http://api.jquery.com/jQuery.ajax/
Related
Something strange is happening since I moved my webserver to a new machine.
Now whenever an ajax call completes and nothing is returned, the data variable contains two spaces.
I have:
$.ajax({
url: 'http://192.168.0.6/access/login',
data: 'user='+user+'&pass='+pass+'&rem='+remember,
type: 'POST',
success: function(data)
{
alert(data.length)
if(data)
{
$('#errorMessage').html(data) ;
$('#loginWarn').fadeIn() ;
} else {
window.location = 'login'
}
}
})
On success my PHP script returns 0, indicating success and nothing is returned so the user is redirected to 'login'.
However, since the move 'data' is now a variable of length two (tested with data.length).
Does anyone know what is wrong?
Try this
$.ajax({
url: 'http://192.168.0.6/access/login',
data: '{ "user":"' + user+ '",pass":"' + pass+ '",rem":"' + remember+ '"}',
type: 'POST',
success: function(data)
{
alert(data.length)
if(data=="true")
{
$('#errorMessage').html(data) ;
$('#loginWarn').fadeIn() ;
} else {
window.location = 'login'
}
}
})
I have a js script that does an ajax request and posts the data to a php script, this script with then echo something back depending if it works or not.
here is the JS
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
}, 6000);
});
here is the php:
if(isset($_POST["json"]))
{
$json = json_decode($_POST["json"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
So basically, i thought the response in the `success: function(response)' method would be populated with either "IT WORKED!!!" or "NOT POSTED" depending on the if statement in the php. Now everything seem to work because the js script manages to go into the success statement but prints this to the console:
Response was null
I need to be able to get the return from the server in order to update the screen.
Any ideas what I'm doing wrong?
Try:
if(isset($_POST["markets"]))
{
$json = json_decode($_POST["markets"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
use this in your php file
if(isset($_POST["markets"]))
{
}
instead of
if(isset($_POST["json"]))
{
.
.
.
.
}
Obiously the if(isset($_POST["json"])) statement is not invoked, so neither of both echos is executed.
The fact that the function specified in .ajax success is invoked, only tells you that the http connection to the url was successful, it does not indicate successful processing of the data.
You are using "success:" wrong.
Try this instead.
$.post("signals.php", { markets: post_data }).done(function(data) {
/* This will return either "IT WORKED!!!!" or "NOT POSTED" */
alert("The response is: " + data);
});
Also have a look at the jQuery documentation.
http://api.jquery.com/jQuery.post/
Look, You send data in market variable not in json. Please change on single.php code by this.
$json_data = array();
if(isset($_POST["markets"]))
{
// $json = json_decode($_POST["markets"]);
$json = ($_POST["markets"]);
if(!empty($json))
echo "IT WORKED!!!!";
else
echo "NOT POSTED";
}
And change on your ajax function
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'post',
// contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
},6000);
});
You have to you change you $.ajax call with
//below post_data array require quotes for keys like 'market_number' and update with your required data
post_data = [ {'market_number':1, 'name':'name1'},
{'market_number':2, 'name':'name2'}];
//console.log(post_data);
$.ajax({
url: "yourfile.php",
type:'post',
async: true,
data:{'markets':post_data},
dataType:'json',
success: function(data){
console.log(data);
},
});
and you php file will be
<?php
if(isset($_POST['markets']))
{
echo "It worked!!!";
}
else
{
echo "It doesn't worked!!!";
}
//if you want to work with json then below will help you
//$data = json_encode($_POST['markets']);
//print_r($data);
?>
in your php file check the $_POST:
echo(json_encode($_POST));
which will tell if your data has been posted or not and the data structure in $_POST.
I have used the following code to covert the posted data to associative array:
$post_data = json_decode(json_encode($_POST), true);
this below code could'nt send data to other server. i want to send "aaa-bbb-ccc" with $.ajax. but after post back userCode thats post empty data from $_POST. sorry for my english
jquery code :
<script type="text/javascript">
$(function(){
$.ajax({
url: "http://www.site.com/index.php",
type: "POST",
dataType: "jsonp",
data: {userCode: "aaa-bbb-ccc"}
}).done(function(data){
alert(data.message);
});
});
</script>
server index.php :
<?php
include_once ('./AFactory.class.php');
$database= new AFactory;
$db=new AFactory();
$link=$db->getDBO();
if ( $_POST['userCode'] == '')
{
$data['success']=false;
$data['message']='ERROR ...';
}
else {
$query=array('id'=>NULL,'userCode'=>$_POST['userCode']);
$sql=$db->insertQuery('`alachiq_takhmis`.`users`',$query);
if ( mysql_query($sql) )
{
$data['success']=true;
$data['message']=$_POST['userCode'];
}
else
{
$data['success']=false;
$data['message']=$_POST['userCode'];
}
}
echo $_GET['callback'] . '('. json_encode($data) . ')';
?>
post back:
({"success":false,"message":'ERROR ...'})
whats my code problem?
JSONP works by injecting a <script> element with a src attribute into a document.
That can only ever make a GET request.
$.ajax({
url: "http://www.site.com/index.php",
type: "GET",
dataType: "jsonp",
data: {userCode: "aaa-bbb-ccc"}
});
I am sending data via jQuery's .ajax method to my PHP file. Both files are on the same domain. The file making the post looks like this..
$('#pdf').click(function() {
var proj_name = $('#proj_name').text();
var date = $('#date').text();
var req_comp_date = $('#req_comp_date').text();
var status = $('#status').text();
var secondUserID = $('#secondUserID').text();
var postData = {
"proj_name" : proj_name,
"date" : date,
"req_comp_date" : req_comp_date,
"status" : status,
"secondUserID" : secondUserID,
};
console.log(postData);
$.ajax({
type: "POST",
url: "test.php",
data: postData,
success: function(){
alert(proj_name + ' ' + status);
window.open("test.php");
}
});
});
And the PHP file getting the post data is...
//request parameters
$proj_name = $_POST['proj_name'];
$date = $_POST['date'];
$req_comp_date = $_POST['req_comp_date'];
$status = $_POST['status'];
$secondUserId = $_POST['secondUserId'];
echo 'postData: ' . var_dump($_POST);
if ($_POST)){
echo $proj_name;
echo $date;
echo $req_comp_date;
echo $status;
echo $secondUserId;
} else {
echo 'problem';
}
In my firebug console, I can see that the parameters posted with .ajax, but I cannot get the post via PHP. Can anyone help me out please? Thank you.
Add the error callback to your to your $.ajax call to debug if the request is failing.
$.ajax({
type: "POST",
url: "test.php",
data: postData,
success: function(){
alert(proj_name + ' ' + status);
window.open("test.php");
},
// Alert status code and error if fail
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
Update
Change this:
if ($_POST)){
echo $proj_name;
echo $date;
echo $req_comp_date;
echo $status;
echo $secondUserId;
} else {
echo 'problem';
}
To this:
if ($_POST)){
// Make a array with the values
$vals = array(
'proj_name' => $proj_name,
'date' => $date,
'req_comp_date' => $req_comp_date,
'status' => $status,
'secondUserId' => $secondUserid
);
// Now we want to JSON encode these values to send them to $.ajax success.
echo json_encode($vals);
exit; // to make sure you arn't getting nothing else
} else {
// so you can access the error message in jQuery
echo json_encode(array('errror' => TRUE, 'message' => 'a problem occured'));
exit;
}
Now in your jQuery .success callback:
success: function(data){ // Our returned data from PHP is stored in "data" as a JSON Object
alert(data.req_comp_date); // access your returned vars like this.
// data.date; // is your posted date.. etc
alert(data.proj_name + ' ' + data.status);
window.open("test.php");
// You can also get your error message like so..
if(data.error) // if its true, we have a error, so display it.
alert('ERROR: ' + data.message);
},
You dont really have to do this next bit (jquery does a good job of determining the data type returned), but its nice to have it in the code to understand what is being returned.
$.ajax({ ...
type: "POST",
url: "test.php",
data: postData,
dataType: "json" // <-- Add this to tell jquery, we are being returned a JSON object.
.... });
I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.