Solved

jquery ajax php variable

Posted on 2015-01-22
8
209 Views
Last Modified: 2015-01-26
Hi,

I have the following code:

$('.editar').click(function(){
			
			
			$.ajax({
  type: "POST",
  url: "seccionesAjax.php",
  data: { var_value: $(this).prevAll().eq(1).html() },async:false
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });
  
			
			$(this).parent().html("<td><form action='editar.php' method='post'><input type='text' name='subestacion' value='"+$(this).prevAll().eq(6).html()+"'><input type='text' name='alimentador' value='"+$(this).prevAll().eq(5).html()+"'><input type='text' name='fecha' value='"+$(this).prevAll().eq(4).html()+"'><input type='text' name='condicion' value='"+$(this).prevAll().eq(3).html()+"'><input type='text' name='hoja' value='"+$(this).prevAll().eq(2).html()+"'><select name='responsable' id='responsable'><option>SECCIONES</option><?php $seccionesQuery = "SELECT * FROM secciones"; //codigo para traer las secciones y mostrarlas al momento de añadir un nuevo interruptor	
$respuestasecciones = $conexion->query($seccionesQuery);
while ($seccionesLoop = $respuestasecciones->fetch_array()){?>
<option value='<?php echo $seccionesLoop[0];?>'<?php if($seccionesLoop[0] == $_SESSION['valor']){echo ' selected';}?>><?php echo $seccionesLoop[0] ?></option><?php } ?></select><input name='contestacion' type='text' value='"+$(this).prevAll().eq(0).html()+"'><input type='hidden' name='hojaOriginal' value='"+$(this).prevAll().eq(2).html()+"'><input type='submit' value='guardar'></form></td><td><?php echo $_SESSION['valor']; ?></td>")
		
			
		
		})

Open in new window


php side:

<?php

session_start();

$valor=$_POST['Id'];
$_SESSION['valor'] = $valor;

 echo json_encode($valor);

?>

Open in new window


my problem is that the $_SESSION['valor'] don't updated before the $(this).parent().html...... execute, and the selected criteria don't execute properly, what i can do?
0
Comment
Question by:joyacv2
  • 5
  • 3
8 Comments
 
LVL 33

Expert Comment

by:Slick812
ID: 40564585
Greetings  joyacv2, , I looked at both your javascript and the PHP server code,  There is a LARGE amount of misunderstanding about how and why AJAX works in your code - To send info (data) to a php page by AJAX you need to place that in the Jquery  data:  property, in this you have -
    data: { var_value: $(this).prevAll().eq(1).html() }
this will send a server side $_POST up  as   $_POST['var_value'];   NOT AS   $_POST['Id'];

I am not sure what  your -
    $(this).prevAll().eq(1).html()
is about, I will assume you have tested this to see if the does output the TEXT you want to send up by AJAX?
And  It is Highly recommended to NEVER use Never use the jquery -
   async:false
why use that ?

I can do some example code for you, but you may need to understand more about how AJAX works before you try and use it?

Next, On the server side PHP, you will always get Nothing (undefined) with this  $_POST['Id'];  as you do not send up any Id.
AND you have this -
      echo json_encode($valor);
WHY would you use json_encode on a NON ARRAY, it only works on arrays or objects.
0
 
LVL 1

Author Comment

by:joyacv2
ID: 40564604
sorry, for that, i paste the wrong code, this is the correct:

<?php

session_start();

$valor=$_POST['var_value'];
$_SESSION['valor'] = $valor;

echo $valor;

?>

Open in new window

0
 
LVL 33

Expert Comment

by:Slick812
ID: 40564786
OK, I read the new code, and you now have the seemingly correct for post as -
$valor=$_POST['var_value'];

But, , As far as I know the   $_POST['var_value'];   may not have any string characters in it (empty variable) , or it has a string value?  You do not say in your last comment if the -
    $_SESSION['valor']
is still empty after the AJAX call, , and you do NOT say what in in this alert -
       alert( "Data Saved: " + msg );
to maybe help to trouble shoot this could you add the following alert here -
   $('.editar').click(function(){
      alert("pre HTML= "+$(this).prevAll().eq(1).html() );
      $.ajax({

in that alert you should see the HTML text of whatever element the  prevAll() at pos 1 , has in it, if you do not see any added text, then the    $(this).prevAll().eq(1).html()   may not fit here?
0
 
LVL 1

Author Comment

by:joyacv2
ID: 40564808
hi,

the only problem that occurs in my code, is that the $_SESSION variable don't updated on the ajax code, i have to click the class twice and in the second one then works, i need the $_SESSION variable to update before the $(this).parent()........ runs, any idea?
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 33

Expert Comment

by:Slick812
ID: 40565025
If I look at the code you have presented here, , then I wonder What you are trying to accomplish? as far as I can tell this seems like an exersize to learn AJAX, as the only data you return from server side AJAX is the value you already have on your page.
You say - "to update before the $(this).parent()........ runs", , So My question is if the -
      $(this).prevAll().eq(1)
does not exist when the first click happens, then what are you doing this for?
Sorry, I am trying, but do not see what the elements of functioning for your page and AJAX sever return, have to do to get the results you need.

I will guess that you mean this line -
<td><?php echo $_SESSION['valor']; ?></td>
is empty, but I do not see what you may mean?
I need to take a break, will look here again later to day.
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40565672
You have not gavein a comment, I can only suggest at this point is to test the  $_POST['var_value']  to see if it has TEXT in it, maybe as -

<?php

session_start();

if (strlen($_POST['var_value']) > 0) {
    $_SESSION['valor'] = $_POST['var_value'];
    } else {$_SESSION['valor'] = "Default";}

echo $_SESSION['valor'];

?>

Open in new window


if your PHP uses $_SESSION['valor'] outside of the AJAX response as in -
     <td><?php echo $_SESSION['valor']; ?></td>

then you can test to see if the $_SESSION['valor'];  has been set -
<?php

session_start();
if ( !isset($_SESSION['valor'] ) ) $_SESSION['valor'] = "default";
?>

Open in new window


In javascript, you can also test to see if your  $(this).prevAll().eq(1)  exists, and or has any html string in it, if not then use a default string value instead, to send the Ajax.
0
 
LVL 1

Author Comment

by:joyacv2
ID: 40566222
ok,

Let me explain what i want to do:

I want to send to ajax a jQuery variable the prevAll.... one, then this will saved in a $_SESSION variable. The alert in the ajax is only for verification that the success occurs. The session variable that is in the php code, i need to be used in the code of this.parent..... for the verification of what is the value for then apply the selected option.

In my code I have a line of code with info and i when i press the button editar, then all the fields convert to a text field with the actual value, and a dropdown in one of the fields, but i need that appears the selected option with the name that is the field before press the editar button. That is the php that you see inside the jQuery parent.... code. Please if you need more information, let me know, thank you very much!
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
ID: 40566952
Thank s for explaining,  I can do some jquery  AJAX code in JS and PHP, with my view on how this might work, if you like?

But, I look at this code section for JS  (which I have REFORMATED so a developer can look at it to make sense of it)-
$(this).parent().html("<td><form action='editar.php' method='post'><input type='text' name='subestacion' value='"+
$(this).prevAll().eq(6).html()+
"'><input type='text' name='alimentador' value='"+
$(this).prevAll().eq(5).html()+
"'><input type='text' name='fecha' value='"+
$(this).prevAll().eq(4).html()+
"'><input type='text' name='condicion' value='"+
$(this).prevAll().eq(3).html()+
"'><input type='text' name='hoja' value='"+
$(this).prevAll().eq(2).html()+
"'><select name='responsable' id='responsable'><option>SECCIONES</option>"+
<?php 
  //codigo para traer las secciones y mostrarlas al momento de añadir un nuevo interruptor
  $seccionesQuery = "SELECT * FROM secciones"; 
  $respuestasecciones = $conexion->query($seccionesQuery);
  while ($seccionesLoop = $respuestasecciones->fetch_array()){
?>"+
"<option value='"+
"<?php 
   echo $seccionesLoop[0]."'";
   if($seccionesLoop[0] == $_SESSION['valor']){ echo ' selected>';} 
   echo $seccionesLoop[0] ?></option><?php } 
?>"+
"</select><input name='contestacion' type='text' value='"+
$(this).prevAll().eq(0).html()+
"'><input type='hidden' name='hojaOriginal' value='"
+$(this).prevAll().eq(2).html()+
"'><input type='submit' value='guardar'></form></td><td>"+
"<?php echo $_SESSION['valor']; ?></td>")

Open in new window

OK, my opinion, as most beginners in AJAX, it looks like you have made the thinking error that for an AJAX exchange with the PHP server, that the PHP code you have written in to the Javascript like -
     if($seccionesLoop[0] == $_SESSION['valor']){ echo ' selected>';}
changes with the PHP, as if you Update the $_SESSION['valor'] in your ajax PHP like you do -
<?php
session_start();
$valor=$_POST['var_value'];
// IMPORTANT changing the $_SESSION['valor'] here
//  DOES NOT CHANGE the old Javascript write PHP value
$_SESSION['valor'] = $valor;
echo $valor;
?>

Open in new window

then the old write of $_SESSION['valor'] here -
       if($seccionesLoop[0] == $_SESSION['valor']
also changes, but it DOES NOT,  the javascript has NO contact or influence from PHP, except what you change by Javascript rewrites from the data sent back from the Server.

So when this page goes into the browser what the JS string portion for the select will look like this-
<select name='responsable' id='responsable'><option>SECCIONES</option>
<option value='first'first</option>
<option value='second'second</option>
</select>

Open in new window

please notice that in the browser JS there are now NO PHP, this <select> string is unchanging and the displayed <select> box from it does NOT change selection, from PHP AJAX changes.

if you need to change the select box selection, you can use javascript jquery maybe like -
     $('#responsable option:contains($(this).prevAll().eq(1))').prop('selected', true);

you might change this last part to -
     "'><input type='submit' value='guardar'></form></td><td id='tV'></td>"
and update that <td> with -
     $("#tV").html($(this).prevAll().eq(1));

I assume that this $(this).prevAll().eq(1)  , exists, you say something about the First button click replacing some code that don't have those with the inputs I see in the JS string. So you may need to place some alternate code if the $(this).prevAll().eq(1)  does not exist on first click? ? ? ?
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now