add multiple data using jquery ajax - javascript

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);
}
});

Related

How do I alert the variable using url segment with ajax?

I am using HVC codeigniter.
I wanted to alert the value of variable.
Here's the code on my view.
$("#user_table tr").click(function(){
$userid = $(this).closest('tr').children('td:first').text();
$.ajax ({
type: "POST",
url: "manageUser_controller/log_history/$userid",
success: function(data){
alert(data);
}
});
});
Here's the code on my controller.
function log_history($userid) {
echo $userid;
}
You need to edit your code as follows
var userid = $(this).closest('tr').children('td:first').text();
url: "manageUser_controller/log_history/'+userid,
try to send as data like this
$("#user_table tr").click(function(){
var userid = $(this).closest('tr').children('td:first').text();
$.ajax ({
type: "POST",
url: "manageUser_controller/log_history",
data:{userid : userid},
success: function(data){
alert(data);
}
});
});
and get it on controller using input post like this
function log_history()
{
$user_id = $this->input->post('userid',true);
echo $userid;
}
it's also be filter by true.

Select function in ajax

My php file
$option1 = filter_input(INPUT_POST, 'key', FILTER_SANITIZE_SPECIAL_CHARS);
if(isset($option1) && !empty(option1)) {
$sql = "SELECT * FROM fantasy WHERE os_id='$option1'";
}
My ajax
function filter(){
var str = $("#advanced-search1").val();
$.ajax({
dataType: 'html',
url: "filter.php",
type: "POST",
data: {"key": str},
success: function(response){
$('#result').html(response);
}
});
}
From the above, stated that my select function id is #advanced-search1 whereas my submit button would be onclick="filter()". But it still doesn't work for me to execute the sql command in my php file. From my url browser, it stated the required select value, but it doesn't show anything in my #result div
Add event.preventDefault(); at the beginning of filter function :
function filter(event){
event.preventDefault();
var str = $("#advanced-search1").val();
$.ajax({
dataType: 'html',
url: "filter.php",
type: "POST",
data: {"key": str},
success: function(response){
$('#result').html(response);
}
});
}
However, you need to change the call also to pass the event argument :
<button onclick="filter(event);" >..</button>
Instead of :
<button onclick="filter();" >..</button>
If does not work , you have to report your PHP log as well as your HTML skeleton.

Passing GET parameter with ajax

I have a link that I want to use with ajax. Here is the link:
<a class="export_csv" href="ajax/createCSV.php?saleid=4"><img src="/img/record.csv.png"></a>
The ajax works fine but I can't pass through the GET variable. Here is the jquery:
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: $(e).data['saleid'],
success: function(results){
console.log('it worked');
}
});
});
Here is the target php page:
<?php
include('./includes/global.php');
//$cl = new Client();
//$cl->createCSV();
echo "This Works ";
$test = $_GET['saleid'];
echo $test;
echo "did work for me";
?>
try like this ,send data to php page using data option
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: "saleid=4",
success: function(results){
console.log('it worked');
}
});
})
or
$('.export_csv').on('click', function(e){
urls=$(this).attr('href');
e.preventDefault();
$.ajax({
url:urls,
type: 'GET',
success: function(results){
console.log('it worked');
}
});
}
You need to pass the data as JSON format like
data:{saleid:$(e).data['saleid']}
But actually dont know what is $(e).data['saleid']
$('#myDomSelectorId').data['saleid'] need to be JSON formated like this :
data : { saleid : $('#myDomSelectorId').data['saleid'] }
Or directly data : "saleid="+$('#myDomSelectorId').data['saleid']
Full example :
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: { saleid : $('#myDomSelectorId').data['saleid'] },
success: function(results){
console.log('it worked');
}
});
});

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);
}
});

Post objects in jquery Ajax

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"];

Categories

Resources