Get value from ID of AJAX-loaded content - javascript

I have javascript to get content from another page, like this :
$.get('disp/run_txt.php?type=andon&dispnm=PS&line=1',function(data){
$('#result').html(data);
});
What I want is the value of id='result' can transfer to variable, i have try :
$result = "<span id='runtxt'></span>";
echo $result;
My question is, how to capture the id='result' to variable?

Try
var resultVariable = $('#result').val(); //For non-text value
OR
var resultVariable = $('#result').text(); //For text value

If you want to pass what you have in data to some PHP code, you will have to do an ajax call to a php page.
$.get('disp/run_txt.php?type=andon&dispnm=PS&line=1',function(data){
$('#result').html(data);
var url = 'your-php-page.php';
// Will now send data to your-php-page.php
// where you can assign it to the variable
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});

Related

Pass JS var to PHP var

I need to have a "global" variable because I need to use it in different page and I want to modify it too: I think that I need to use $_SESSION
I need to change this variable, when the user click on dropdown or list.
I have this:
SOLUTION 1
PageA:
$('#list.test li').on('click',function(){
choice=$(this).attr('id');
$.ajax({
url: "PageB.php",
data: {word : choice},
dataType: "html",
success: function (data) {
$('#content_table').html(data);
}
});
});
PageB
session_start();
$_SESSION['b']=$_GET['word'];
echo $_SESSION['b']; // It works
PageC for verify the result
session_start();
echo $_SESSION['b']; // Error !!
In my PageC, I have an error ( Notice: Undefined index: b )
Is it possible to update session variable with ajax ?
SOLUTION 2
PageA: I want to passe the id JS var to PHP var
$('#list.test li').on('click',function(){
choice=$(this).attr('id');
<?php $_SESSION['b'] ?> = choice; //<--- it is possible ?
$.ajax({
url: "PageB.php",
data: {word : choice},
dataType: "html",
success: function (data) {
$('#content_table').html(data);
}
});
});
This solution doesn't work because AJAX and PHP are note in the same side (client/server).
Thank you
You can push data to cookies via JavaScript, smth like document.cookie = "key=value";
And receive it on back-end like $_COOKIE["key"];.
$_SESSION['b']=$_GET['projet']; should be $_SESSION['b']=$_GET['word'];

Send Ajax post request and retrieve the inserted id

I am trying to submit a form which will insert data into a mysql database which is working fine. I then would like to return the id of the new inserted row (id auto increment in mysql table) as I want to open up a modal once the form is submitted so I can provide a link which includes id as a parameter in the url.
To send the data for the form I am using the following code:
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#commentForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "SubmitData.php",
data: string,
cache: false,
success: function(result){
//alert(result);
}
});
});
});
The SubmitData.php file then inserts the form data into the database.
In the SubmitData.php I can create a variable to pick up the id of the newly inserted row like
$last_id = mysqli_insert_id($conn);
Is there a way I can return the $last_id from the SubmitData.php file within the same function?
Yes return from SubmitData.php the id using the following echo:
echo json_encode(['id'=>$last_id]);
js:
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#commentForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "SubmitData.php",
data: string,
cache: false,
success: function(result){
alert(result.id);//this will alert you the last_id
}
});
});
});
print last id in that php file
echo $last_id;
get that in ajax success function
success: function(result){
alert(result);
}

Jquery get json data from data type dataString

I have the following jquery function which submits data to the database :
$('#book_client_form').submit(function (event) {
dataString = $("#book_client_form").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>operations/book_client",
data: dataString,
success: function (data) {
console.log(data);
$('.job_card_id').val(data[0].id);
$(".info_box_reload").show('slow');
setInterval(function () {
$(".add_new_client_div").hide('slow');
$(".clients_table_div").show('slow');
}, 3000);
}
});
event.preventDefault();
return false;
});
Once the data is supposed to returned the last insert id in json format which gives me the following output :
[{"id":"17"}]
But when I try to pass it to a text field or alert it , I get an undefined output or passes empty. Please advise on how can I pass it to the text input? I'm using datatype : datastring.
did you try parsing the JSON data?
data = JSON.parse(data);
console.log(data[0].id); // you can see the id in the dev console
$('.job_card_id').val(data[0].id);
or you can set dataType : 'jsonp' to get a JavaScript object as response
use dataType, its case sensitive.

Making Key Value pair for the form elements in JavaScript

I have a module where the forms created are dynamic. So the number of inputs can defer always. Also, the array key can also defer.
My current method of posting form is this:
name = form_options[option_1] value = 1
On submitting the form using POST, I get the form as array in $_POST, which looks like this.
form_options(
option_1 => 1
)
But, now I am trying to implement the same thing using AJAX. So, I would need a common module to get all form values.
I found a way to do it.
var objectResult = $('#options_form').serializeArray();
console.log(objectResult);
This gives me a result like this:
0: Object
name: "form_options[option_1]"
value: "1"
How can parse this result to get an array like $_POST array, which I can send as data in AJAX.
P.S: All the form elements have name field as form_options[key]
You should use this for get post data in PHP file.
// You can use like this
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: "POST", // Enter Request type GET/POST
url: 'action.php', // Enter your ajax file URL here,
dataType: 'json', // If you are using dataType JSON then in php file use die( json_encode($resultArray) );
data: objectResult, // Put your object here
beforeSend: function(){
alert('before');
},
error: function(data) {
console.log(data);
},
success: function(response){
console.log(response);
}
});
// In php file get values like this way
$_POST['form_options']
try like this,
In JQuery:
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: 'POST',
url: 'yoururl'',
data: objectResult ,
success:function(data){
alert(data);
}
});
In your php:
<?php echo var_dump($_POST);?>
You can use jquery serialize with ajax directly, there is no need to use serializeArray:
$.ajax({
type:"post",
url:"formHandleSkript.php",
data: $("#options_form").serialize(),
success: function(response){
$(".result").html(response);
}
});
For more information see http://api.jquery.com/serialize/

Getting PHP variable to jquery script file by AJAX call

So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
$('#results').html(data);
}
});
and it works fine by printing my results.
My php file is echoing data that should be printed in my results div.
Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??
Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.
<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>
And you could use those values accessing PHPVariables.VariableName1 on the javascript.
You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.
the explode function is used like this
explode('§', $somestringofinfoyouwanttoturnintoanarray);
you can then echo the relevent data like so
echo data[0];
which in this case wiill echo the text peiceofdata.
write this type of code in ajax file
var data =array('name'=>'steve', date=>'18-3-2014');
echo jsonencode(data);
//ajax call in this manner
$.ajax({
type: 'POST',
data: pass data array,
url: ajaxfile url,
success: function(data) {
var data = $.parseJSON(data);
$('#name').html(data.name);
$('#date').html(data.date);
}
});
Use json format, and in this json add your data variables :
PHP :
$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);
echo json_encode($arr);
Javascript :
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
data = JSON && JSON.parse(data) || $.parseJSON(data);
$('#results1').html(data.var1);
$('#results2').html(data.var2);
}
});

Categories

Resources