Post objects in jquery Ajax - javascript

I have to send position size and their parent details in jquery ajax and get them by PHP
My code is :-
$("#save").click(function(){
var pos=[];
$(".dr").each(function(index){
dragId=$(this).attr("id");
topPos=$("#"+ dragId).position().top;
left=$("#"+ dragId).position().left;
dragLeft=left/10;
dragLeft=dragLeft ? dragLeft:0;
dragTop=topPos/10;
dragTop=dragTop ? dragTop :0;
dragWidth=$("#"+dragId).width();
dragHeight=$("#"+dragId).height();
parentDivWidth=$("#"+dragId).parent().width();
parentDivheight=$("#"+dragId).parent().height();
parentDivClass=$("#"+dragId).parent().attr("class");
var obj = {};
obj = {left: dragLeft,top :dragTop,dragWidth:dragWidth,dragHeight:dragHeight,parentDivWidth:parentDivWidth,parentDivheight:parentDivheight,parentDivClass:parentDivClass};
pos[$(this).attr("id")]=obj;
})
$.ajax({
type: "POST",
url:"<?php echo Yii::app()->request->baseUrl?>/index.php/BillSettings/savePositions",
data:{pos:pos},
dataType:'html',
success: function(res){
console.log(res);
}
})
});
PHP code
var_dump($_REQUEST);
But I can not get value of $_REQUEST or $_REQUEST['pos'].Any help should be appreciated.

js:
$.ajax({
type: "POST",
data:{pos: JSON.stringify(pos},
//...
php:
var pos = json_decode($_REQUEST['pos']);
var_dump(pos);
Is it what you want?

try converting the object you want to pass via ajax to a string
$.ajax({
type: "POST",
url:"<?php echo Yii::app()->request->baseUrl?>/index.php/BillSettings/savePositions",
data: JSON.stringify(pos),
dataType:'html',
success: function(res){
console.log(res);
}
})
then in php
$pos = json_decode($_REQUEST['pos']);

js:
$.ajax({
type: "POST",
url:"<?php echo Yii::app()->request->baseUrl?>/index.php/BillSettings/savePositions",
data:{"pos":pos},
cache: false,
success: function(res){
console.log(res);
}
})
php:
$post=$_POST["post"];

Related

add multiple data using jquery ajax

i want to add multiple data in jquery ajax.
i try like this but not working,
i take a data from this span.
<span id="<?php echo $tutorial_id; ?>" modes="<?php echo $modesearch ?>" searchs="<?php echo $searchstring ?>" class="show_more" title="Load more posts">Show more</span>
<script>
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
var MODESEARCH = $(this).attr('modes');
var SEARCHSTRING = $(this).attr('searchs');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'GET',
url:'getDataS.php',
data:'idpost='+ID,
data:'modesearch='+MODESEARCH,
data:'searchstring='+SEARCHSTRING,
success:function(html){
$('#show_more_main'+ID).remove();
$('.tutorial_list').append(html);
}
});
});
});
</script>
when i try to run it, result always showing the latest data.
in this case just showing data from searchstring.
You can send the data as a json object like { idpost : ID, modesearch : MODESEARCH, searchstring : SEARCHSTRING }
$.ajax({
type:'GET',
url:'getDataS.php',
data:{ idpost : ID, modesearch : MODESEARCH, searchstring : SEARCHSTRING },
success:function(html){
$('#show_more_main'+ID).remove();
$('.tutorial_list').append(html);
}
});
One way of solving this would be to combine your query strings with an ampersand:
$.ajax({
type: 'GET',
url: 'getDataS.php',
data: 'idpost=' + ID + '&modesearch=' + MODESEARCH + '&searchstring=' + SEARCHSTRING,
success: function(html) {
$('#show_more_main'+ID).remove();
$('.tutorial_list').append(html);
}
});
Alternatively, you can simply pass JSON data, remembering to wrap your keys in quotation marks:
$.ajax({
type: 'GET',
url: 'getDataS.php',
data: {'idpost': ID, 'modesearch': MODESEARCH, 'searchstring': SEARCHSTRING},
success: function(html) {
$('#show_more_main'+ID).remove();
$('.tutorial_list').append(html);
}
});
Hope this helps :)
You can also try
var formData =
{
'idpost' : ID,
'modesearch' : MODESEARCH,
'searchstring' : searchstring
};
$.ajax({
type : 'GET',
url : 'data.php',
data : formData,
success : function(html)
{
$('#show_more_main'+ID).remove();
$('.tutorial_list').append(html);
}
});

checking JSON data with jQuery

I have written a php script:
cch.php:
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
json_encode($array);
$stmtcheck->close();
And jquery for submitting form is
recover.php:
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function()
{
}
});
});
The script is returning more than one variable and the returned data should be in JSON format.
How do I read the data in jQuery?
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function(data) //parameter missing
{
var json = $.parseJSON(data);
console.log(json);
//in console you will get the result response
}
});
});
Hello your php code should echo the JSON output like this:
<?php
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
$stmtcheck->close();
echo json_encode($array);
?>
Now, in your javascript, you can use JSON.parse method to get the JSON.
Also, specifying your response type as JSON will automatically return a JSON object.
$("#formUnlock").submit(function (e) {
e.preventDefault();
$.ajax({
url: '../scripts/cch.php',
method: 'POST',
data: $('#formUnlock').serialize(),
dataType: 'JSON',
success: function (json_string) {
var res = JSON.parse(json_string);
console.log(res);//This should output your JSON in console..
}
});
});

Get data from a different php file using JQuery

I have an JQuery function which submits data from a php form to a different php file(submitForm.php). The submission works fine and there isn't any problem whatsoever, below is the handler:
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
success: function(data) {
}
});
}
Now, I want to be able get data from the submit form (submitForm.php), and load it into a different page.
This is my submitForm.php
<?php
$name="Amanda";
$age="23";
$data = array("name"=>"$name","age"=>"$age");
header("Content-Type: application/json");
echo json_encode($data);
?>
This is how my new submitHandler looks like
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
success: function(data) {
var name= html(name);
var age=html(age);
$("#message").load("newpage.php",{name:name,age:age});
}
});
}
I think I am doing it wrong, I would be grateful if somebody could correct me or give an idea as to how to do this. Thanks
It should be like this. If you want to take your returner data you should use formal parameter of success function.
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
dataType : 'json',
success: function(data) {
var name= data.name;
var age=data.age;
$("#message").load("newpage.php",{name:name,age:age});
}
});
}
Edit: Also you need dataType: 'json' line.

Post array from javascript to php function using Ajax

i want to post an array from java script to php by ajax. But i don't know how do that, especially send it to php function like controller class. Correct me if i'm wrong, this is my java script source, as a function to send an array :
<script>
function send(){
var obj = JSON.stringify(array);
window.location.href = "post.php?q=" + obj;
}
</script>
i was try, but still fail. really need help..
As described in the JQuery API documentation, you can use
var rootPath="http://example.com/"
var jsonData = $.toJSON({ q: array });
var urlWS = rootPath + "post.php";
$.ajax({
url: urlWS,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function(result) {
// do something here with returned result
}
});
var array= [];
array[0] = 'hi';
array[1] = 'hello';
$.ajax({
url: 'http://something.com/post.php',
data: {array: array},
type: 'POST'
});
try like this,
var data_to_send = $.serialize(array);
$.ajax({
type: "POST",
url: 'post.php',
data: data_to_send,
success: function(msg){
}
});
or
you can pass as json like below,
$.ajax({
type: "POST",
url: 'post.php',
dataType: "json",
data: {result:JSON.stringify(array)},
success: function(msg){
}
});
var arr = <?php echo json_encode($postdata); ?>;
ajax: {
url:"post.php"
type: "POST",
data: {dataarr: arr},
complete: function (jqXHR, textStatus) {
}
You can try this .this will work
example
ajax code:
$.ajax({
url: 'save.php',
data: {data: yourdata},
type: 'POST',
dataType: 'json', // you will get return json data
success:function(result){
// to do result from php file
}
});
PHP Code:
$data['something'] = "value";
echo json_encode($data);

How to get the ajax response from success and assign it in a variable using jQuery?

Hello guys I have a problem in getting the response from my ajax. If I display it in the console. I can view it. But How do I assign it in a variable?
Here's what I have.
In my PHP code I have this
public function checkPassword($password){
$username = $this->session->userdata('username');
$validate = $this->members_model->checkPassword($password,$username);
echo $validate;
}
In my jquery I have this
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var g = response;
if(g == 1){
$('#existing_info').html('Password is VALID'); //Doesn't display the VALID if the response is 1. Why?
}else{
$('#existing_info').html('Password is INVALID!');
}
}
});
});
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var k=response;
if(k.indexOf("1") != -1)
$('#existing_info').html('Password is VALID');
else
$('#existing_info').html('Password is INVALID!');
}
});
response is in response variable of success function.
indexof returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex,
returns -1 if the value is not found.
try something like this
<script>
var k = null;
$(function(){
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
if(response == 1){
k = response;
}
}
});
});
})
</script>
In your success response you will get what you are set to output in php.
If you want to get an array or data set you can encode it in json in your php script like
echo json_encode($validate);
Then in your jquery you can use this response like this
var responseData = jQuery.parseJSON(response);
console.log(responseData);
console.log will print json object in browser console.
You can use this json object like this
responseData.some_data
Ajax is asynch so you will have access to it after the ajax method returns:
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json'
}).then(function(response){
var k;
if(response == 1){
k = response;
//call another function that needs k here
}
});
});
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
k=response;
}
});
var k = null;
$('#existing').on('keyup', function() {
var id = '<?php echo $this->session->userdata("user_id"); ?>',
password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type : 'POST',
url : password_url,
success : function(data) {
if(data === '1') {
k = data;
}
}
});
});
response parameter itself contain data so just assign that to variable and use it.
$.ajax({
type: 'POST',
url: password_url,
success: function(response){
if(parseInt(response) == 1){
var k = response;
}
}
});
Your response data is in response variable of success function. Since the response type is json you can assign it directly to javaScript variable.
Also you comparison is wrong try if(g == '1') instead if(g == 1). You are getting a string as response and your checking equality with a numeric type which won't be equal at any point.
ie:-
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
contentType:"application/json",// Add Content type too
success: function(response){
k=response;
}
});
if your json response is as shown below
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
you can access menuitem array as
success: function(response){
k=response.menu.popup.menuitem;
}
File Name votepost.php
<?php
include("domain.php");
$csid=$_POST['CSID'];
$voteid=$_POST['VOTEID'];
$myid=$_POST['MYID'];
$usertype=$_POST['USERTYPE'];
$myurl =URL."putvote.php?csid=".$csid."&voterid=".$myid."&voteid=".$voteid."&usertype=".$usertype;
$myurl=str_replace(" ","%20",$myurl);
$jsondata = file_get_contents($myurl);
$data = json_decode($jsondata);
if($data->response=="true")
{
echo 'true';
}
else
{
echo 'false';
}
?>
ajax reponse use $.trim for IF ELSE
$.post("votepost.php", {CSID:csid,VOTEID:voteid,MYID:myid,USERTYPE:usertype}, function (data) {
if($.trim(data)=='true')
{
alert('ok');
}
else
{
alert('error');
}
});
I hope you will solve your problem
You can create the js blank array and assign it to the same array.
var resp = [];
jQuery.ajax({
dataType: "json",
method: 'post',
url: 'ajax.php',
async: false,
data: {postData: 'postData'},
success: function(data){
resp.push(data);
}
});

Categories

Resources