how to send multiple ajax post - php

I have 2 ajax is an array and single char:
var jsonEncode = JSON.stringify(TableData); --> output: [{"name":"Ristha","age":"30"},{"name":"Niken","age":"25"}]
var code = $('#mutiplearray-code_reg').val(); --> output: 1RF46TA
How to send ajax post when I use 2 data like that:
$.ajax({
type: "POST",
data: "pTableData=" + jsonEncode + "code1=" + code,
success: function(msg){
// alert(msg);
},
});
When I get using in my controller:
$tableData = stripcslashes($_POST['pTableData']);
$tableData = json_decode($tableData, true);
$name1 = $tableData['name'];
$age1 = $tableData['age'];
$code1 = $_POST['code1'];
It's have error dev tool undefined code1 and pTableData?? What I'm do wrong with use multiple data in my ajax?
When I'm just using post data one of them is work correctly

Pass data as json. You passed the data as string.
$.ajax({
type: "POST",
data: {pTableData: jsonEncode, code1: code},
success: function(msg){
// alert(msg);
},
});

$.ajax({
type: "POST",
data:{'pTableData':jsonEncode,'code1':code},
success: function(msg){
// alert(msg);
},
});

Related

Json unable to pass array to php

As the title says, I failed to pass the data array via json ajax to php. I am using codeigniter, what did I do wrong? here is the jQuery code:
function load_page_data1(){
var data = [];
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Here is the php code:
function getdata(){
$parameter = '';
if(isset($_POST))
{
if(isset($_POST['val']))
{
$parameter = $_POST['val'];
} else
{
echo "failed!";
}
}
$this->load->model('Chart');
$this->load->helper('url');
$data1 = $this->Chart->getdata_solid($parameter);
echo json_encode($data1);
}
Final:
Guys, it turn out that the values did passed from jQuery to php, the problem is that I stupidly call the same php function twice within the javascript function, then the second time calling without posting the 'val', so that the php function error and stop.
Thank you all for your answers, at least I learn the different ways to passing data by using jQuery.
Don't make a array if it's not a array just make a object
var data = {};
data.val = "solid_t1";
// equivalent to
data ={val:"solid_t1"};
// equivalent to
data['val'] ="solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
Update 1: if you need to send array you need to make a proper array object like below
Example :
var data=[];
item ={val:'value'};
data.push(item);
var new_data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: new_data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
For Debugging :
May be problem with your server side code .so for the testing purpose comment all the line in function just do this echo json_encode($_POST); and in your ajax success function just add console.log(output); and let me know the result.
create one json object
jsonObj = [];
create array list as per your need
item = {}
item ["val"] = "solid_t1";
push the array list in to the json.
jsonObj.push(item);
Please have a try like this. It is working in my case.
Your full code will be like
function load_page_data1(){
jsonObj = [];
item = {}
item ["val"] = "solid_t1";
jsonObj.push(item);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
The another way to use this is given below.
function load_page_data1(){
var jsonObj = {};
jsonObj["val"] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Instead of var data = []; use var data = {}; to initialize your data. It should solve your problem.
Your data wasn't being passed as json, now it will.
Code will be:
function load_page_data1(){
var data = {};
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/welcome/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
One more suggestion please use CI input library for post request in controller.
e.g.
$parameter = $this->input->post('val');

How to pass two variables to php,mySQL using ajax jquery

$("#submit_login").click(function(){
var username=$('input[name=user_email]');
var password=$('input[name=user_password]');
var data;
data: "name="+username+"&pwd="+password,
$.ajax({
type: "POST",
dataType: "json",
url: "newExam.php",
data: data,
success: function(data) {
alert("Form submitted successfully");
}
});
});
How to give the data variable so that we can fetch it in PHP using $_REQUEST?
The above representation of the data variable shows an error.
You can pass the data as json,
$.ajax({
type: "POST",
dataType: "json",
url: "newExam.php",
data: {
name: username,
pwd: password
},
success: function(data) {
alert("Form submitted successfully");
}
});
Also, names should match the parameters in the function.
Client Side
$("#submit_login").click(function(){
var username=$("input[name='user_email']").val();
var password=$("input[name='user_password']").val();
$.ajax({
type: "POST",
dataType: "json",
url: "newExam.php",
data: {name : username, pwd : password },
success: function(data) {
alert("Form submitted successfully");
}
});
});
Server Side
<?php
// file : newExam.php
// to view post array
if(!empty($_POST))
{
print_r($_POST);
}
// access individual element
if(isset($_POST['name']))
{
echo $_POST['name'];
}
?>
The above representation of the data variable shows an error.
Absolutely. That is correct because there is an error. You have a variable and you are assigning a query string with : where it should be =:
data= "name="+username+"&pwd="+password;
But this is not a good idea because you have to post the values not the input objects. username is an html input element, instead you should post an object like:
$("#submit_login").click(function(){
var username=$('input[name=user_email]').val();
var password=$('input[name=user_password]').val();
var data = {name:username, pwd:password};
$.ajax({
type: "POST",
dataType: "json", // <---make sure you return json from the php side.
url: "newExam.php",
data: data,
success: function(data) {
alert("Form submitted successfully");
}
});
});
Your selectors dont look right to me.
var username=$('input[name="user_email"]');
var password=$('input[name="user_password"]');
Note the double quotes around the input name attributes
Can you try the below code format:
data: {name : username, pwd : password }

Can't post JSON variable with AJAX to PHP

In the first document I added a JSON string filled with numbers to localstorage like this:
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}});
Then in another document I am trying to post the JSON string retrieved from local storage like this:
<script>
var data = JSON.parse(localStorage.getItem('key'));
var localData = data.join(", ");
$.ajax({
type: 'post',
data: {localData: localData},
url: '',
dataType: "json",
success: function(result){
console.log(result)
}});
</script>
The PHP on the same page as the post tries to fetch the data like this:
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$values = json_decode($user_id);
var_dump($values);
?>
When I run var_dump I get Array(), so in essence it doesn't post anything. Anyone know whats going wrong?
You don't need to use JSON when sending an array in an object argument to $.ajax. Just put the array there, and jQuery will URL-encode it.
var data = JSON.parse(localStorage.getItem('key'));
$.ajax({
type: "post",
data: { localData: data },
...
});
Then in PHP you can do:
$values = isset($_POST['localData']) ? $_POST['localData'] : array();
var_dump($values);
You can also send JSON this way:
var json_string = localStorage.getItem('key');
$.ajax({
type: "post",
data: { localData: json_string},
...
});
then in PHP do:
$values = json_decode(isset($_POST['localData']) ? $_POST['localData'] : '[]');
var_dump($values);

Localstorage to PHP variable

I am sending and retrieving some data with this ajax call and saving result in localstorage like this:
$.ajax({
url: "list.php",
data: {values: values},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}
});
Then I am retrieving it in a separate PHP document like this and trying to add it to a PHP variable. I think the problem occurs because when I console.log, it logs 10 times or so. And I can't echo it in PHP. How do I pass it correctly?
<script>
var localData = JSON.parse(localStorage.getItem('key'));
$.each(localData, function(key, value){
console.log("This is the data that is stored", localData)
$.ajax({
type: 'post',
data: {localData},
dataType: "json",
success: function(result){
console.log(result)
}
});
</script>
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier = implode(", ", $user_id);
?>
You are causing an asynchronous functionality of ajax() real pain by calling it in a loop
Why dont you use join() to join items with ", " in js like what you do in php
<script>
var localData = JSON.parse(localStorage.getItem('key')).join(", ");
$.ajax({
type: 'post',
data: {localData},
dataType: "json",
success: function(result){
console.log(result)
}
});
</script>
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier = $user_id;
?>
You Should also cast user_id as an (int) if user_id need to be a single value and int
$verdier = (int) $user_id;

jQuery Ajax post to php not catching variable

What am i doing wrong. PHP doesn't seem to catch title and wrapper from $.ajax. Does the code look correct. The success message i get indicate an error that title is not found.
jQuery main.html
$.ajax({
type: "POST",
url: "process.php",
data: 'title=test&wrapper=testing',
success: function(msg){
alert( "Data Saved: " + msg );
}
});
PHP process.php
<?php
$title = $_REQUEST['title'];
$wrapper = $_REQUEST['wrapper'];
...
?>
Take a look: jQuery.ajax()
The data parameter is better to be a Key/Value pairs object, it's cleaner and easier to debug :)
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Thats a good solution.but if I try to send data through a form in a webservice.
$.ajax({
type: "POST",
url: "process.php",
data: {
title: $('#title').val,
name: $('#name').val
},
success: function(data){
alert(data );
}
});
Here title and name are forms element in client side.but i am not able to get post value in json based webservice file say process.php

Categories