por qué no está funcionando. Estoy tratando de llamar a un archivo php cuando se hace clic en un botón con algunos parámetros. Se ejecuta hasta la declaración de alerta en jsfile.js. Después de eso, la parte de ajax no se ejecuta... Ayúdenme... Gracias de antemano...
principal.html
<!DOCTYPE html> <html> <head> <title></title> <script src="jsfile.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </head> <body> <button onclick="cart(0)"> hi </button> <p id="disp"></p> </body> </html>jsfile.js
function cart(id1) { var id=id1; alert("enterd "+id); document.getElementById("disp").innerHTML ="hi"; $.ajax({ url:"/add.php ", type:"POST", data:{ item_id: id, }, success:function(response) { //document.getElementById("total_items").value=response; document.getElementById("disp").innerHTML =response; }, error:function(){ alert("error"); } }); }añadir.php
<?php if(isset($_POST['item_id']) && !empty($_POST['item_id'])){ //if(count($_POST)>0) echo "success"; exit(); } ?>En su archivo jsfile.js, corrija los siguientes puntos que mencioné como comentarios en el siguiente código.
function cart(id1) { var id=id1; alert("enterd "+id); document.getElementById("disp").innerHTML ="hi"; $.ajax({ url:"/add.php ", method:"POST", //First change type to method here data:{ item_id: id, }, success:function(response) { document.getElementById("disp").innerHTML =response; }, error:function(){ alert("error"); } }); }Cambialo y prueba
type:"POST" -> method: "POST"Si su versión de jquery es> = 1.5, utilícela de esta manera.
$.ajax({ url: "add.php", method: "POST", data: { item_id: id}, }).done(function(response) { ...... }).fail(function( jqXHR, textStatus ) { ...... });Cargue Jquery antes de su archivo JS.