Jump to content

pass values ​​from ajax to php without refresh the page


biza

Recommended Posts

Sounds like there is an error then. Are you sure you are inspecting the request? You should also add an error callback handler as well.

error: function(response){  console.log('error with request');  console.log(response);}

What you need to be doing is alerting and debugging every step of your application to find out what it is doing.

 

Usually, in an situation where I would be using POST, I typically use GET initially so I can call the PHP script right from my browser, with the query params in the URL. I make sure the PHP script is working before I try and wire it up on the front end, and then once that's working, I switch it POST. That was I can debug and trace each part in isolation, and build it one piece at a time.

Link to comment
Share on other sites

I dont detect de error .

I send you the screen shot's of my all work . I have done all things and nothing.

My page:

https://www.dropbox.com/s/70sey1evjb4nm6y/Screen%20Shot%202013-10-29%20at%203.41.47%20PM.png

My page with firebug console error:

https://www.dropbox.com/s/s5o3xw1d52aitls/Screen%20Shot%202013-10-29%20at%203.43.31%20PM.png

My code view in console error firebug :

https://www.dropbox.com/s/zrr2c3jcs4fioll/Screen%20Shot%202013-10-29%20at%203.43.37%20PM.png

 

I change the code to see an error callback handler and nothing, only an error query.min.js (linha 6) alert

https://www.dropbox.com/s/shb08uzss96x3gu/Screen%20Shot%202013-10-29%20at%203.57.10%20PM.png

Link to comment
Share on other sites

The server is responding with a bunch of HTML and Javascript, so that's what the ajax response contains. It's responding with the code in your first post, in the box you labeled AJAX. Is that what you want it to do, you want to submit a value to the server and have the server respond with Javascript code? The inser_actividade.php page is responding with the ajax Javascript code that is supposed to send data to inser_actividade.php. Post your code for that page, what does the inser_actividade.php page contain?

Link to comment
Share on other sites

three things

1) are those console shots the actual output of your requests? It just looks like code.

2) I don't see any screenshots of the network tabs. As we've mentioned, that's where you need to be looking when you make the request so you can see what the actual response is

 

http://getfirebug.com/network

 

3) In your second screenshot, the */ doesn't look it should be there.

Edited by thescientist
Link to comment
Share on other sites

these are the shots of the actual output request...

https://www.dropbox.com/s/v1p5defscvdqgvc/Screen%20Shot%202013-10-29%20at%206.07.02%20PM.png

 

and all code I use in the inser_actividade.php page is:

<script type="text/javascript" src="js/jquery.min.js"></script><script type="text/javascript">function show(){var option = document.getElementById("subuniverso").selectedIndex;var ref = document.getElementById('subuniverso').options[option].text.substr(0,3);	alert( ref); // <- Retorna os dados em array dos option selecionados	$.ajax({		                        url: 'inser_actividade.php',				type: 'GET',               	data: {ref : ref}, 				cache: true,				/*success: function(response) {					alert('foi enviado com sucesso' + ref)								},							*/			error: function(response){  console.log('error with request');  console.log(response);}            }        );};show();</script>      <?$data = date("Y-m-d");$validade = strtotime(date("d-m-Y", strtotime($data))."+0 day");set_time_limit(0); ini_set("memory_limit","50M");if (isset($_REQUEST['submit'])) {$imagens = $_FILES['arquivo'];for($g=0; $g < 5; $g++)//for($g=0; $g < sizeof($imagens); $g++)// for ($g = 0; $g < count($imagens); $g++)if(@$nome = $_FILES['arquivo']['name'][$g] != ""){ // para campos vazios{        $nome = $_FILES['arquivo']['name'][$g];        $tipo = $_FILES['arquivo']['type'][$g];        $tmpname = $_FILES['arquivo']['tmp_name'][$g];        $renomear = md5(uniqid(rand(), true)); // nome aleatorio        $nome_grande  = ($renomear . "-g.jpg"); // cria nome da imagem                      $matriz[] = $nome_grande;		                        $pasta_imagens = "../universo/actividades/"; //diretorio pra onde vai a imagem        $caminho = $pasta_imagens . $nome; // caminho com nome da imagem e local para guardar				$pasta_pequena ="../universo/actividades/peq/";//directorio das imagens pequenas		$caminho2 = $pasta_pequena . $nome;        //---------------------------------- CRIAR IMAGEM PROPORCIONAL -------------------------------------------        if(move_uploaded_file($tmpname, $caminho)) // move a tmp_name pro caminho dado        {                list($pontoX, $pontoY, $tipo) = getimagesize($caminho);                $img = imagecreatefromjpeg($caminho);                $largura_maxima = 640; //largura máxima                $altura_maxima = 480; //altura máxima                        if ($pontoX == $pontoY) { // se a altura e largura originais forem iguais                        $largura = $largura_maxima;                        $altura = $largura_maxima;                        }                        elseif ($pontoX >= $pontoY) { // se a largura for maior que a altura                        $nova_largura = $largura_maxima;                        $nova_altura = ($pontoY*$nova_largura)/$pontoX;                                // mas se depois da redução a altura for maior que $altura_maxima então reduz novamente                                if ($nova_altura >= $altura_maxima) {                                $altura = $altura_maxima;                                $largura = ($nova_largura*$altura)/$nova_altura;                                }                                else {                                $largura = $largura_maxima;                                $altura = ($pontoY*$largura)/$pontoX;                                }                        }                        elseif ($pontoX <= $pontoY) { // se a largura for menor que a altura                        $nova_altura = $altura_maxima;                         $nova_largura = ($pontoX*$nova_altura)/$pontoY;                                // mas se depois da redução a largura for maior que a $largura_maxima então reduz novamente                                if ($nova_largura >= $largura_maxima) {                                $largura = $largura_maxima;                                $altura = ($nova_altura*$largura)/$nova_largura;                                }                                else {                                $altura = $altura_maxima;                                 $largura = ($pontoX*$altura)/$pontoY;                                }                        }                        $foto_grande = imagecreatetruecolor($largura, $altura); // aqui eu pego a imagem no caminho e jogo na memoria                        imagecopyresampled($foto_grande, $img, 0, 0, 0, 0, $largura, $altura, $pontoX, $pontoY); // sample da imagem com o tamanho                        imagejpeg($foto_grande, $pasta_imagens . $nome_grande, 100);												//---------------------------------- CRIAR THUMB desPROPORCIONAL -------------------------------------------                                                $thumbnail = imagecreatetruecolor(98, 65); // aqui eu pego a imagem no caminho e jogo na memoria                        imagecopyresampled($thumbnail, $img, 0, 0, 0, 0, 98, 65, $pontoX, $pontoY); // sample da imagem com o tamanho                        imagejpeg($thumbnail, $pasta_imagens . $nome_grande, 100);												unlink($caminho); // apaga a imagem original						unlink($caminho2);			        } // if move_uploaded_file}// fecha if dos campso vazios}  $sql = "INSERT INTO tbl_actividade (subuniverso_id, entidade, legenda, descri, preco, pessoa, referencia, data) VALUES ('". $_POST['sub_uni']. "','". $_POST['entidade']. "','". $_POST['legenda']. "','". $_POST['descricao']. "','". $_POST['preco']. "', '". $_POST['pess']. "','". $_POST['referencia']. "','$data')" ; $sql = mysql_query( $sql ) or die( "Houve erro na gravação dos dados." ) ;  $actividade= mysql_insert_id() ;    mysql_query( "INSERT INTO tbl_imagem_produto (imagem1,imagem2, imagem3, imagem4, imagem5, imagem6, actividade_id, entidade, data)  VALUES ('$matriz[0]','$matriz[1]','$matriz[2]','$matriz[3]', '$matriz[4]','$matriz[5]','$actividade','". $_POST['entidade']. "','$data')" ) ;        mysql_query( "INSERT INTO tbl_detalhe_actividade (periodo, descricao, programa, informacoes, actividades, localizacao, locais, servicos, actividade_id)  VALUES ('". $_POST['funcionamento']. "','". $_POST['descricao']. "','". $_POST['programa']. "','". $_POST['informacao']. "','". $_POST['actividades']. "','". $_POST['localizacao']. "','". $_POST['interesse']. "','". $_POST['servicos']. "','$actividade' )" ) ;  echo '<div id="success" class="info_div"><span class="ico_success">O Actividade '.$_POST['entidade']. ' foi submetida com sucesso. </span></div>'; echo "<meta http-equiv='refresh' content='4;URL=index2.php?pag=act'>";}?> <div id="espaco"><div id="tabledata" class="section">			<h2 class="ico_mug">Inserir Actividade <?php echo $ref = $_GET['ref']; ?></h2>           <form method="post" enctype="multipart/form-data" name="" action="">            <div id="campo1">Sub-Universo:</div>            <div id="campo2">                       <?php    $result = mysql_query("SELECT id_subuniverso, subuniverso, ref FROM tbl_sub_universo ORDER BY subuniverso ASC");    echo'<select name="sub_uni" id="subuniverso"  onchange="show()">    <option value="" size="35">..........Seleccione o Subuniverso..........</option>';    while( $row = mysql_fetch_array($result)){        $seleciona = $row[0] == $t_id ? "selected" : "";                echo "<option {$seleciona} value='{$row[0]}'>{$row[2]} - {$row[1]}</option>";        }        mysql_free_result( $result );       echo"</select>";	?>            </div>             <div style="clear: both;"></div>                    <?		$ref = $_GET['ref'];				if (isset($_GET['ref'])){						echo 'chonar';									switch($ref){				case "ACT":				break;								case "CIR":				break;								case "GAS":				break;									case "PRG":				break;													case "TUR":				break;			}						echo 'armando';					}else{			switch($referencia){				case "PAJ":				break;								case "CAM":				break;								case "RAP":				break;									case "TUR":				break;			}			}		?>            <div id="campo1">Entidade (titulo):</div>            <div id="campo2"><input name="entidade" type="text" value="" size="30" /> </div>              <div id="campo1">Tipo Dados:</div>            <div id="campo2">                              <?php    $result = mysql_query("SELECT ref, descricao FROM tbl_referencia ORDER BY descricao ASC");    echo'<select name="referencia">    <option value="" size="35">..........Seleccione o Tipo de Dados..........</option>';    while( $row = mysql_fetch_array($result)){        $seleciona = $row[0] == $t_id ? "selected" : "";                echo "<option {$seleciona} value='{$row[0]}'>{$row[1]}</option>";        }        mysql_free_result( $result );       echo"</select>";	?>            </div>           	<div style="clear: both;"></div>            <div id="campo1">Legenda Entidade:</div>            <div id="campo2"><input name="legenda" type="text" value="" size="30" /> </div>            <div id="campo1">Preço:</div>            <div id="campo2"><input name="preco" type="text" value="" size="30" /> </div>            <div style="clear: both;"></div>            <div id="campo1">Periodo de funcionamento:</div>            <div id="campo2"><input name="funcionamento" type="text" value="" size="88" /> </div>            <div style="clear: both;"></div>            <div id="campo1">Serviços:</div>            <div id="campo2"><input name="servicos" type="text" value="" size="88" /> </div>            <div style="clear: both;"></div>            <div id="campo1">Actividades:</div>            <div id="campo2"><textarea name="actividades" class="textarea2" type="text" value=""></textarea></div>            <div id="campo1">Descrição do Programa:</div>            <div id="campo2"><textarea name="programa" class="textarea2" type="text" value=""></textarea> </div>            <div style="clear: both;"></div>            <div id="campo1">Localização:</div>            <div id="campo2"><textarea name="localizacao" class="textarea2" type="text" value=""></textarea></div>            <div id="campo1">Nº Pessoa p/ Actividade:</div>            <div id="campo2">              <input name="pess" type="text" value=""  size="4"/>            </div>            <div style="clear: both;"></div>            <div id="campo1">Imagem 1:</div>            <div id="campo2"><input name="arquivo[]" type="file" class="content-box-header" id="arquivo[]" value="" /> </div>            <div id="campo1">Imagem 2:</div>            <div id="campo2"><input name="arquivo[]" type="file" class="content-box-header" id="arquivo[]" value="" /> </div>            <div style="clear: both;"></div>            <div id="campo1">Imagem 3:</div>            <div id="campo2"><input name="arquivo[]" type="file" class="content-box-header" id="arquivo[]" value="" /> </div>            <div id="campo1">Imagem 4:</div>            <div id="campo2"><input name="arquivo[]" type="file" class="content-box-header" id="arquivo[]" value="" /> </div>            <div style="clear: both;"></div>            <div id="campo1">Imagem 5:</div>            <div id="campo2"><input name="arquivo[]" type="file" class="content-box-header" id="arquivo[]" value="" /> </div>            <div id="campo1">Imagem 6:</div>            <div id="campo2"><input name="arquivo[]" type="file" class="content-box-header" id="arquivo[]" value="" /> </div>            <div style="clear: both;"></div>            <div id="campo1">Descrição do Local:</div>            <div id="campo2"><textarea name="descricao" rows="5" class="textarea1" type="text" value=""></textarea></div>            <div style="clear: both;"></div>              <div id="campo1">Informações Úteis do Local:</div>            <div id="campo2"><textarea name="informacao" rows="5" class="textarea1" type="text" value=""></textarea></div>            <div style="clear: both;"></div>              <div id="campo1">Pontos de interesse da area:</div>            <div id="campo2"><textarea name="interesse" rows="5" class="textarea1" type="text" value=""></textarea></div>            <div style="clear: both;"></div><div id="botao"> <input input name="submit" type="submit" value="Guardar" /></div>                      <div style="clear: both;"></div>            </form>					</div> <!-- end #tabledata -->            </div>
Link to comment
Share on other sites

Well, there are several problems with this.

 

Here is what you're doing:

 

url: 'inser_actividade.php',

type: 'GET',

data: {ref : ref},

 

So you're sending a get request to that page, and you're sending a parameter called "ref". You have a bunch of PHP code on that page that is copying an uploaded image file, but that is never going to run, right now you can't upload files via ajax and you're checking for $_REQUEST['submit'], which doesn't exist. The only thing that is set is $_REQUEST['ref'] (or $_GET['ref']). So none of that image uploading code is going to run.

 

Before that, at the top, you have a bunch of Javascript. You can return Javascript code in an ajax response, but that code does not automatically run. If you want to run Javascript code an in ajax response handler you need to either use eval or create a new script element, set the contents of it to the code, and add it to the page. Using innerHTML to put that content on the page will not execute the code. So I don't see a reason to output that Javascript code at all.

 

After the PHP code that processes the uploaded file, you output some HTML code that includes a form with several files to upload and some other fields. Some of that code isn't doing anything, you have 2 switch statements which don't do anything. You also have several elements with the same ID, you have several divs that either have the ID "campo1" or "campo2". It's not correct to have more than one element with any ID, it sounds like you want to use a class there instead of an ID if the purpose is CSS styling.

 

So, I'm not real sure what you're trying to do. If you're sending that ajax request then $_GET['ref'] is going to contain whatever value the ref variable has. You can do whatever you want in that PHP page, but with all of that Javascript and form processing code I'm not sure what you're trying to do with the ref value. If you replace all of that code with just this:

 

 

<?php echo 'ref is ' . $_GET['ref'];

 

then when you run that ajax request you will see that message in the console for the page response. You can get the response text in the ajax response handler also.

Link to comment
Share on other sites

humm...

 

well, the $_REQUEST['submit'], only runs when you click the button to submit to upload the form values to database. All this form is working correctly.what I'm trying to do is when you select an option in select box the value of the option chosen by me is passed to the ajax Now I want the ajax return me the value for the page to be able to use the switch for each of the options reference for example if you choose ACT it will show only the fields for the ACT option.

Can you help me

Link to comment
Share on other sites

You need to write the PHP code to do that then, if the select value is the ref variable then you need your code to look up $_GET['ref'] (or $_POST['ref'] depending on the request), and look up the options for that value in the database or wherever else you get them, and the output of that PHP script should only be the options. Right now the output is a bunch of Javascript code plus the entire form. You are only supposed to return the list of option elements. In the ajax response handler you should be able to set the select element's innerHTML property to the list of options to update the dropdown.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...